making JOptionPane disappear - java

public void windowClosing (WindowEvent e)
{
JFrame frame = new JFrame();
int confirm = JOptionPane.showConfirmDialog (frame, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION)
{
dispose ();
}
else
{
frame.setVisible(false);
}
}
So when the user clicks on the close button, a JOptionPane pops up. When the user clicks on "No" the JOptionpane is supposed to disappear and then return to the frame it was originally displaying, but with my code, even when I click on No, both frames, the one for the JOptionPane and the one it sits on, disappear.
One thing:
I know I should not create a new JFrame for a JOptionPane, but I tried using this for the component, like: JOptionPane.showConfirmDialog (this, "...",...) when the user clicks on "No" the JOptionPane is the only thing that's supposed to disappear (so I set it to: this.setVisible(false);) but when I use this even the main frame disappears, so I just thought to create a new frame to meet my needs. I can't set it to null either because I need it to appear at the center of the screen. If anyone could advise me on how to handle this, please do.

It's really simple, your frame disappear because you say that it should not be visible, just remove that else:
public void windowClosing (WindowEvent e) {
int confirm = JOptionPane.showConfirmDialog (this, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
dispose();
}
}
EDIT:
Also replace setDefaultCloseOperation (EXIT_ON_CLOSE); with setDefaultCloseOperation (DO_NOTHING_ON_CLOSE);, else the main frame would close regardless of what happens in the windowClosing method.

Just don't put else if you don't want to hide the frame. The JOptionPane will disappear by itself, whether you click yes or no.

Don't create a new JFrame in the method. That's why you have random frame from now where.
public void windowClosing (WindowEvent e)
{
JFrame frame = new JFrame();
Pass the reference of the JFrame in question. If the code above is from a JDialog you can do something like this
public class MyDialog extends JDialog {
public MyDialog(final JFrame frame, boolean modal) {
super(frame, modal);
public void windowClosing (WindowEvent e) {
int confirm = JOptionPane.showConfirmDialog (frame, "Exit game?", "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
dispose ();
}
}
}
}
And just instantiate the JDialog like this from your GUI class with the JFrame
MyDialog dialog = new MyDialog(thisFrame, true);
Side Note
Why Even have a JOptionPane and a JDialog? Ultimately, a JDialog is just a custom JOptionPane, they have the same functionality.
EDIT
If you just want to pass the JFrame class as reference to the JOPtionPane just pass
MyFrameClass.this
instead of a new JFrame()
UDPATE
Test out this program using a simple custom JDialog.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogExample extends JFrame {
public JDialogExample() {
JButton exit = new JButton("Do you want to Exit?");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new HelloDialog(JDialogExample.this, true);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(exit);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private class HelloDialog extends JDialog {
public HelloDialog(final JFrame frame, boolean modal) {
super(frame, modal);
JButton exit = new JButton("EXIT");
JButton cancel = new JButton("CANCEL");
setLayout(new GridLayout(2, 1));
JPanel panel = new JPanel();
panel.add(exit);
panel.add(cancel);
add(new JLabel("Do you want to exit?", JLabel.CENTER));
add(panel);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JDialogExample();
}
});
}
}

Related

How do I call a GUI form from another Java class

So I have been figuring out how to make this work but I can't find , so I decided to look for help, the below is how my code look like,What I'm trying to do is display the Main Menu after the user refuse to proceed the tutorial and I tried to
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
public Login() {
String userName;
int option;
//This will ask user to input the username
userName = JOptionPane.showInputDialog(null,"Please enter your name","Welcome", JOptionPane.INFORMATION_MESSAGE);
//Display option
option =JOptionPane.showOptionDialog(null, "Welcome " + userName + "\n\nWould you like to have a tutorial about this game?",
"Welcome", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
//Ok to continue to the tutorial
if(option == JOptionPane.OK_OPTION)
{
//Call the tutorial class
}
This is where the code gone wrong and I tried to resolve with different ways
else //If select cancel will proceed to the Main menu
{
//This is the part I can't figure it out, it display different errors when I try different ways
that I searched from website
MainMenu MainMenuGUI = new MainMenu();
}
}
}
And here's my Main Menu code
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class MainMenu {
private JButton exitButton;
private JPanel MainMenu;
private JButton startButton;
private JButton historyButton;
public MainMenu() {
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int exitButton = JOptionPane.YES_NO_OPTION;
exitButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Warning", JOptionPane.YES_NO_OPTION);
if (exitButton == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
}
//Main Menu GUI setup
public static void main(String[] args) {
JFrame frame = new JFrame("Main Menu");
frame.setContentPane(new MainMenu().MainMenu);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setMinimumSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
}
}
Your current code has a couple of problems.
By creating the JFrame container in your main method, you're preventing the UI from ever showing up when instantiating MainMenu - that is, the UI will only show anything when the main method is invoked by the JVM. To fix this, I've moved your JFrame instantiation/setup into MainMenu's constructor.
In the MainMenu class, the mainMenu JPanel is never instantiated. This means your current code doesn't actually paint anything on the JFrame - you need to instantiate mainMenu and add your GUI controls to mainMenu.
The code below fixes both problems.
public class MainMenu
{
private JButton exitButton;
private JPanel mainMenu;
private JButton startButton;
private JButton historyButton;
public MainMenu()
{
JFrame frame = new JFrame("Main Menu");
///// mainMenu IS ALWAYS NULL WITHOUT THE NEXT LINE!!!!
this.mainMenu = new JPanel();
frame.setContentPane(this.mainMenu);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setMinimumSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
int exitButton = JOptionPane.YES_NO_OPTION;
exitButton = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Warning", JOptionPane.YES_NO_OPTION);
if (exitButton == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
}
//Main Menu GUI setup
public static void main(String[] args)
{
new MainMenu();
}
Get rid of the public static void main(String args[]) method in your MainMenu class. You only use the main method once in a java program. Instead, create a method like public void initUI() and place all the code you have inside the main() method in it.
And in your Login class, right after you call MainMenu MainMenuGUI = new MainMenu();
you can call MainMenuGUI.initUI().
One small thing, MainMenuGUI should probably be mainMenuGUI to properly follow camel case formatting and to avoid confusion later on.

JFrame: How to hide main window when button is clicked?

I have a simple code, what it does is first there's a Frame with a button, if you click the button a message dialog appears, how will I set the visibility of the main frame to false when the button is pressed, then set back the visibility to true when the user clicks 'Ok' in the message dialog
here's the code:
package something;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; //notice javax
public class Something extends JFrame implements ActionListener {
JLabel answer = new JLabel("");
JPanel pane = new JPanel();
JButton somethingButton = new JButton("Something");
Something() {
super("Something");
setBounds(100, 100, 300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane(); // inherit main frame
con.add(pane); // add the panel to frame
pane.add(somethingButton);
somethingButton.requestFocus();
somethingButton.addActionListener(this);
setVisible(true); // display this frame
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == somethingButton) {
answer.setText("Button pressed!");
JOptionPane.showMessageDialog(null, "Something", "Message Dialog",
JOptionPane.PLAIN_MESSAGE);
setVisible(true); // show something
}
}
public static void main(String args[]) {
Something something = new Something();
}
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == somethingButton) {
answer.setText("Button pressed!");
setVisible(false); // hide something
JOptionPane.showMessageDialog(this, "Something", "Message Dialog",JOptionPane.PLAIN_MESSAGE);
setVisible(true); // show something
}
}

how to show JOptionPane on the top of all windows

I have created a DialogUtil which shows numbers of JOptionPan in different situation.
sometimes in my action class call to this method with null parameters as below.
DialogUtil.showNotExist(null,xml.getName().concat(" is null or"));
In this case JOptionPane does not appears on the top of window.
How can I add something to JOptionPane to appears always on the top?
public static void showNotExist(JPanel panel, String action) {
JOptionPane.showMessageDialog(panel, new JLabel(action.concat(" doesn't exist."), 2));
}
Have you tried something like this?
JOptionPane optionPane = new JOptionPane();
JDialog dialog = optionPane.createDialog("Title");
dialog.setAlwaysOnTop(alwaysOnTop);
dialog.setVisible(true);
There is no guarantee that the operating system will allow your dialog to be always on top, but it will often work.
If you have an existing window or dialog and you want to bring it to the top, but don't want to permanently set alwaysOnTop, this should work while leaving the old value of alwaysOnTop alone:
boolean supported = window.isAlwaysOnTopSupported();
boolean old_alwaysOnTop = window.isAlwaysOnTop();
if (supported) {
window.setAlwaysOnTop(true);
}
window.toFront();
window.requestFocus();
if (supported) {
window.setAlwaysOnTop(old_alwaysOnTop);
}
Run that code only on the SwingThread.
You can set JOptionPane always on top by using this code:-
JFrame jf=new JFrame();
jf.setAlwaysOnTop(true);
int response = JOptionPane.showConfirmDialog(jf,"Message", "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
there are two possible issues
JOptionPane is called out of EDT, then only toolbar (caption that came from Native OS is visible on the screen, RootPane isn't visible) is visible on the screen
there you can to test JOptionPanes features, where JOptionPane.showInternalMessageDialog() makes troubles in all cases that there is another JDialog with setModal(true), real reason I dont know, same should be with ModalityTypes
not possible to showing two JOptionPanes on the screen in the same time
code
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.Timer;
//http://stackoverflow.com/questions/8670297/make-java-swing-modal-dialog-behave-like-mac-osx-dialogs
public class ModalDialogDemoFrame extends JFrame {
private static final long serialVersionUID = 1L;
private ModalDialogDemoFrame modalDialogDemo;
public ModalDialogDemoFrame() {
modalDialogDemo = this;
setBounds(100, 100, 400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonDialog = new JButton("Open Dialog");
buttonDialog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Create a Modal Dialog with this Frame as Parent.
ModalDialog modalDialog = new ModalDialog(modalDialogDemo, true);
modalDialog.setVisible(true);
}
});
getContentPane().add(buttonDialog, BorderLayout.CENTER);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ModalDialogDemoFrame window = new ModalDialogDemoFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
//http://stackoverflow.com/questions/4577424/distinguish-between-a-single-click-and-a-double-click-in-java/4577475#4577475
class ClickListener extends MouseAdapter implements ActionListener {
private final static int clickInterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
private MouseEvent lastEvent;
private Timer timer;
public ClickListener() {
this(clickInterval);
}
public ClickListener(int delay) {
timer = new Timer(delay, this);
}
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() > 2) {
return;
}
lastEvent = e;
if (timer.isRunning()) {
timer.stop();
doubleClick(lastEvent);
} else {
timer.restart();
}
}
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
singleClick(lastEvent);
}
public void singleClick(MouseEvent e) {
}
public void doubleClick(MouseEvent e) {
}
}
class ModalDialog extends JDialog {
private static final long serialVersionUID = 1L;
public ModalDialog(JFrame parent, boolean modal) {
Dimension dimensionParentFrame = parent.getSize();
setSize(new Dimension((parent == null) ? 300 : dimensionParentFrame.width / 2, 75));
Dimension dimensionDialog = getSize();
int x = parent.getX() + ((dimensionParentFrame.width - dimensionDialog.width) / 2);
setLocation(x, parent.getY() + parent.getInsets().top);
//setUndecorated(true);
setModal(modal);
//setUndecorated(true);
//getRootPane().setWindowDecorationStyle(JRootPane.ERROR_DIALOG);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final JButton buttonClose = new JButton("Close");
buttonClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//ok
/*JOptionPane.showMessageDialog(buttonClose,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);*/
//uncomment for un_handled GUI, JOptionPane is behing JFrame I think....
/*JOptionPane.showInternalMessageDialog(buttonClose,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);*/
//ok
/*JOptionPane.showConfirmDialog(buttonClose,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);*/
//ok
/*JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);*/
//uncomment for un_handled GUI
//Exception occurred during event dispatching:
//java.lang.RuntimeException: JOptionPane: parentComponent does not have a valid parent
/*JOptionPane.showInternalMessageDialog(null,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);*/
//ok
JOptionPane.showConfirmDialog(null,
"Eggs are not supposed to be green.",
"Inane warning",
JOptionPane.WARNING_MESSAGE);
dispose();
}
});
add(buttonClose, BorderLayout.CENTER); // comment for listening
addMouseListener(new ClickListener() {
#Override
public void singleClick(MouseEvent e) {
System.out.println("single");
}
#Override
public void doubleClick(MouseEvent e) {
System.out.println("double");
}
});
}
}
I don't know what WebOptionPane or WebPanel are, but if they're based on JOptionPane, then the issue is that you're passing null for that first argument to the showXXX() method. If you want the JOptionPane to be modal -- which forces it to be in front of a specified window -- then you need to specify a window (i.e., a JFrame -- for that first argument.
public static void showNotExist(JPanel panel, String action) {
JOptionPane.showMessageDialog(rootPane, new JLabel(action.concat(" doesn't exist."), 2));
}
Try giving the rootpane as the 1st value in the showMessageDialog section
If your class has extended JFrame, then just simply set the
class property setAlwaysOnTop(true); in anywhere in constructors before JOptionPane.showMessageDialog(null,"OKay");
I use it for copying file and check, don't even need a JFrame but JOptionPane.
P.S. If you don't want the main JFrame always shows on the top, then you need to create dummy JFrame or reset the property setAlwaysOnTop(false); after the JOptionPane.

Java keep frame focused

Could you please help me on this one? I have a JDialog with some textfields, checkboxes and buttons. I want that when the frame is not focused anymore, to disappear. So I added a focus listener to the JDialog and when the focus is lost, I call dialog.setVisible(false);. The problem is that if I click on the checkbox,textfield or button, the frame loses it's focus and disappears. How could I keep it focused until the user clicks outside it's area?
EDIT : The "frame" I am referring to is a JDialog. I don't use a Frame nor a JFrame. All the components are placed on the JDialog. I want it to hide when not focused, but keep it focused until the user clicks outside it's area.
Seems like you had added the wrong Listener, what you should be adding is addWindowFocusListener(...), see this small sample program, is this what you want to happen :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogFocus
{
private JFrame frame;
private MyDialog myDialog;
public DialogFocus()
{
}
private void createAndDisplayGUI()
{
frame = new JFrame("JFRAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
myDialog = new MyDialog(frame, "My Dialog", false);
JButton showButton = new JButton("SHOW DIALOG");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(myDialog.isShowing()))
myDialog.setVisible(true);
}
});
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DialogFocus().createAndDisplayGUI();
}
});
}
}
class MyDialog extends JDialog
{
private WindowFocusListener windowFocusListener;
public MyDialog(JFrame frame, String title, boolean isModal)
{
setTitle(title);
setModal(isModal);
JPanel contentPane = new JPanel();
JTextField tfield = new JTextField(10);
JComboBox cbox = new JComboBox();
cbox.addItem("One");
cbox.addItem("Two");
cbox.addItem("Three");
contentPane.add(tfield);
contentPane.add(cbox);
windowFocusListener = new WindowFocusListener()
{
public void windowGainedFocus(WindowEvent we)
{
}
public void windowLostFocus(WindowEvent we)
{
setVisible(false);
}
};
addWindowFocusListener(windowFocusListener);
add(contentPane);
pack();
}
}
Make the dialog modal, then the user cannot click on the frame.
Check the FocusEvent
it has public Component getOppositeComponent(). If the opposite component is child component of the JDialog don't hide the dialog.

action listener to JDialog for clicked button

I have main application where is table with values. Then, I click "Add" button, new CUSTOM (I made it myself) JDialog type popup comes up. There I can input value, make some ticks and click "Confirm". So I need to read that input from dialog, so I can add this value to table in main application.
How can I listen when "confirm" button is pressed, so I can read that value after that?
addISDialog = new AddISDialog();
addISDialog.setVisible(true);
addISDialog.setLocationRelativeTo(null);
//somekind of listener...
//after "Confirm" button in dialog was pressed, get value
value = addISDialog.ISName;
If the dialog will disappear after the user presses confirm:
and you wish to have the dialog behave as a modal JDialog, then it's easy, since you know where in the code your program will be as soon as the user is done dealing with the dialog -- it will be right after you call setVisible(true) on the dialog. So you simply query the dialog object for its state in the lines of code immediately after you call setVisible(true) on the dialog.
If you need to deal with a non-modal dialog, then you'll need to add a WindowListener to the dialog to be notified when the dialog's window has become invisible.
If the dialog is to stay open after the user presses confirm:
Then you should probably use a PropertyChangeListener as has been suggested above. Either that or give the dialog object a public method that allows outside classes the ability to add an ActionListener to the confirm button.
For more detail, please show us relevant bits of your code, or even better, an sscce.
For example to allow the JDialog class to accept outside listeners, you could give it a JTextField and a JButton:
class MyDialog extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
and a method that allows outside classes to add an ActionListener to the button:
public void addConfirmListener(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
Then an outside class can simply call the `addConfirmListener(...) method to add its ActionListener to the confirmBtn.
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OutsideListener extends JFrame {
private JTextField textField = new JTextField(10);
private JButton showDialogBtn = new JButton("Show Dialog");
private MyDialog myDialog = new MyDialog(this, "My Dialog");
public OutsideListener(String title) {
super(title);
textField.setEditable(false);
showDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!myDialog.isVisible()) {
myDialog.setVisible(true);
}
}
});
// !! add a listener to the dialog's button
myDialog.addConfirmListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = myDialog.getTextFieldText();
textField.setText(text);
}
});
JPanel panel = new JPanel();
panel.add(textField);
panel.add(showDialogBtn);
add(panel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
private static void createAndShowGui() {
JFrame frame = new OutsideListener("OutsideListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyDialog extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
public MyDialog(JFrame frame, String title) {
super(frame, title, false);
JPanel panel = new JPanel();
panel.add(textfield);
panel.add(confirmBtn);
add(panel);
pack();
setLocationRelativeTo(frame);
}
public String getTextFieldText() {
return textfield.getText();
}
public void addConfirmListener(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
}
Caveats though: I don't recommend subclassing JFrame or JDialog unless absolutely necessary. It was done here simply for the sake of brevity. I also myself prefer to use a modal dialog for solving this problem and just re-opening the dialog when needed.
Edit 2
An example of use of a Modal dialog:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class OutsideListener2 extends JFrame {
private JTextField textField = new JTextField(10);
private JButton showDialogBtn = new JButton("Show Dialog");
private MyDialog2 myDialog = new MyDialog2(this, "My Dialog");
public OutsideListener2(String title) {
super(title);
textField.setEditable(false);
showDialogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!myDialog.isVisible()) {
myDialog.setVisible(true);
textField.setText(myDialog.getTextFieldText());
}
}
});
JPanel panel = new JPanel();
panel.add(textField);
panel.add(showDialogBtn);
add(panel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
private static void createAndShowGui() {
JFrame frame = new OutsideListener2("OutsideListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyDialog2 extends JDialog {
private JTextField textfield = new JTextField(10);
private JButton confirmBtn = new JButton("Confirm");
public MyDialog2(JFrame frame, String title) {
super(frame, title, true); // !!!!! made into a modal dialog
JPanel panel = new JPanel();
panel.add(new JLabel("Please enter a number between 1 and 100:"));
panel.add(textfield);
panel.add(confirmBtn);
add(panel);
pack();
setLocationRelativeTo(frame);
ActionListener confirmListener = new ConfirmListener();
confirmBtn.addActionListener(confirmListener); // add listener
textfield.addActionListener(confirmListener );
}
public String getTextFieldText() {
return textfield.getText();
}
private class ConfirmListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = textfield.getText();
if (isTextValid(text)) {
MyDialog2.this.setVisible(false);
} else {
// show warning
String warning = "Data entered, \"" + text +
"\", is invalid. Please enter a number between 1 and 100";
JOptionPane.showMessageDialog(confirmBtn,
warning,
"Invalid Input", JOptionPane.ERROR_MESSAGE);
textfield.setText("");
textfield.requestFocusInWindow();
}
}
}
// true if data is a number between 1 and 100
public boolean isTextValid(String text) {
try {
int number = Integer.parseInt(text);
if (number > 0 && number <= 100) {
return true;
}
} catch (NumberFormatException e) {
// one of the few times it's OK to ignore an exception
}
return false;
}
}
Why don't you check if your jDialog is visible?
yourJD.setVisible(true);
while(yourJD.isVisible())try{Thread.sleep(50);}catch(InterruptedException e){}
this works, also.
import javax.swing.JOptionPane;
or if you're already swinging
import javax.swing.*;
will have you covered.
After conditional trigger JOptionPane to send your warning or whatever modal message:
JOptionPane.showMessageDialog(
null,
"Your warning String: I can't do that John",
"Window Title",
JOptionPane.ERROR_MESSAGE);
check your options for JOptionPane.* to determine message type.

Categories

Resources