Closing JOptionPane after input option selected - java

I am using a JOptionPane and I want it to automatically close after a user has selected an option.
At present this is working but I still have to manually click the OK button to close the JOptionPane. Is there anyway I can close it when the checkbox is ticked
JPanel a1 = new JPanel();
a1.add(bubbleCheckBox);
a1.add(quickCheckBox);
a1.add(insertionCheckBox);
a1.add(selectionCheckBox);
// a1.add(mergeCheckBox);
arraySize=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter number of elements would like to sort (Recommend max =30)"));
JOptionPane.showMessageDialog(null, a1, "Choose an algorithm to run", DEFAULT_OPTION);
}
public static void lockCheckboxes(JCheckBox a) throws IOException, InterruptedException {
if (a == insertionCheckBox) {
selectionCheckBox.setEnabled(false);
quickCheckBox.setEnabled(false);
bubbleCheckBox.setEnabled(false);
mergeCheckBox.setEnabled(false);
SortAnimator.setArraySize(arraySize);
SortAnimator animator = new SortAnimator(new InsertionSorter());

This is slightly complicated.
First, add an ActionListener to your JCheckBox's...
When this ActionListener is triggered, you need to find the window which contains the JCheckBox, you need to find the instance of the JOptionPane, call setValue and pass it JOptionPane.OK_OPTION then dispose of the dialog
Something like...
JPanel a1 = new JPanel();
JCheckBox bubbleCheckBox = new JCheckBox("Bubbble");
JCheckBox quickCheckBox = new JCheckBox("Quick");
JCheckBox insertionCheckBox = new JCheckBox("Insert");
JCheckBox selectionCheckBox = new JCheckBox("Select");
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox cb = (JCheckBox) e.getSource();
JOptionPane op = (JOptionPane) SwingUtilities.getAncestorOfClass(JOptionPane.class, cb);
if (op != null) {
op.setValue(JOptionPane.OK_OPTION);
}
SwingUtilities.getWindowAncestor(cb).dispose();
}
};
bubbleCheckBox.addActionListener(al);
quickCheckBox.addActionListener(al);
insertionCheckBox.addActionListener(al);
selectionCheckBox.addActionListener(al);
a1.add(bubbleCheckBox);
a1.add(quickCheckBox);
a1.add(insertionCheckBox);
a1.add(selectionCheckBox);
// a1.add(mergeCheckBox);
if (JOptionPane.showConfirmDialog(null, a1, "Choose an algorithm to run", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) {
System.out.println("Yeah for me");
}
Personally, I'd use a JComboBox and just make the user select OK or Cancel

Related

JOptionPane Dialog Determine if Close Button was Clicked

I want to create a dialog with a checkbox and a combobox. This is what I have:
JCheckBox checkBox = new JCheckBox("My checkbox");
JLabel modeLabel = new JLabel("Select mode:");
String[] modes = {"A", "B", "C"};
JComboBox<String> modesComboBox = new JComboBox<>(modes);
JPanel modePanel = new JPanel(new FlowLayout());
modePanel.add(modeLabel);
modePanel.add(modesComboBox);
JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
dialogPanel.add(checkBox);
dialogPanel.add(modePanel);
JOptionPane.showMessageDialog(null, dialogPanel);
How do I determine whether the Close (i.e., "X") button or the OK button was clicked? I need to know which one of these two buttons caused the dialog to close.
Use JOptionPane.showConfirmDialog(Component,Object) (or overloaded equivalents) to get an int returned that reports yes, no or cancelled.
Calling showConfirmDialog..
Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option.
Parameters:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
message - the Object to display
Returns:
an integer indicating the option selected by the user
Edit
On closer inspection, it becomes apparent this task needs both a confirmation dialog and an option dialog. Here is a complete example that reports the results of the user choices to the console.
import javax.swing.*;
public class OptionSelection {
public OptionSelection() {
int result;
String[] modes = {"A", "B", "C"};
result = JOptionPane.showOptionDialog(
null,
"Modes",
"Select mode",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
modes,
"B"
);
if (result == JOptionPane.CLOSED_OPTION) {
System.out.println("User canceled mode selection");
} else {
System.out.println("Result: " + modes[result]);
}
result = JOptionPane.showConfirmDialog(null,
"Are you now, or have you ever?",
"Declaration",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
System.out.println("User says YES!");
} else if (result == JOptionPane.NO_OPTION) {
System.out.println("User says NO!");
} else {
System.out.println("User canceled");
}
}
public static void main(String[] args) {
Runnable r = () -> new OptionSelection();
SwingUtilities.invokeLater(r);
}
}

Adding multiple items to an action listener

I was wondering in someone could point me in the right direction for this. I have this simple calculator, where the user enters two numbers and then has to select an action (+, -, *, *) from a drop down menu.
After they select an option, it gives them an answer, but I was trying to add a check box to allow the result to be displayed as a float if the box was checked. I was confused on how to have the actionPreformed handle both the JCheckBox and the JComboBox. I tried just adding newCheckBox, but that causes casting errors, between JCheckBox and JComboBox.
public class Calculator2 implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JPanel xpanel;
String[] mathStrings = { "Multiply", "Subtraction", "Division", "Addition"}; //Options for drop down menu
JComboBox mathList = new JComboBox(mathStrings); //Create drop down menu and fill it
public Calculator2() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(); //New panel for the drop down menu
southPanel.setBorder(BorderFactory.createEtchedBorder());
JCheckBox newCheckBox = new JCheckBox("Show My Answer In Floating Point Format"); //Check box to allow user to view answer in floating point
southPanel.add(newCheckBox);
//newCheckBox.addActionListener(this);
southPanel.add(mathList);
mathList.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
//clear();
return ;
}
JComboBox comboSource = (JComboBox)event.getSource(); //Get the item picked from the drop down menu
String selectedItem = (String)comboSource.getSelectedItem();
if(selectedItem.equalsIgnoreCase("Multiply")) { //multiply selected
result.setText(Integer.toString(xVal*yVal));
}
else if(selectedItem.equalsIgnoreCase("Division")) { //division selected
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
//clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(selectedItem.equalsIgnoreCase("Subtraction")) { //subtraction selected
result.setText(Integer.toString(xVal-yVal));
}
else if(selectedItem.equalsIgnoreCase("Addition")) { //addition selected
result.setText(Integer.toString(xVal+yVal));
}
}
}
What I would recommend is that you keep a reference to the JCheckBox in the Calculator2 class. So something along the lines of
public class Calculator implements ActionListener {
...
JComboBox mathList = ...
JCheckBox useFloatCheckBox = ...
...
}
then in your actionPerformed mehtod, instead of getting the reference to the widget from event.getSource() get it directly from the reference in the class. So actionPerformed would look like this
public void actionPerformed(ActionEvent e) {
String operator = (String)this.mathList.getSelected();
boolean useFloat = this.useFloatCheckBox.isSelected();
...
}
This way you can use the same listener on both objects without having to worry about casting the widget.
The casting errors are because event.getSource() changes depending on which object fired the event. You can check the source of the event and process based on that:
if (event.getSource() instanceof JCheckBox) { ... act accordingly ... } else
Instead you could add a different ActionListener implementation to the JCheckBox so that the event it creates goes to a different place. An anonymous listener that sets a flag or calls a different method would work too.
There are other ways you could approach the problem, do you want the checkbox to affect an existing calculation, or only a new one? If only a new calculation you don't need an action listener on the checkbox, you can find out whether it is checked when you do the calculation:
if (myCheckbox.isSelected()) {
// do float calculation...
} else {
// do int calculation
}

How to close a JDialog through JButtons

I am making a method that gives the user three choices and returns the one they click, right now the method kinda works I click one of the options and if I click the close button it returns the last clicked. I want to to make it so that the dialog closes when you click one of the options
public E drawThreeForDecision()
{
ArrayList<E> c = new ArrayList<E>();
Component[] options = new Component[3];
for (int iii = 0; iii < 3; iii++)
{
final int loop = iii;
c.add((E) drawCard());
JButton button = new JButton(new ImageIcon(((GameEntity) c.get(iii)).getEntityImage()));
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
}
});
options[iii] = button;
}
JOptionPane pane = new JOptionPane("Please select a card", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
JDialog dialog = pane.createDialog(null, "DECISION TIME!");
dialog.setVisible(true);;
if (pane.getValue() instanceof Integer)
return (E) pane.getValue();
return c.get(0);
}
If anyone can help me with this or suggest a better solution it would be greatly appreciated!
Try these:
dialog.setModal(true);
dialog.setVisible(true);
use dialog.dispose(); inside the actionPerformed() method.

Items in ComboBox

I am tying to perform and action when an item in combo box are selected, but it performs an action no matter what item is selected.Can someone help me out please.
//number of players combo box
players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeFrame();
}
});
players.addItem("3 Players");
//end of combo box
In order to change behavior based on which item was selected, you will need to retrieve the selected value inside your ActionListener and change the behavior based on the selected value. You could use something like the following:
//number of players combo box
//notice that you have to declare players
//as final. If it is a member of the class,
//you can declare it final in the field
//declaration and initialize it in the
//constructor, or if local, just leave it
//as it is here. Unless using Java 8, then it
//doesn't need to be declared final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selectedValue = String.valueOf(players.getSelectedItem());
if (selectedValue != null && (selectedValue.equals("1 Player") || selectedValue.equals("2 Players"))) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box
If you happen to know the index ahead of time (i.e., you statically initialize the list of options instead of dynamically generating the list), you could also just refer to .getSelectedIndex() to retrieve the index as follows:
//number of players combo box
//the combo box still needs to be final here
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int myIndex = players.getSelectedIndex();
if (myIndex == 0 || myIndex == 1) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box

How to put both images and strings in the buttons of a JOptionPane

I'm trying to make a JOptionPane that has buttons with both images and text in them. JLabel and JButton both allow for both text and images at the same time, but using JLabel prevents actual buttons from showing up, whereas using JButton makes the buttons do nothing once clicked. The only way to make it work I've found is to use either String or ImageIcon by itself, and that's obviously not what I want.
JLabel[] members = {
new JLabel(one.name,one.image,JLabel.LEFT),
new JLabel(two.name,two.image,JLabel.LEFT),
new JLabel(three.name,three.image,JLabel.LEFT),
new JLabel(four.name,four.image,JLabel.LEFT),
new JLabel("Continue",new ImageIcon("mog.gif"),JLabel.LEFT)};
JButton[] members = {
new JButton(one.name,one.image),
new JButton(two.name,two.image),
new JButton(three.name,three.image),
new JButton(four.name,four.image),
new JButton("Continue",new ImageIcon("mog.gif"))};
String[] members = {
one.name,
two.name,
three.name,
four.name,
"Continue"};
choice= JOptionPane.showOptionDialog(null, "Here are your party members", "Party Members", JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE, new ImageIcon("mog.gif"), members, members[4]);
Does anybody know how to solve this?
The only way to make it work I've found is to use either String or ImageIcon by itself
Check out Compound Icon and Text Icon. You can create a custom icon with both your icon and text (represented as an icon):
import java.awt.*;
import javax.swing.*;
public class OptionPaneButton
{
private static void createAndShowUI()
{
ImageIcon icon = new ImageIcon("About16.gif");
JButton button = new JButton();
TextIcon text = new TextIcon(button, "Maybe");
CompoundIcon compound =
new CompoundIcon(CompoundIcon.Axis.X_AXIS, button.getIconTextGap(), icon, text);
Object options[] = {compound, "Not Now", "Go Away"};
int value = JOptionPane.showOptionDialog(null,
"Would you like some green eggs to go with that ham?",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
System.out.println(value);
if (value == JOptionPane.YES_OPTION)
{
System.out.println("Maybe");
}
else
{
System.out.println("Not today");
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Categories

Resources