I have a jdialog and want close it on confirmation after that store the data of a text box... now I have no problem to store the data from the box but,
How can I close this dialog after the operation???
Seems a simple thing but I haven't found the solution.
public class test extends JDialog {
private final JPanel contentPanel = new JPanel();
public test() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try{
int x=Integer.parseInt(textField.getText());
saver.saveN(x);
}catch(Exception ecc){
JOptionPane.showMessageDialog(Test.this,"error");
}
}
});
}
}
}
}
Either use Window#dispose or Window#setVisible(false).
if you use this dialog only once time then there is same to use dispose() as setVisible(false)
in the case that you invoke this method more than once time, then you can use HIDE_ON_CLOSE
or setVisible(false), better would be re_use this JDialog
EDIT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
private static final long serialVersionUID = 1L;
private JDialog dialog = new JDialog();
private final JPanel contentPanel = new JPanel();
private Timer timer1;
private JButton killkButton = new JButton("Kill JDialog");
public Test() {
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel buttonPane = new JPanel();
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
killkButton.setActionCommand("Kill JDialog");
buttonPane.add(killkButton);
dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
dialog.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
startTimer();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
dialog.setLayout(new BorderLayout());
dialog.getRootPane().setDefaultButton(okButton);
dialog.add(buttonPane, BorderLayout.SOUTH);
dialog.add(contentPanel, BorderLayout.CENTER);
dialog.pack();
dialog.setLocation(100, 100);
dialog.setVisible(true);
setKeyBindings();
}
private void setKeyBindings() {
killkButton.getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
killkButton.getActionMap().put("clickENTER", new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
}
If you plan to use a jDialog again with all the field values and component states left the same when you close it, use setVisible(false).
In any other case, call dispose(), to avoid the jDialog remaining in the memory when it is no longer required.
Related
I am making a game where the user has to press keys to move around. I am using keybindings but they are not working. The keybindings are supposed to call the Wp class and print "W pressed", but nothing happens. Here's the code:
public class SO extends JFrame {
public static void main(String[] args) {
new SO();
}
C c;
public SO(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
c=new C();
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("W"), "wp");
c.getActionMap().put("wp", new Wp());
this.setVisible(true);
}
private class C extends JComponent {
public void paint(Graphics g){}
}
private class Wp extends AbstractAction {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("W pressed");
}
}
}
Use Action to call like component.getActionMap().put("doSomething", anAction);
Refer Key Binding for more information. Below is a sample code I have referred in another Stackoverflow Question reference link SO Ref link
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonBinding {
private JPanel contentPane;
private JTextField tField;
private JButton button;
private KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
private Action action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Action Performed");
contentPane.setBackground(Color.BLUE);
}
};
private MouseAdapter mouseActions = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent me) {
System.out.println("Mouse Entered");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "enter");
button.getActionMap().put("enter", action);
}
#Override
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
JButton button = (JButton) me.getSource();
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, "none");
contentPane.setBackground(Color.RED);
}
};
private void displayGUI() {
JFrame frame = new JFrame("Button Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
tField = new JTextField(10);
button = new JButton("Click Me");
button.addMouseListener(mouseActions);
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new ButtonBinding().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
So I thought I had this code being able to work but it is not working.
I do not know what to do and I have tried looking at everything everyone has suggested but I just do not know what to do so any help would be greatly appreciated!
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class memory extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(156, 93, 82));
g.fill3DRect(21,3,7,12, true);
g.setColor(new Color(156,23,134));
g.fillOval(1,15,15,15);
g.fillOval(16,15,15,15);
g.fillOval(31,15,15,15);
g.fillOval(7,31,15,15);
g.fillOval(22,31,15,15);
g.fillOval(16,47,15,15);
setVisible(false);}
public memory()
{
GridLayout h =new GridLayout(3,3);
final JFrame frame = new JFrame();
final JPanel pan = new JPanel(h);
frame.add(pan);
pan.setBackground(new Color(130,224,190));
pan.setFont(new Font("Serif", Font.BOLD, 28));
JButton button1= new JButton();
pan.add(button1);
final JLabel label1= new JLabel("hi");
label1.setVisible(false);
pan.add(label1);
JButton button2= new JButton();
pan.add(button2);
final JLabel label2= new JLabel("hi");
label2.setVisible(false);
pan.add(label2);
JButton button3= new JButton();
pan.add(button3);
final JLabel label3 = new JLabel("hi");
label3.setVisible(false);
pan.add(label3);
JButton button4 = new JButton();
pan.add(button4);
final JLabel label4 = new JLabel("hi");
label4.setVisible(false);
pan.add(label4);
JButton button5= new JButton();
pan.add(button5);
final JLabel label5= new JLabel("hi");
label5.setVisible(false);
pan.add(label5);
JButton button6= new JButton();
pan.add(button6);
final JLabel label6= new JLabel("hi");
label6.setVisible(false);
pan.add(label6);
JButton button7= new JButton();
pan.add(button7);
final JLabel label7= new JLabel("hi");
label7.setVisible(false);
pan.add(label7);
JButton button8= new JButton();
pan.add(button8);
final JLabel label8= new JLabel("hi");
label8.setVisible(false);
pan.add(label8);
JButton button9= new JButton();
pan.add(button9);
final JButton button10= new JButton("Exit");
pan.add(button10);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Memory Game");
frame.setSize(500,500);
frame.setVisible(true);
setLayout(new BorderLayout());
add(pan,BorderLayout.CENTER);
add(button10, BorderLayout.SOUTH);
setSize(600,600);
setVisible(true);
final JLabel label9= new JLabel("hi");
label9.setVisible(false);
pan.add(label9);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label1.setVisible(true);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label2.setVisible(true);
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label3.setVisible(true);
}
});
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label4.setVisible(true);
}
});
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label5.setVisible(true);
}
});
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label6.setVisible(true);
}
});
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label7.setVisible(true);
}
});
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label8.setVisible(true);
frame.getContentPane().add(new memory());
setVisible(true);
}});
;
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
label9.setVisible(true);}}
);
button10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (button10.getSize() != null) {
System.exit(0);}}
});};
public static void main(String args[])
{
new memory();
};
}
As I said in your last question, you need to add your panel to an instance of a JFrame...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new memory());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Take some time and have a read through Creating a GUI With JFC/Swing
You'll also want to remove
final JFrame frame = new JFrame();
final JPanel pan = new JPanel(h);
frame.add(pan);
From the constructor and simple add your components directly to the (memory) panel
You'll also need to remove setVisible(false); from your paintComponent method ... which explains why you're having so many problems...
You must have a JFrame and show it for a swing application. I dont see anything like that.
Your main should be like this:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new memory());
frame.setSize(500, 400);
frame.setVisible(true);
}
});
}
When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else.
How should I do that?
textarea.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
button.doClick();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use .consume():
Consumes this event so that it will not be processed in the default
manner by the source which originated it.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
e.consume();
button.doClick();
}
}
Documentation
You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)
A small program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingExample {
private static final String key = "ENTER";
private KeyStroke keyStroke;
private JButton button;
private JTextArea textArea;
private Action wrapper = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
button.doClick();
}
};
private void displayGUI() {
JFrame frame = new JFrame("Key Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
textArea = new JTextArea(10, 10);
keyStroke = KeyStroke.getKeyStroke(key);
Object actionKey = textArea.getInputMap(
JComponent.WHEN_FOCUSED).get(keyStroke);
textArea.getActionMap().put(actionKey, wrapper);
button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.format("Button Clicked :-)%n");
}
});
contentPane.add(textArea, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new KeyBindingExample().displayGUI();
}
};
EventQueue.invokeLater(r);
}
}
There is a problem in my application when trying to set focus on a JEditorPane using the tab key. I did not understand why at first, but I manage to make a small test case that demonstrates the issue.
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
}
(Tested on Windows 7 and Mac OS X Lion.) The application will start with focus on the JTextField. Using the tab key won't set focus to the JEditorPane. But if you comment the setText line, it seems to work...
Any idea?
short answer
delay this event by wraping to the invokeLater()
longer answer
Focus / Focus Subsystem is asynchronous, in most cases hard to manage/timing this/these even(s), for better understanding about this issue you have to read linked tutorials,
example about Focus issue
import java.awt.*;
import java.awt.event.*;
import java.awt.font.TextAttribute;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
public class TextAttributeSTRIKETHROUGH {
private JFrame frame = new JFrame();
private JPanel pnl = new JPanel();
private JLabel focusLabel = new JLabel(" focusLost Handle ");
private JFormattedTextField formTextField;
private JLabel docLabel = new JLabel(" document Handle ");
private JFormattedTextField formTextField1;
private NumberFormat formTextFieldFormat;
private double amount = 10000.00;
private Map attributes;
#SuppressWarnings("unchecked")
public TextAttributeSTRIKETHROUGH() {
formTextFieldFormat = NumberFormat.getNumberInstance();
formTextFieldFormat.setMinimumFractionDigits(2);
formTextFieldFormat.setMaximumFractionDigits(2);
formTextFieldFormat.setRoundingMode(RoundingMode.HALF_UP);
focusLabel.setFont(new Font("Serif", Font.BOLD, 14));
focusLabel.setForeground(Color.blue);
focusLabel.setPreferredSize(new Dimension(120, 27));
formTextField = new JFormattedTextField(formTextFieldFormat);
formTextField.setValue(amount);
formTextField.setFont(new Font("Serif", Font.BOLD, 22));
formTextField.setForeground(Color.black);
formTextField.setBackground(Color.yellow);
formTextField.setPreferredSize(new Dimension(120, 27));
formTextField.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
}
public void focusLost(FocusEvent e) {
//Runnable doRun = new Runnable() {
//#Override
//public void run() {
double t1a1 = (((Number) formTextField.getValue()).doubleValue());
if (t1a1 < 1000) {
formTextField.setValue(amount);
}
//}
// };
//SwingUtilities.invokeLater(doRun);
}
});
docLabel.setFont(new Font("Serif", Font.BOLD, 14));
docLabel.setForeground(Color.blue);
docLabel.setPreferredSize(new Dimension(120, 27));
formTextField1 = new JFormattedTextField(formTextFieldFormat);
formTextField1.setValue(amount);
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
formTextField1.setForeground(Color.black);
formTextField1.setBackground(Color.yellow);
formTextField1.setPreferredSize(new Dimension(120, 27));
formTextField1.setHorizontalAlignment(SwingConstants.RIGHT);
formTextField1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
formTextField1.getDocument().addDocumentListener(docListener);
attributes = (new Font("Serif", Font.BOLD, 24)).getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
pnl = new JPanel();
pnl.setBorder(new EmptyBorder(2, 2, 2, 2));
pnl.setLayout(new GridLayout(2, 2));
pnl.add(focusLabel);
pnl.add(formTextField);
pnl.add(docLabel);
pnl.add(formTextField1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pnl, BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
formTextFieldFocus1();
}
//
private DocumentListener docListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
#Override
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
double t1a1 = (((Number) formTextField1.getValue()).doubleValue());
if (t1a1 < 1000) {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font(attributes));
}
};
SwingUtilities.invokeLater(doRun);
} else {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.setFont(new Font("Serif", Font.BOLD, 22));
}
};
SwingUtilities.invokeLater(doRun);
}
}
};
private void formTextFieldFocus1() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField1.grabFocus();
formTextField1.requestFocus();
formTextField1.setText(formTextField1.getText());
formTextField1.selectAll();
}
};
SwingUtilities.invokeLater(doRun);
}
private void formTextFieldFocus() {
Runnable doRun = new Runnable() {
#Override
public void run() {
formTextField.grabFocus();
formTextField.requestFocus();
formTextField.setText(formTextField.getText());
formTextField.selectAll();
formTextFieldFocus1();
}
};
SwingUtilities.invokeLater(doRun);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
TextAttributeSTRIKETHROUGH fl = new TextAttributeSTRIKETHROUGH();
}
});
}
}
All GUI related code should be executed on the EDT. See Concurrency in Swing for more details.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.html.*;
public class JEditorPaneFocusTest
{
public static void main(String... args) throws Exception
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JTextField(), BorderLayout.NORTH);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
editorPane.setText("<html><body>Hello World</body></html>");
container.add(editorPane, BorderLayout.CENTER);
jFrame.setSize(new Dimension(400, 400));
jFrame.setVisible(true);
}
});
}
}
i have a situation where i show a dialog where user has to fill some menus and then press OK. It works fine, but now i have another button on this dialog that if user wants to add some certain value, i want another dialog to popup where user fills the additional value and while pressing ok, this dialog disappears and user comes back to the main dialog.
I have tried this, but every time i call the new dialog, the focus does not go away from the main dialog, how can i do such a task.
Is there any relevant example or what is the proper way of doing such things.
EDIT:
public static class EdgeMenu extends JPopupMenu {
// private JFrame frame;
public MyMenu(final JFrame frame) {
super("My Menu");
// this.frame = frame;
this.addSeparator();
this.add(new EdgePropItem(frame));
}
}
//this shows the first dialog, another class because i have some other
//functions to be performed here
public static class EdgePropItem extends JMenuItem{
//...
public EdgePropItem(final JFrame frame) {
super("Edit Properties");
this.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EdgePropertyDialog dialog = new EdgePropertyDialog(frame, edge);
dialog.setVisible(true);
}
});
}
}
and now in other dialog, in the button even listener i am trying to call another dialog:
private void newDialogHandler(java.awt.event.ActionEvent evt) {
MyNewDialog rdialog = new MyNewDialog(edge);
rdialog.setVisible(true);
}
It appears fine, but the previous dialog, does not leave the focus, and it goes away only if i press finish/done on that dialog, what i want is the new dialog to come in focus, while pressing ok on here, focus should come back to the old main dialog, but it is not working?
maybe this code could be demonstate your issues,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SuperConstructor extends JFrame {
private static final long serialVersionUID = 1L;
public SuperConstructor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Super constructor");
Container cp = getContentPane();
JButton b = new JButton("Show dialog");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
FirstDialog firstDialog = new FirstDialog(SuperConstructor.this);
}
});
cp.add(b, BorderLayout.SOUTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
add(bClose, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
SuperConstructor superConstructor = new SuperConstructor();
}
});
}
private class FirstDialog extends JDialog {
private static final long serialVersionUID = 1L;
FirstDialog(final Frame parent) {
super(parent, "FirstDialog");
setPreferredSize(new Dimension(200, 200));
setLocationRelativeTo(parent);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
JButton bNext = new JButton("Show next dialog");
bNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
SecondDialog secondDialog = new SecondDialog(parent, false);
}
});
add(bNext, BorderLayout.NORTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
private int i;
private class SecondDialog extends JDialog {
private static final long serialVersionUID = 1L;
SecondDialog(final Frame parent, boolean modal) {
//super(parent); // < --- Makes this dialog
//unfocusable as long as FirstDialog is visible
setPreferredSize(new Dimension(200, 200));
setLocation(300, 50);
setModal(modal);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("SecondDialog " + (i++));
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
}
You can achieve this as follows:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class MultipleDialogs
{
public MultipleDialogs()
{
JButton btnOpen = new JButton("Open another dialog!");
btnOpen.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "This is the second dialog!");
}
});
Object[] options = {"OK", "Cancel", btnOpen};
int selectedOption = JOptionPane.showOptionDialog(null,
"This is the first dialog!", "The title",
JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
if(selectedOption == 0) // Clicking "OK"
{
}
else if(selectedOption == 1) // Clicking "Cancel"
{
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new MultipleDialogs();
});
}
}
}
You can replace "This is the first dialog!" and "This is the second dialog!" with JPanel's which can contain any swing components you want.
Create the second dialog from a constructor that takes dialog and boolean as parameters and that solves the problem.