I'm trying to get the value returned by custom buttons passed to JOptionPane. However the buttons I pass don't return a value at all. Only when the exit button is pressed is a value of -1 returned. I need this because I am changing the properties of the buttons enabled or disabled. I assume I need the buttons to return some information to the JOptionPane in some way. Any idea?
JButton button1= new JButton("Button 1");
JButton button2= new JButton("Button 2");
button1.setEnabled(false);
int value = JOptionPane.showOptionDialog(null, "Heres a test message", "Test", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1);
JOptionPane.showMessageDialog(null, "You entered " + value);
Nb This is related to my previous question - JOptionPane Grey Out One Button
I tried setting the value of the buttons like you said but they never return OK or CANCEL.
Whenever checking the value of the buttons, they never return the value I set them too.
JButton button1= new JButton("Button1");
JButton button2= new JButton("Button2");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.OK_OPTION);
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.CANCEL_OPTION);
}
});
if (JOptionPane.showOptionDialog(null, "Pick a button", "Pick", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1) == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Button1");
}
else{
JOptionPane.showMessageDialog(null, "Button2");
}
See above, always I get the button2 popup no matter what.
In the example I linked to you previous question, the buttons use the JOptionPane#setValue method to set the return value. This allows you to continue using the API as normal, while providing you with the customisation your after.
final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.OK_OPTION);
}
});
Take a closer look at Disable ok button on JOptionPane.dialog until user gives an input
Updated
I've gone back through the code and correct the actionPerformed methods to enable it to return a valid value...
final JButton okay = new JButton("Ok");
okay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(okay);
}
});
okay.setEnabled(false);
final JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
pane.setValue(cancel);
}
});
The value returned by the index of the value in the options array (last parameter)
So, for example...
int value = JOptionPane.showOptionDialog(
null,
field,
"Get",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
new Object[]{okay, cancel},
okay);
If the user clicks the okay button, the return value will be 0, or if they select the cancel button, it will be 1
If you need this complex behavior, consider creating your own JDialog and then displaying it in a modal fashion.
If you have to use a JOptionPane, you can do this by extracting its JDialog and recursively iterating through its components til you find the one you want to disable and disable it:
import java.awt.Component;
import java.awt.Container;
import javax.swing.*;
public class Foo2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
doRun();
}
});
}
public static void doRun() {
String[] options = {"Button 1", "Button 2", "Button 3"};
JOptionPane myOptionPane = new JOptionPane("Heres a test message",
JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION,
null, options, options[2]);
JDialog myDialog = myOptionPane.createDialog(null, "My Test");
myDialog.setModal(true);
inactivateOption(myDialog, options[1]);
myDialog.setVisible(true);
Object result = myOptionPane.getValue();
// Note: result might be null if the option is cancelled
System.out.println("result: " + result);
System.exit(0); // to stop Swing event thread
}
private static void inactivateOption(Container container, String text) {
Component[] comps = container.getComponents();
for (Component comp : comps) {
if (comp instanceof AbstractButton) {
AbstractButton btn = (AbstractButton) comp;
if (btn.getActionCommand().equals(text)) {
btn.setEnabled(false);
return;
}
} else if (comp instanceof Container) {
inactivateOption((Container) comp, text);
}
}
}
}
However for myself, I'd just create a JDialog.
You don't have to define your buttons explicitly.
int result = JOptionPane.showOptionDialog(this, "Are you sure you want to...?", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] { "Yes", "No" }, JOptionPane.NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
...
}
Related
I am relatively new to Java and have been trying to figure out a way to create a JOption window that not only has a drop down option with an "Ok" and "Cancel" button, but also adds an additional button called "Back." So far none of my attempts have successfully been able to add this Back button and every time I run the code it simply brings up the traditional dropdown/ok/cancel type window. Additionally I would also like the window to close when a button has been clicked, but I have been unsuccessful in that as well. Here is the code I have so far, not entirely sure what's missing/wrong with it:
public static String sampleWindow(){
JButton jbt_ok = new JButton("OK");
JButton jbt_back = new JButton("Back");
JButton jbt_cancel = new JButton("Cancel");
boolean greyOutBackButton = false;
jbt_ok.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("OK was clicked");
}
});
jbt_cancel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Cancel was clicked");
}
});
if(greyOutBackButton)
jbt_back.setEnabled(false);
else
jbt_back.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Back was clicked");
}
});
Object[] options = {jbt_ok, jbt_back, jbt_cancel};
Object selectionObject = JOptionPane.showInputDialog(null, "message", "", JOptionPane.DEFAULT_OPTION, null, options, options[0]);
if (selectionObject == null)
System.exit(0);
String selectionString = selectionObject.toString();
System.out.println("Selection String: "+ selectionString);
return selectionString;
}
I'm trying to put a conditional in a JDialog which detect if the two buttons in it are disabled. I need that also to close the dialog when it reach this condition so I found 2 problems. Example code:
public static String windowvisitAlert(JButton but, JButton but2, String message1, String message2) throws Exception, Exception {
String n = "";
Object[] options = {but, but2};
Object a = message1;
JOptionPane pane = new JOptionPane(a, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
JDialog dialog = pane.createDialog(message2);
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setSize(new Dimension(450, 10));
dialog.pack();
dialog.setVisible(true);
return n;
}
This is the method which creates a JDialog from a JPanel options. We have 2 buttons and 2 "messages" which only determinates the name of the dialog window.
I tried to put :
if (but.isEnabled()==false && but2.isEnabled()==false) {
dialog.setVisible(false);
}else{
dialog.setVisible(true);}
Also this method will return the value n so I don't know how will a condition work inside it.
Where i implement this method:
public void actionPerformed(ActionEvent e) {
final JButton but = new JButton("VISITA");
final JButton but2 = new JButton("RESPONSABLE");
try {
ActionListener actionListener2 = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//action performed
}
};
but.addActionListener(actionListener2);
but2.addActionListener(actionListener);
Alerts.windowvisitAlert(but, but2, Gui.getProperties().getProperty("text"), Gui.getProperties().getProperty("text"));
}catch (Exception ex) {
sc.functionSavingInLog(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]), ex.toString());
System.out.println(Utils.getClassInfo(Thread.currentThread().getStackTrace()[1]) + ex);
}
}
This is actually not working so my question is:
-How can I make this condition work and make the JDialog close when it hits it?
If not, how can I change the method or just do a jpanel?
I have a non-modal dialog with two input text fields shown with the JOptionPane with OK and CANCEL buttons. I show the dialog as below.
JTextField field_1 = new JTextField("Field 1");
JTextField field_2 = new JTextField("Field 2");
Object[] inputField = new Object[] { "Input 1", field_1,
"Input_2", field_2 };
JOptionPane optionPane = new JOptionPane(inputField,
JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(null, "Input Dialog");
dialog.setModal(false);
dialog.setVisible(true);
How can i get the return value from the dialog? Means i need to get whether Ok or CANCEL button is pressed. How can achieve this?
One way would be to add a ComponentListener to the dialog and listen for its visibility to change,
dialog.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) { }
#Override
public void componentMoved(ComponentEvent e) { }
#Override
public void componentShown(ComponentEvent e) { }
#Override
public void componentHidden(ComponentEvent e) {
if ((int) optionPane.getValue()
== JOptionPane.YES_OPTION) {
// do YES stuff...
} else if ((int) optionPane.getValue()
== JOptionPane.CANCEL_OPTION) {
// do CANCEL stuff...
} else {
throw new IllegalStateException(
"Unexpected Option");
}
}
});
Note: you should probably use the ComponentAdapter instead; I'm showing the whole interface for illustration.
Using getValue() will tell you how the dialog was closed. Since it's non-modal, you'll need to get that information once the dialog is closed, probably using a Thread that will wait that your dialog is closed to return the information. You don't give any details on what needs that information, so using another Thread might not be the best solution for you.
I want to know how to cause a program to exit upon selecting the X button of a showMessageDialog dialog box.
Currently whenever I do this, it simply continues running the code or, in the case of confirm or option dialog boxes, selects the 'Yes' option. Is it possible to include this kind of command in the code for the dialog box? For example:
JOptionPane.showMessageDialog(null, "Your message here");
How would I edit the output so that the X button closes the program?
Will I have to change the showMessageDialog to another type of dialog box?
I dont know if is this what you want but i put a confirm box in a program:
(...)
import org.eclipse.swt.widgets.MessageBox;
(...)
createButton(buttons, "&Exit", "Exit", new MySelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent evt) {
MessageBox messageBox = new MessageBox(getShell(), SWT.YES | SWT.NO | SWT.ICON_QUESTION);
messageBox.setMessage("Are you sure?");
messageBox.setText("Exit");
if (messageBox.open() == SWT.YES) {
getParent().dispose();
}
}
});
And looking at online javadoc (java 6) or (java 1.4), you have another option:
Direct Use:
To create and use an JOptionPane directly, the standard pattern is roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
showMessageDialog() doesn't have a return value. Here is an example with showOptionsDialog().
public class Test
{
public static void main(String[] args){
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Test");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane.showOptionDialog(null,
"Your message here", "", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, new String[] {"OK"}, "OK");
if (result == JOptionPane.CLOSED_OPTION) {
frame.dispose();
}
}
});
panel.add(button);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
}
This might be a very simple thing that I'm overlooking, but I just can't seem to figure it out.
I have the following method that updates a JTable:
class TableModel extends AbstractTableModel {
public void updateTable() {
try {
// update table here
...
} catch (NullPointerException npe) {
isOpenDialog = true;
JOptionPane.showMessageDialog(null, "No active shares found on this IP!");
isOpenDialog = false;
}
}
}
However, I don't want isOpenDialog boolean to be set to false until the OK button on the message dialog is pressed, because if a user presses enter it will activate a KeyListener event on a textfield and it triggers that entire block of code again if it's set to false.
Part of the KeyListener code is shown below:
public class KeyReleased implements KeyListener {
...
#Override
public void keyReleased(KeyEvent ke) {
if(txtIPField.getText().matches(IPADDRESS_PATTERN)) {
validIP = true;
} else {
validIP = false;
}
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
if (validIP && !isOpenDialog) {
updateTable();
}
}
}
}
Does JOptionPane.showMessageDialog() have some sort of mechanism that prevents executing the next line until the OK button is pressed? Thank you.
The JOptionPane creates a modal dialog and so the line beyond it will by design not be called until the dialog has been dealt with (either one of the buttons have been pushed or the close menu button has been pressed).
More important, you shouldn't be using a KeyListener for this sort of thing. If you want to have a JTextField listen for press of the enter key, add an ActionListener to it.
An easy work around to suite your needs is the use of showConfirmDialog(...), over showMessageDialog(), this lets you take the input from the user and then proceed likewise. Do have a look at this example program, for clarification :-)
import javax.swing.*;
public class JOptionExample
{
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
int selection = JOptionPane.showConfirmDialog(
null
, "No active shares found on this IP!"
, "Selection : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
System.out.println("I be written" +
" after you close, the JOptionPane");
if (selection == JOptionPane.OK_OPTION)
{
// Code to use when OK is PRESSED.
System.out.println("Selected Option is OK : " + selection);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Code to use when CANCEL is PRESSED.
System.out.println("Selected Option Is CANCEL : " + selection);
}
}
});
}
}
You can get acces to the OK button if you create optionpanel and custom dialog. Here's an example of this kind of implementation:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author OZBORN
*/
public class TestyDialog {
static JFrame okno;
static JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
zrobOkno();
JButton przycisk =new JButton("Dialog");
przycisk.setSize(200,200);
panel.add(przycisk,BorderLayout.CENTER);
panel.setCursor(null);
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
przycisk.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor"));
final JOptionPane optionPane = new JOptionPane(
"U can close this dialog\n"
+ "by pressing ok button, close frame button or by clicking outside of the dialog box.\n"
+"Every time there will be action defined in the windowLostFocus function"
+ "Do you understand?",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION);
System.out.println(optionPane.getComponentCount());
przycisk.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
final JFrame aa=new JFrame();
final JDialog dialog = new JDialog(aa,"Click a button",false);
((JButton)((JPanel)optionPane.getComponents()[1]).getComponent(0)).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
aa.dispose();
}
});
dialog.setContentPane(optionPane);
dialog.pack();
dialog.addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowLostFocus(WindowEvent e) {
System.out.println("Zamykam");
aa.dispose();
}
#Override public void windowGainedFocus(WindowEvent e) {}
});
dialog.setVisible(true);
}
});
}
public static void zrobOkno(){
okno=new JFrame("Testy okno");
okno.setLocationRelativeTo(null);
okno.setSize(200,200);
okno.setPreferredSize(new Dimension(200,200));
okno.setVisible(true);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel();
panel.setPreferredSize(new Dimension(200,200));
panel.setLayout(new BorderLayout());
okno.add(panel);
}
}
Try this,
catch(NullPointerException ex){
Thread t = new Thread(new Runnable(){
public void run(){
isOpenDialog = true;
JOptionPane.setMessageDialog(Title,Content);
}
});
t.start();
t.join(); // Join will make the thread wait for t to finish its run method, before
executing the below lines
isOpenDialog = false;
}