In my application I use JOptionPane.showConfirmDialog() at several places.
I now have the requirement to prevent it from focusing a button, so that when a user presses <Enter>, the dialog remains.
Is there a way to do this without having to write my own extension of dialog?
To clarify: the main issue is that it may not close when the user presses enter. The dialog not focusing is merely an obvious way of accomplishing that.
If you set custom buttons and set the initial button value to null, it will give you the behavior you want: no initially focused button, so pressing the Enter key will not do anything.
See the below example:
public class Test {
public static void main(final String[] args) {
final Object[] options = { "OK", "Cancel" };
JOptionPane.showOptionDialog(null, "Enter won't work.", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options,
null); // this is the trick
JOptionPane.showOptionDialog(null, "Can press Enter.", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
}
Related
I am working with Swing right now and I do not get this to work properly.
What I need is the following:
I've got a class "Client" that is able to connect to a TCP server.
If the connection fails (wrong IP for example), then it will show an error dialog that can be closed by clicking on the "OK" Button.
However if the client connected successfully, a window should popup that runs until my client receives a specific message from the server.
My code looks like this:
if(ip != null) {
Client c = new Client();
try{
c.connect(ip, 56556);
JOptionPane msg = new JOptionPane("Connecting...", JOptionPane.INFORMATION_MESSAGE);
JDialog dlg = msg.createDialog("Connecting...");
dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dlg.setVisible(true);
c.addIncomingMessageHandler(new IncomingMessageHandler(){
#Override
public void incomingMessage(Connection<?> cnctn, Object o) {
dlg.setVisible(false);
dlg.dispose();
}
});
}catch(Exception e) {
int n = JOptionPane.showOptionDialog(this, "Oops! Something went wrong!",
"Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
null, new Object[] {"OK"}, JOptionPane.OK_OPTION);
}
}
So the exception is throws if c.connect() fails.
c.addIncomingMessageHandler() is a listener that listens to any incoming messages to the client. If the server sends something, this method will be called. If that's the case, the JDialog will be closed. But this window can be closed right now by clicking on the OK-Button.
I'd like to rename that button and add a function.
The new text should be "Cancel" and if the button is pressed, the client should be closed (c.disconnect) and the window itself should be closed as well.
How could I do that?
From the Documentation:
Stopping Automatic Dialog Closing
By default, when the user clicks a JOptionPane-created button, the dialog closes. But what if you want to check the user's answer before closing the dialog? In this case, you must implement your own property change listener so that when the user clicks a button, the dialog does not automatically close.
DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yes/No JOptionPane. Though this dialog is rather useless as written, its code is simple enough that you can use it as a template for more complex dialogs.
Besides setting the property change listener, the following code also calls the JDialog's setDefaultCloseOperation method and implements a window listener that handles the window close attempt properly. If you do not care to be notified when the user closes the window explicitly, then ignore the bold code.
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
final JDialog dialog = new JDialog(frame,
"Click a button",
true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
setLabel("Thwarted user attempt to close window.");
}
});
optionPane.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (dialog.isVisible()
&& (e.getSource() == optionPane)
&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
//If you were going to check something
//before closing the window, you'd do
//it here.
dialog.setVisible(false);
}
}
});
dialog.pack();
dialog.setVisible(true);
int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
setLabel("Try using the window decorations "
+ "to close the non-auto-closing dialog. "
+ "You can't!");
}
Click here!
Related question.
I am working on a program that shows the following menu (menu_image) when it starts. I have a little problem: I'd want to show it on the top of the other windows, but I am not able to achieve this.
class Menu {
public String showMenu(){
Object[] options = {"option1", "option2", "option3"};
Object selectionObject = JOptionPane.showInputDialog(null, "Choose", "Menu", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
String selectionString = selectionObject.toString();
return selectionString;
}
}
Can someone help me, please? Thank you in advance
Based on Berger's suggestion, I solved my problem in the following way...
class Menu {
public String showMenu(){
//i solved my problem adding the following 2 lines of code...
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
Object[] options = {"option1", "option2", "option3"};
//...and passing `frame` instead of `null` as first parameter
Object selectionObject = JOptionPane.showInputDialog(frame, "Choose", "Menu", JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
String selectionString = selectionObject.toString();
return selectionString;
}
}
How can I create a MessageDialog that is resizable.
Shell parentShell = Display.getCurrent().getActiveShell();
MessageDialog.openInformation(parentShell, "title", "message");
The information dialog cannot be changed in size. How to make it resizable?
The MessageDialog is not meant to be resizable. If you really really want to make it resizeable, override the getShellStyle() method to return the desired style flags.
For example
MessageDialog dialog = new MessageDialog( shell,
"title",
null,
"message",
MessageDialog.INFORMATION,
new String[] { IDialogConstants.OK_LABEL },
0 )
{
protected int getShellStyle() {
return SWT.SHELL_TRIM;
}
};
will result in a resizable dialog with an information icon and min/max/close buttons.
I've designed (using the GUI designer within Netbeans) a small dialog with two radio buttons and a number spinner.
If I press Enter while the focus is on one of the radio buttons, the dialog correctly closes, but if the focus is on the spinner, I have to Tab away from it in order to use the Enter key.
How do I instruct the dialog that Enter really means "accept and close"?
Alternatively, how do I instruct (each) input field to relay an Enter to the "accept and close" handler?
Similarly, how do I instruct the dialog that Esc really means "cancel and close" even when the focus is on the spinner (or other field)?
how do I instruct (each) input field to relay an Enter to the "accept and close" handler?
The easiest approach is to define a "default button" on the dialog. Then when Enter is pressed the default button will be activated. Check out Enter Key and Button for different ways to do this.
how do I instruct the dialog that Esc really means "cancel and close"
Use Key Bindings to invoke the Action of your Cancel button.
First you define an Action to be used by the button:
public class CancelAction extends AbstractAction
{
public CancelAction()
{
super("Cancel");
putValue( Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_C) );
}
#Override
public void actionPerformed(ActionEvent e)
{
Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
if (window != null)
{
WindowEvent windowClosing = new WindowEvent(window, WindowEvent.WINDOW_CLOSING);
window.dispatchEvent(windowClosing);
}
}
}
Then you add the Action to the button so the user can use the mouse:
CancelAction cancelAction = new CancelAction();
cancelButton.setAction( cancelAction );
dialog.add(cancelButton);
Now you can use Key Bindings to bind the Escape key to the CancelAction so the user can use the keyboard:
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
getRootPane().getActionMap().put("ESCAPE", cancelAction);
I suspect the reason I had problems is that a spinner is really a compound control, and the text (well, number) field is an component of that. So I needed to hook up the events to that subcomponent, rather than to the spinner itself:
// Make Ok/Cancel work when JSpinner has focus
getSpinnerField(jSpinnerOffset).addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
doOk();
}
});
where "getSpinnerField()" is just a shorthand in a private method:
private JFormattedTextField getSpinnerField(JSpinner spinner) {
return ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
}
Doing this, the Esc key automagically becomes able to dismiss the dialog.
I know that in order to prevent JOptionpane from hiding behind any of the frame we have to give the current frame as parent frame to JOptionpane.
I have a JTree with popupmenu
it has popup menu follows
Add
Rename
Delete
when I click the delete menu i'll call the showDeleteConfirmation() to confirm the action to delete or not
But the problem if I use currentMainframe(the one which jtree is present) as parent frame for JOptionpane and when I click the JPopumenu is not hiding(still in focus) so I have to click on Joptionpane once (to hide the popupmenu) and then only I can select the options
If I use null as parentframe it is working perfectly(onclicking the the menuitem it is automatically hiding).
How to solve the issue
//Have to click anywhere on JOptionpane to gain focus(also to hide popupmenu)
public static Boolean showDeleteConfirmation() {
if (deleteConfirmation) {
int value = JOptionPane.showConfirmDialog(currentMainFrame, "Are you sure want to delete?", "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
return value == JOptionPane.YES_OPTION;
}
return true;
}
//This is working perfectly
public static Boolean showDeleteConfirmation() {
if (deleteConfirmation) {
int value = JOptionPane.showConfirmDialog(null, "Are you sure want to delete?", "Delete", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
return value == JOptionPane.YES_OPTION;
}
return true;
}
I manually called JPopupmenu.hide() before calling that function.It solved the problem