How to get dynamic RadioButton tooltip in Java? - java

I have a group of JRadioButtons. Each of them points to a directory with only text files, when I mouse over them they should count how many files are in each directory and return the file count as tooltips, I can not set the tooltips when I created the buttons, how to get dynamic tooltips from them ?
I tried the following, but didn't work :
JRadioButton myButton=new JRadioButton("Test")
{
public static final long serialVersionUID=26362862L;
public String getToolTipText(MouseEvent evt)
{
return "123";
}
}

Override the getToolTipText() method of your radio buttons.
You can then use the File.listFiles(...) method to determine the number of files in the directory.
Edit:
It appears that when you override this method you need to manually register the component with the ToolTipManager:
ToolTipManager.sharedInstance().registerComponent(radioButton);

Related

Why is the ActionPerformed performed several times?

I have a small issue and I'm sure it's a stupid mistake but here I go.
I have a GUI containing amongst other objects a JComboBox and a JButton.
The ComboBox (called orderTypeChoices in my code) contains the names of objects in an "enum" called OrderType.
This is my enum :
public enum OrderType {
BUILD_SCREENING_CENTER,
INCREASE_TAXES,
RESEARCH_MEDICINE,
RESEARCH_VACCINE
}
In my code, there is a method called executeOrder that executes other code, depending on the OrderType. I'm pretty much sure the error isn't here.
The context is that I need to check in the JComboBox which item is selected, so when I click on the button, the executeOrder will use what's selected as Item.
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String orderName = (String) cloudPandemic.orderTypeChoices.getSelectedItem();
for (OrderType orderType : OrderType.values()) {
if (orderType.name().equals(orderName)) {
System.out.println(orderType.name());
cloudPandemic.executeButton.addActionListener(e1 -> cloudPandemic.simulation.executeOrder(OrderType.valueOf(orderName)));
break;
}
}
}
};
this.cloudPandemic.orderTypeChoices.addActionListener(actionListener);
So I added 2 ActionListeners (one to the ComboBox and the other to the Button). I store in a String the String name of the Item and check in my enum if one of the objects in it matches namewise. If it does, I add an ActionListener to the button, in which I use the method executeOrder. However, I've noticed that it tends to accumulate : If I choose at first one Item, it'll work, if I choose another Item, it'll execute on both this item and the first item i've chosen, etc.
I was wondering if I missed something, because I don't see why the ActionPerformed is executing past Actions.
Thanks in advance,
Fares.

JFace - How can I make only one column editable in TreeViewer based on checkbox value from another column in the same row?

I have a TreeViewer which has two columns: ProximityClustersColumn: which has names as String, selectionColumn: which has checkbox as shown in the figure
TreeViewer
I have two questions:
On clicking the selection column's checkbox, the corresponding name of ProximityClustersColumn should become editable.
For eg: When I click on the checkbox corresponding to "Studium organisieren-Formelles", the cell "Studium organisieren-Formelles" should become editable.
Also, as seen in the figure, a check must be made such that only one value in the group, whose checkbox is checked becomes editable.
In other words, for each group, only one category name can be checked and that corresponding name should be editable.
For eg:
If you look at the second group, there are two proximity Cluster names, i.e "Infos für Studis" and "Finanzielles im Studium", along with their respective checkboxes. Now, I can choose one among the two names, by selecting the corresponding checkbox. Suppose, I click on the checkbox corresponding to "Infos für Studis", only that cell should become editable.
The main idea is that : I should be able to select only one name from each group and edit it.
I have tried EditingSupport as suggested by #keyur, but the "canEdit" method is not called at all.
My LabelProvider extends ColumnLabelProvider and implements ITableLabelProvider. My ContentProvider implements ITreeContentProvider.
Is there any reason why EditingSupport will fail?
public class ProximityClustersEditingSupport extends EditingSupport{
private TreeViewer viewer;
private CellEditor editor;
public ProximityClustersEditingSupport(ColumnViewer columnViewer, TreeViewer treeViewer) {
super(columnViewer);
this.viewer = treeViewer;
this.editor = new TextCellEditor(treeViewer.getTree());
}
#Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor();
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
if(element instanceof ProbeSort)
return ((ProximityClusters)element).proximityClusterNames;
return element;
}
#Override
protected void setValue(Object element, Object value) {
if (element instanceof ProbeSort)
{
((ProximityClusters)element).setProximityClusterNames(String.valueOf(value));
}
viewer.update(element, null);
}
}
I think I need more information to answer it completely. First of all is that Treeviewer or Tableviewer. To me it looks like TableViewer.
What is the expected behavior of the cell when you mean editable. Those cells which are not editable should have disable type foreground colored text and the one which is editable can have normal foreground color say black. Only when user changes to focus (if tab is supported) or by clicking on the cell it is better to show the editable text where user can select the text and change/edit it. And pressing Enter key or Tab Key program can accept the change. Is that what you are looking for?
I guess I didnt get the question. Can you give example from the above figure. Like what is group?
I think EditingSupport will be useful for you.
You can create your concrete EditingSupport class and assign it to your column. It has method "canEdit" through which you can control the editing dynamically.
So what you have to do is to store the boolean flag in the model from checkbox status or read the check box status directly and return false/true value , which will enable/disable editing.
The program in the link shows all possible Tree viewer related implementations. Copy paste the program into a new java class and run as java application. This one example solved all tree related issues i had in my implementation.

Is there a way to disable all buttons with a method?

This is a lab for school that I'm struggling with, the code is making a game of hangman, and when the "brain" program says the game is over, all of the letter buttons are supposed to be disabled.
relevant code sections:
the buttons:
class ActionButton extends JButton implements ActionListener{
private String name;
private char t;
public ActionButton(String s){
super(s);
name = s;
t = name.charAt(0);
}
#Override
public void actionPerformed(ActionEvent e) {
ido.newLetter(t);
this.setEnabled(false);
LovesMePanel.this.update();
}
}
the update method:
public void update(){
answers = ido.getAnswer();
flower.setTriesLeft(ido.getTriesLeft());
progress.setText(answers);
if(ido.gameOver()){
// This is where I need to deactivate the buttons
if(ido.hasWon()){
}
}
else if(triesLeft == 0){
}
}
the buttons are all created in a loop in the LoveMePanel that holds all of the other panels. Is there a way to reference them all or disable them all when the game is over?
If not, how should I change my code so that it would be possible to do that?
If you put your buttons in a Collection, you can iterate through them and disable them all that way. I.e.,
for (JButton b : myButtons) {
b.setEnabled(false)
}
If not, you have 26 disable statements to write.
See the setEnabled() method for JButton. You can:
Add your Buttons to an ArrayList while creating them and then iterate over it and disable one by one
Get children of a JPanel, iterate over them, check if it's a button and disable it
Put a Glass Pane on top of your Burrons to intercept the incoming events
Feel free to choose the one you like best.
how about getting the children of the root panel by calling getComponents and iterating over them recursively and finding JButtons and disabling them as you find them?

GWT - how to get the tabText of selected tab?

I want to get the tab text when I click on a tab. I do this:
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
#Override
public void onSelection(SelectionEvent<Integer> event) {
//get the tabtext here
}
});
But I only get the index.
Assuming you are using TabPanel and you haven't provided a custom Widget for the TabBar, you could do this:
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
#Override
public void onSelection(SelectionEvent<Integer> event) {
String tabHtml = tabPanel.getTabBar().getTabHTML(event.getSelectedItem());
}
});
Of course, you will get the underlying HTML of the tab, that generally is a <div>tab text</div>. The text you put in the add() methods are wrapped in either a Label, or an HTML widget, whether you have chosen to display the tab text as HTML.
Of course this is not handy, generally you need to store somewhere the tab text (in a TabPanel extension I'd guess, or a model) at insertion time (overriding the add(...)s) and retrieve it when needed (by adding a simple getter for them).
You can get the selected tab by following.
tabPanel.getElement().getTitle();

I want to restrict the dimensions of images users can select with a JFileChooser

I have a JFileChooser that lets users choose an image for themselves. I want to limit the images they can choose to ones with square dimensions, for example -
width and height both 50
width and height both 75, etc...
So when they select an image with the JFileChooser and click 'Open' I need to validate the image size and if it doesn't have square dimensions I need to present the user with a dialog informing them "The image must have the same width and height".
I'm just learning swing so I don't know how to do this. Any ideas on how to do this? Is there a way of hooking the "Open" button's event handler?
You can hide all images that do not confirm to the rules with an implementation of a FileFilter:
JFileChooser fileChooser = new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());
// Open file dialog.
fileChooser.showOpenDialog(frame);
openFile(fileChooser.getSelectedFile());
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
// load the image
// check if it satisfies the criteria
// return boolean result
}
}
I tried overwriting
public void approveSelection ()
by deriving a own class from JFileChooser, and at first glance, it seemed to work.
The method is called, I can make a test on the selected file, and, if it fails, recall showOpenDialog (ref);.
But ...
It works fine, when I call a legitimate file, and it opens a new dialog, if not, but after that, the dialog won't close again normally, and if forced by the X of the window, I get a StackTrace printed. So I guess the state of the dialog is the critical thing here - it doesn't work if 'showOpenDialog' is called recursively.
Here is one of the variants I tested:
class ProportionalImageChooser extends JFileChooser
{
private Component ref;
public ProportionalImageChooser (File f)
{
super (f);
}
public int showOpenDialog (Component parent)
{
ref = parent;
return super.showOpenDialog (parent);
}
public void approveSelection () {
System.out.println ("approving selection!");
String fname = getSelectedFile ().getName ();
if (fname.matches (".*e.*")) {
cancelSelection ();
System.out.println ("Dialog: size doesn't match");
showOpenDialog (ref);
}
else super.approveSelection ();
}
}
To keep the test simple, I only tested the filename to include an 'e' or not.
So I suggest, use Boris' approach, and test your file after finishing the dialog. If it fails, immediately reopen a new one.

Categories