I have made a panel which contains two radio groups of buttons. You can find the result of JPanel in the image below. Then I used the below code to add this panel to a JOptionPane box:
OptionsForDisjunctionNodes optionsForDisjunctionNodes=new OptionsForDisjunctionNodes();
JPanel p=optionsForDisjunctionNodes.getPanel();
int option = JOptionPane.showConfirmDialog(null, p, "Decision on Disjunctive Nodes", JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.OK_OPTION == option) {
// Print selected radio button in each group. How?
} else {
// Do something else.
}
Let's say the name of group boxes are buttonGroup1, and buttonGroup2
I need to when the user click on Ok button, I print the selected label in both groups
Let OptionsForDisjunctionNodes add a listener to the radio buttons. And when pressed have it store whatever option was pressed last.
Then also provide getters on OptionsForDisjunctionNodes to retrieve this information.
Alternatively, you still provide getters in OptionsForDisjunctionNodes but have them loop over the button group to find which option is selected.
Check this stackoverflow question for ideas on how to do that exactly.
You could work with action commands on the JRadioButtons like this:
ButtonGroup buttonGroup1=new ButtonGroup();
JRadioButton r1=new JRadioButton();
JRadioButton r2=new JRadioButton();
r1.setActionCommand("hello");
buttonGroup1.add(r1);
buttonGroup1.add(r2);
your if would then look like this:
if (JOptionPane.OK_OPTION == option) {
System.out.println(buttonGroup1.getSelection().getActionCommand());
System.out.println(buttonGroup2.getSelection().getActionCommand());
} else {
}
for buttonGroup1 it would print hello in this case if r1 is selected
Related
I have 3 buttons
b1
b2
b3
I want to now have these buttons be pressed in turns.
So turn one I press and turn 2 another person presses.
So after turn two, I will compare the names of the buttons.
b1.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event ) {
b1.setEnabled(false);
if (!b1.isEnabled() && !b2.isEnabled()) {
//computeWinner(b1.getText(), b2.getText());
} else if(!b1.isEnabled() && !b3.isEnabled()) {
//computeWinner(b1.getText(), b2.getText());
}
}
});
This was what I thought would work, but there are many things wrong with this,
First, since I disable the buttons the second user always has one less option. and second the if statements do not seem to work? how should I compare the
JButton b3 = new JButton ("hello"); <- hello lable of the buttons?
EDIT:
I was able to successfully compare the two buttons. Now my only problem is that for the second player one of the buttons are disabled(how can I capture the first button press and the second without disabling them?). And that after the comparison I don't know how to reset the board to go again. (for a set number of loops.)
Thank you for the help!
The following code will print the label of the button which has been pressed. I hope, you should be able to proceed from here. Feel free to let me know if you face any further issue.
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
There are several options.
Store the buttons in a map<Integer, String>. the integer would be a count for keeping track of pushes. The string would be the actionCommand of the button pressed.
Store the button actionCommands in a list or array.
In either of the above you can provide appropriate logic to compare the buttons and then reset the arrays or map and count.
Note: The actionCommand defaults to the button label unless it explicitly set.
I'm new in Java swing, and I have a problem. I made for-loop for creating buttons and now I want automatically give them names or some kind of marks for future recognition (I will need name of clicked button to make it a variable).
How can I give them names in my loop? Thank you.
Here is code of my for-loop:
for (int aa=1; aa<65; aa++)
{
JButton button = new SquareButton("");
gui.add(button);
button.addActionListener((ActionListener) button);
}
I will need name of clicked button to make it a variable).
You don't need a variable to work with the clicked button. Instead you get a reference to the button that was clicked from the ActionListener code:
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
// do processing on the clicked button.
}
In my Java Swing application, I show a list of options to users using a JOptionPane with a JList, using the code below:
List<Object> options = getOptions();
JList list = new JList(options.toArray());
JScrollPane scrollpane = new JScrollPane();
JPanel panel = new JPanel();
panel.add(scrollpane);
scrollpane.getViewport().add(list);
JOptionPane.showMessageDialog(null, scrollpane,
"Please select an object", JOptionPane.PLAIN_MESSAGE);
How can I let the user select an option by double-clicking it?
JList doesn't provide any special handling of double or triple (or N) mouse clicks, but it's easy to add a MouseListener if you wish to take action on these events. Use the locationToIndex method to determine what cell was clicked. For example:
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
});
I just need to know how to close the dialog after the user
double-clicks the item
In this mouse event, you can make use of SwingUtilities.windowForComponent(list) to get the window and dispose it using window.dispose() function.
See List Action for a solution that will allow you to select an Item from the list with the mouse or the keyboard.
In the Action that you create you can use:
Window window = SwingUtilities.windowForComponent(...);
to get the window that you need to dispose();
I want to create this code :
The user enter a numerical value , if he entered character it will throw exception
the field will stop working then another frame show up and display error message
after the user close the new frame , everything return to the way it is
that means the field will work again !
I managed to make the field stop working but I didn't know if the user closed the new frame or not !
here is my try
public void keyReleased(KeyEvent event) {
try{
double l,h,w;
l=Double.parseDouble(input_length.getText());
w=Double.parseDouble("0"+input_width.getText());
h=Double.parseDouble("0"+input_width.getText());
}
catch(NumberFormatException a){
input_length.setEditable(false);
input_height.setEditable(false);
input_width.setEditable(false);
JFrame ErrorFrame = new JFrame("Error");
JPanel content = new JPanel(); ;
ErrorFrame.setContentPane(content);
ErrorFrame.setSize (350, 150);
ErrorFrame.setResizable (false);
ErrorFrame.setLocation (FRAME_X_ORIGIN, 250);
content.setLayout(new FlowLayout());
JLabel text = new JLabel(" ERROR ! please Enter number only ",JLabel.CENTER);
text.setFont(new Font("Arial", Font.PLAIN, 20));
text.setForeground(Color.red);
content.add(text);
ErrorFrame.setVisible(true);
setDefaultCloseOperation(ErrorFrame.EXIT_ON_CLOSE);
int op = ErrorFrame.getDefaultCloseOperation();
if(op == 1 ){
input_length.setEditable(true);
input_height.setEditable(true);
input_width.setEditable(true);}
}
}
1). Do not use new JFrame for error message - use JDialog Here is how
2). h=Double.parseDouble("0"+input_width.getText()); i think that you meant input_height.getText() here, not input_width.getText()
3). After showing your error dialog just clear your text fields - it is ok. When user will close it - he will see them empty.
If you would opt for a modal dialog to show the error message, there is no need to change the editable state of your fields.
Personally as a user I would become quite irritated if a dialog was shown each time I made a typo. For example changing the background color of the text field to red on invalid input, and disabling the OK button (or whatever mechanism you have as user to indicate you are finished editing) is more user-friendly IMO. You can even show a label indicating the errors in your panel, or a tooltip, ... .
I would also recommend a DocumentListener instead of a KeyListener if you want to react on updates of the text in the text field
An example on why I propose to opt for another mechanism to inform the user of the error:
I paste an invalid value in the textfield (e.g. 3x456) and a dialog pops up. Now I want to use my arrow keys to navigate to the error and correct it. This means I have to navigate 3 positions to the left to delete the x. If I use my arrow keys (which are keys as well) I will see this dialog 3 more times during the navigation.
I'm very new to Java and am having some issues looping through JCheckBoxes on a UI. The idea is that I have a bunch of checkboxes (not in a group because more than one can be selected.) When I click a JButton, I want to build a string containing the text from each selected checkbox. The issue I'm having is that our instructor told us that the checkboxes need to be created via a method, which means (see code below) that there isn't a discrete instance name for each checkbox. If there were, I could say something like
if(checkBox1.isSelected()) {
myString.append(checkBox.getText());
}
That would repeat for checkBox2, checkBox3, and so on. But the method provided to us for adding checkboxes to a panel looks like this:
public class CheckBoxPanel extends JPanel {
private static final long serialVersionUID = 1L;
public CheckBoxPanel(String title, String... options) {
setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(), title));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// make one checkbox for each option
for (String option : options) {
JCheckBox b = new JCheckBox(option);
b.setActionCommand(option);
add(b);
}
}
}
This is called like this:
toppingPanel = new CheckBoxPanel("Each Topping $1.50", "Tomato", "Green Pepper",
"Black Olives", "Mushrooms", "Extra Cheese",
"Pepperoni", "Sausage");
So I now have a panel that contains a border with the title "Each Topping $1.50", and 7 visible checkboxes. What I need to do is get a list of all the selected toppings. We are not supposed to use an ActionListener for each checkbox, but rather get the list when a button is clicked. I'm feeling really clueless here, but I just can't figure out how to get the isSelected property of the checkboxes when the individual checkboxes don't have instance names.
Ideally I'd like to somehow add all the checkboxes to an array and loop through the array in the button's action listener to determine which ones are checked, but if I have to check each one individually I will. I just can't figure out how to refer to an individual checkbox when they've been created dynamically.
I'm assuming you're not allowed to alter the CheckBoxPanel code at all. Which seems like a useless exercise, because in the real world, you'd think that if CheckBoxPanel where a class being provided to you (e.g. in a library) it would include a way of getting the selected options. Anyway, due to the limitation, you could do something like this:
for( int i=0; i<checkBoxPanel.getComponentCount(); i++ ) {
JCheckBox checkBox = (JCheckBox)checkBoxPanel.getComponent( i );
if( checkBox.isSelected() ) {
String option = checkBox.getText();
// append text, etc
}
}
I suggest you maintain a list of checkboxes:
List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
and before add(b) do:
checkboxes.add(b);
You may then iterate through the list of checkboxes in the buttons action-code using a "for-each" loop construct:
for (JCheckBox cb : checkboxes)
if (cb.isSelected())
process(cb.getText()); // or whatever.
Alternatively, if you need to keep track of the specific index:
for (int i = 0; i < checkboxes.size(); i++)
if (checkboxes.get(i).isSelected())
....
I would suggest that you dont put each of the checkboxes in a List when you create them. Instead, in your shared ActionListener, you maintain a Set of all selected checkboxes. Use the getSource method on the ActionEvent to identify which checkbox the user selected and then cast it to a JCheckBox. If isSelected() returns true for the item in question, attempt to add it to your selectedItems Set. If it is not, then attempt to remove it.
You can then just iterate over the subset of all items (only those that are selected) and print them to the console.