Also, right now whenever I click the 'X" button on top right, the dialog boxes behaves as if I clicked OK (on messages) or YES (on questions). When the user clicks the X, I want DO_Nothing.
In the code below, when i click on the X on the dialog box, it pops out the 'eat!'. Apparently, the X is acting as 'YES' Option, which it should not.
int c =JOptionPane.showConfirmDialog(null, "Are you hungry?", "1", JOptionPane.YES_NO_OPTION);
if(c==JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else {JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);}
Changed to show how to ignore the cancel button on Dialog box per OP clarification of question:
JOptionPane pane = new JOptionPane("Are you hungry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
JDialog dialog = pane.createDialog("Title");
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
}
});
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();
dialog.setVisible(true);
int c = ((Integer)pane.getValue()).intValue();
if(c == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else if (c == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);
}
You can't do what you want through the usual JOptionPane.show* methods.
You have to do something like this:
public static int showConfirmDialog(Component parentComponent,
Object message, String title, int optionType)
{
JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
optionType);
final JDialog dialog = pane.createDialog(parentComponent, title);
dialog.setVisible(false) ;
dialog.setLocationRelativeTo(parentComponent);
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModal(true);
dialog.setVisible(true) ;
dialog.dispose();
Object o = pane.getValue();
if (o instanceof Integer) {
return (Integer)o;
}
return JOptionPane.CLOSED_OPTION;
}
The line that actually disables the close button is:
dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
Related
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);
}
}
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.
I'd like to replace the icon in a JOptionPane title bar (as it currently shows the default Java coffee logo).
I tried the following:
JOptionPane.showMessageDialog(null, "Some Text", "Login",
JOptionPane.INFORMATION_MESSAGE, ImageCacheProvider
.instance.getImageIcon("img/an image.png"));
It replaces the icon in the window but not the one in the title bar:
Is there any approach to change the icon in the title bar or alternatively to hide the default Java icon without having to implement a JDialog class?
Thanks a bunch!
Thomas
Use it like this:
Icon icon = new ImageIcon("d:/temp/CheckBox.gif");
JOptionPane jp = new JOptionPane("Session Expired - Please Re Login"),
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
icon);
JDialog dialog = jp.createDialog(null, "Session Expired - Please Re Login");
((Frame)dialog.getParent()).setIconImage(((ImageIcon)icon).getImage());
dialog.setResizable(true);
dialog.setVisible(true);
This worked well for me:
private static final Image myImage = ...;
/*
* Copied from javax.swing.JOptionPane.showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)
*/
#SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException {
JOptionPane pane = new JOptionPane(message, messageType, optionType, icon, options, initialValue);
pane.setInitialValue(initialValue);
JDialog dialog = pane.createDialog(parentComponent, title);
// Added this line
dialog.setIconImage(myImage);
pane.selectInitialValue();
dialog.show();
dialog.dispose();
Object selectedValue = pane.getValue();
if (selectedValue == null)
return JOptionPane.CLOSED_OPTION;
if (options == null) {
if (selectedValue instanceof Integer)
return ((Integer) selectedValue).intValue();
return JOptionPane.CLOSED_OPTION;
}
for (int counter = 0, maxCounter = options.length; counter < maxCounter; counter++) {
if (options[counter].equals(selectedValue))
return counter;
}
return JOptionPane.CLOSED_OPTION;
}
When my JButton is clicked 5 times I want to show a dialog asking if the user wants more questions
Yes or No
Yes should reset counter to 0 and allow more questions to be asked,
No should close out program when Clicked in the dialog box.
The way I have it now is resetting counter to 0 and I am not sure where to add the
System.exit(0);
here is my code
b1.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e)
{
clicked++;
if (clicked >= 5) {
Object[] options = {
"No, thanks",
"Yes, please"
};
JOptionPane.showOptionDialog(frame,
"Would you like more math questions? ",
"Math Questions",
JOptionPane.YES_NO_CANCEL_OPTION, System.exit(0);
JOptionPane.QUESTION_MESSAGE,
null,
options ,
options[1]);
} else {
clicked = 0;
}
}
});
b1.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e)
{
clicked++;
if (clicked >= 5) {
Object[] options = {
"No, thanks",
"Yes, please"
};
int response = JOptionPane.showOptionDialog(frame,
"Would you like more math questions? ",
"Math Questions",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options ,
options[1]);
if (response == 1)
clicked = 0; //reset
else
System.exit(0);
}
}
});
I was wondering how inputdialog returns value especially when there are also ok and cancel buttons.
Could somebody explain how does it manage to return value?
UPDATE:
Let me put it this way.
I want to create a dialog with 6 buttons and each button returns different value.
And i want it get that value like this:
String value = MyDialog.getValue(); // like showInputDialog
the problem is how do i return value on button press?
Now that I have a clearer understanding of your goal, I think instead of trying to emulate JOptionPane, it would be easier to just give each button a different actionCommand:
private JDialog dialog;
private String inputValue;
String showPromptDialog(Frame parent) {
dialog = new JDialog(parent, true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// [add components to dialog here]
firstButton.setAction(new ButtonAction("Button 1", "first"));
secondButton.setAction(new ButtonAction("Button 2", "second"));
thirdButton.setAction(new ButtonAction("Button 3", "third"));
fourthButton.setAction(new ButtonAction("Button 4", "fourth"));
fifthButton.setAction(new ButtonAction("Button 5", "fifth"));
sixthButton.setAction(new ButtonAction("Button 6", "sixth"));
dialog.pack();
dialog.setLocationRelativeTo(parent);
inputValue = null;
dialog.setVisible(true);
return inputValue;
}
private class ButtonAction
extends AbstractAction {
private static final long serialVersionUID = 1;
ButtonAction(String text,
String actionCommand) {
super(text);
putValue(ACTION_COMMAND_KEY, actionCommand);
}
public void actionPerformed(ActionEvent event) {
inputValue = event.getActionCommand();
dialog.dispose();
}
}
From the Java tutorials
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
You might like to familiarise yourself with the section on "Getting the User's Input from a Dialog"
You should also familiarise yourself with the Java Docs on the same subject