ActionListener in JDialog created by JOptionPane

I have a problem I absolutely cannot get around. I've been toying with this code all day and nedd some help badly. The code is posted below. Let me give you some background. I have an application that uses "popups" to ask the user a series of questions. I have two bg images I want to display for the background,
as well as a custom button (that's no sweat). I originally wrote a class extending JDialog to show the popups. But JDialog does not "block" and wait for user input. I started toying around with JOptionPane. I have created a JDialog from JOptionPane.createDialog(parent, title). All the components display correctly and
the dialog blocks, BUT the actionListener I added to my button does not go into action. Am I barking up the wrong tree, or is there a way to get a JDialog to block
the running thread?
class myDialog{
JDialog main;
JTextField inputfield;
  public myDialog(JFrame parent, String display){
main = this.createDialog(parent, "hello");
Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        main.setBounds(screenSize.width/2 - 195,
                  screenSize.height/2 - 50,395,110);
JLabel textInsert = new JLabel(display);
textInsert.setFont(new Font("Serif", Font.BOLD|Font.ITALIC, 14));
textInsert.setForeground(Color.gray);
JButton next = new JButton(new ImageIcon("images/gui/next.png"));
inputfield = new JTextField(20);
Container c = main.getContentPane();
c.setLayout(new BorderLayout());
c.removeAll(); // call this to remove the components added by JOptionPane.
BackgroundComponent panel = new BackgroundComponent(new ImageIcon("images/gui/upperdialog.png").getImage());
BackgroundComponent panel2 = new BackgroundComponent(new ImageIcon("images/gui/lowerdialog.png").getImage());
panel.add(new JLabel(new ImageIcon("images/gui/spacer.png")));
panel.add(textInsert);
panel2.add(inputfield);
panel2.add(next);
c.add(panel, BorderLayout.NORTH);
c.add(panel2, BorderLayout.CENTER);
main.setResizable(true);
main.setVisible(true);
next.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         main.setVisible(false);
     }Thanx in advance -- CSB

the wrong tree, or is there a way to get a JDialog to
block
the running thread?Yes, by making it modal:
main.setModal(true);
main.setVisible(true);There are also a couple of JDialog constructors that you can use to create a modal dialog without having to use the setModal method.

Similar Messages

  • Display an icon(question,warning,etc.) inside JDialog(like in JOptionPane)

    Hello,
    because JOptionPane can't use a JPasswordField as the input component, I created a JDialog prompting the user for a password. Now I can't figure out how to show that nice look-and-feel style icon inside the dialog (the question mark that is shown when you use messageType=QUESTION_MESSAGE in JOptionPane). Shortly, this is what I have and this is what I want to get... I tried this:
    dlg.getRootPane().setWindowDecorationStyle(JRootPane.QUESTION_DIALOG)But it does nothing. Could you help me, please?
    Thank you
    Ondra

    Still it doesn't answer my question: how to display the LAF icon inside a JDialog.Huh?import javax.swing.*;
    public class OptionPanePassword {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OptionPanePassword().makeUI();
       public void makeUI() {
          JLabel label =new JLabel("Enter Password: ");
          JPasswordField field = new JPasswordField(15);
          JPanel panel = new JPanel();
          BoxLayout layout = new BoxLayout(panel, BoxLayout.X_AXIS);
          panel.setLayout(layout);
          panel.add(label);
          panel.add(field);
          JOptionPane.showConfirmDialog(null, panel, "",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
    }db

  • JDialog disappears behind Browser after sevearal seconds

    Hi!
    I found a strange behaviour I can't explain, perhaps you have an idea:
    I use an Applet for printing. The Applet asks the user to put the right paper into the printer by using a JDialog created using
    JOptionPane.showMessageDialog(null, "someMassage", "someTitle", JOptionPane.INFORMATION_MASSAGE)
    the Dialog appears correctly and is modal, but sometimes it disappears and the browser window (Internet Explorer 6) seems to hang (because of the modal dialog). The only solution is, to find the Dialog by pressing "Alt+Tab".
    When I change the code slightly to
    JOptionPane.showMessageDialog(myApplet, "someMassage", "someTitle", JOptionPane.INFORMATION_MASSAGE)
    (where "myApplet" is the object of my Applet)
    it seems to work.
    Any ideas why?
    Thanks a lot!

    I don't think that you can fix it.
    Create your own MessageDialogClass, this is the best solution
    Here is an example how to create your dialog
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyMessageDialog extends JDialog implements ActionListener
         private Color myColor = null;
         public MyMessageDialog(Frame owner, String message)
              /* if removed super(owner), you'll have the same problem*/
              super(owner);
              JLabel lab = new JLabel(message);
              JButton close = new JButton("close");
              close.addActionListener(this);
              JPanel up = new JPanel();
              JPanel down = new JPanel();
              up.setLayout(new FlowLayout());
              down.setLayout(new FlowLayout());
              up.add(lab);
              down.add(close);
              getContentPane().add(up, BorderLayout.NORTH);
              getContentPane().add(down, BorderLayout.SOUTH);
              setModal(true);
         public void showDialog()
              setLocation(300,200);
              pack();
              setVisible(true);
         public void actionPerformed(ActionEvent ae)
              dispose();          
    In your main class (from where you call the dialog), add the following code :
    MyMessageDialog obj = new MyMessageDialog(this, "Some message");
    obj.showDialog();

  • JOptionPane and JDialog.DO_NOTHING_ON_CLOSE broken?

    Hi there
    I've created a JDialog from a JOptionPane and I don't want the user to simply dispose of the dialog by clicking on the close button but they are still able and I'm sure that my code is correct. Is it my code that is wrong or is it a java bug? Oh I'm running on 1.3 BTW
    JFrame f = new JFrame();
    f.setSize(500, 500);
    f.setVisible(true);
    JOptionPane optionPane = new JOptionPane("Hello there", JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    JDialog d = optionPane.createDialog(f, "Testing");
    d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    d.setVisible(true);I know that I can just set up a JDialog directly and use the setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE) and it seems to work properly but I would like to see it work for JOptionPane!
    Thanks in advance

    Sorry but this doesn't make it work either. I've looked at the code for createDialog in JOptionPane and it actually adds a WindowListener to the dialog in there as well as a propertyListener. On closing the option pane it calls a method in windowClosing of the windowListener which in turn fires a property change event which then tells the dialog to dispose itself so the addition of another windowAdapter to override the windowClosing method will not help :-(
    I've managed to get round it by doing something similar to
    JFrame frame = new JFrame();
    final JDialog dialog = new JDialog(frame, "Testing", true);
    JButton button = new JButton("OK");
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        dialog.dispose();
    JOptionPane optionPane = new JOptionPane(button, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
    dialog.setContentPane(optionPane);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.pack();
    dialog.setVisible(true);

  • JOptionPane and JDialog

    Hi guys,
    I've been scooting around the net trying to find an answer to this problem. Basically I have a JDialog that users enter registration details. If they haven't completed all fields or if the password confirmation is wrong then a JOptionPane.showMessageDialog appears telling users what has happened. However if they were to then click ok in the OptionPane it closes both the option pane and the original Dialog window. Have you guys any idea?
    A code snippet below:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JDialog implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFrstName;
         JLabel lblLstName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblSex;
         JLabel lblEmail;
         String usrName;
         String strUsrPwd;
         String strCnfPwd;
         String frstName;
         String lstName;
         String age;
         String empid;
         String email;
         String sex;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox listSex;
         JTextField txtUserName;
         JPasswordField txtUsrPwd;
         JPasswordField txtCnfUsrPwd;
         JTextField txtFrstName;
         JTextField txtLstName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         public Register() {
              this.setTitle("Registration Form");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Please register below");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUsrPwd = new JPasswordField(15);
              panel.add(txtUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUsrPwd=new JPasswordField(15);
              panel.add(txtCnfUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFrstName=new JLabel("First Name");
              panel.add(lblFrstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFrstName=new JTextField(15);
              panel.add(txtFrstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLstName=new JLabel("Last Name");
              panel.add(lblLstName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLstName=new JTextField(15);
              panel.add(txtLstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email address");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sex= {"Male", "Female"};
              listSex = new JComboBox(sex);
              listSex.setSelectedIndex(0);
              panel.add(listSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
             setDefaultCloseOperation(DISPOSE_ON_CLOSE); //get rid of this window only on closing
              setVisible(true);
              setSize(450,400);
             }//end Register()
              public void actionPerformed(ActionEvent ae) {
                   Object o = ae.getSource(); //get the source of the event
                   if(o == btnCancel)
                        this.dispose();
                   if(o == btnSubmit){
                        usrName = txtUserName.getText();
                        strUsrPwd = txtUsrPwd.getText();
                        strCnfPwd = txtCnfUsrPwd.getText();
                        frstName = txtFrstName.getText();
                        lstName = txtLstName.getText();
                        age = txtAge.getText();
                        empid = txtEmpId.getText();
                        email = txtEmail.getText();
                        sex = (String)listSex.getItemAt(0);
                        if ((usrName.length() == 0) || (strUsrPwd.length() == 0) ||
                        (strCnfPwd.length() == 0) || (frstName.length() == 0) ||
                        (lstName.length() == 0) || (age.length() == 0) ||
                        (empid.length() == 0) || (email.length() == 0))
                        JOptionPane.showMessageDialog(null,
                        "One or more entry is empty. Please fill out all entries.", "Message", JOptionPane.ERROR_MESSAGE);
                        if ((!strUsrPwd.equals(strCnfPwd))){
                             JOptionPane.showMessageDialog(null,
                             "Passwords do not match. Please try again", "Message", JOptionPane.ERROR_MESSAGE);
                        Thanks,
    Chris

    try something like this:
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    public class About extends JDialog {
    /** Creates new form About */
    public About(JFrame parent) {
    super(parent,true);
    initComponents();
    pack();
    Rectangle parentBounds = parent.getBounds();
    Dimension size = getSize();
    // Center in the parent
    int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
    int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
    setLocation(new Point(x, y));
    and from the main dialog:
    new About(this).setVisible(true);

  • JButton in JDialog vs JOptionPane

    I have created two different JDialogs, one with JOptionPane and one in the old-fashioned way. My problem is that the buttons in the different JDialogs get different appearence (I'm usings javas Metal L&F). Take a look at this sample code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TestFrame extends JFrame implements ActionListener {
       JDialog dialog1;
       JDialog dialog2;
       JButton button1;
       JButton button2;
       JButton dialogButton;
       public TestFrame() {
          button1 = new JButton("Open dialog 1");
          button1.addActionListener(this);
          button2 = new JButton("Open dialog 2");
          button2.addActionListener(this);
          getContentPane().add(button1, BorderLayout.NORTH);
          getContentPane().add(button2, BorderLayout.SOUTH);
          pack();
          setVisible(true);
       public static void main(String args[]) {
          new TestFrame();
       public void openDialog1() {
          JOptionPane vAbout = new JOptionPane("Just some text...", JOptionPane.INFORMATION_MESSAGE);
          dialog1 = vAbout.createDialog(this, "Dialog 1");
          dialog1.show();
       public void openDialog2() {
          dialog2 = new JDialog(this, "Dialog 2", true);
          GridBagLayout gbl = new GridBagLayout();
          GridBagConstraints gbc = new GridBagConstraints();
          dialog2.getContentPane().setLayout(gbl);
          JLabel text = new JLabel("Just some text...");
          dialogButton = new JButton("OK");
          dialogButton.addActionListener(this);
          dialog2.getContentPane().add(text, gbc);
          gbc.gridy = 1;
          dialog2.getContentPane().add(dialogButton, gbc);
          dialog2.pack();
          dialog2.setVisible(true);
       public void actionPerformed(ActionEvent e) {
          System.out.println(e.getSource());
          if (e.getSource() == button1)
             openDialog1();
          if (e.getSource() == button2)
             openDialog2();
          if (e.getSource() == dialogButton)
             dialog2.dispose();
       protected void processWindowEvent(WindowEvent e) {
          super.processWindowEvent(e);
          if(e.getID() == WindowEvent.WINDOW_CLOSING) {
             System.exit(0);
    }How can I get my button in dialog2 to look the same as the button in dialog1?

    To set the button to be default, you need some modification. Here's the basic frame work:
    public class TestFrame() extends JFrame
       //Your constructor
       public TestFrame()
          //Do stuff in here
          myDialog mydialog = new myDialog(this);
          mydialog.show()
       public static void main(String[] args)
          //etc
       private void SomeOtherMethods()
           //Declare your JOptionPane
    public class myDialog extends JDialog
       //Constructor
       public myDialog()
           //Add Components like usual
           getRootPane.setDefaultButton(DialogButton);
           getContentPane.add(Your_Panels);
        private void SomeOtherMethods()
    }Basically, you're taking your JDialog and placing it in it's own class (which is better anyway, trust me). Then it will set the button as the default and make the border darker.
    Let me know if you have anymore questions.

  • JOptionPane with multiple inputs

    Well, I want to know , if someone can help me with JOptionPane, I need a windows of JOptionPane.showInputDialog (), that reads
    3 inputs in the same window, I mean if I can have three Input Spaces in the same window.

    Zerokid wrote:
    by the way, is it easier to do it with JFrame or JOptionPane?I don't understand this question. You are wanting to create a dialog that allows the user to input into three fields, correct? You won't use a JFrame to create a dialog. You could do this with a JDialog, but a JOptionPane is somewhat easier to use here.

  • Create a screen for user input in BI

    Hi Experts,
    I want to know can i creat a screen for user input in BI with module pool programing
    and i want to store the data in ztable in SAP-BI.
    Moderator message: please search for available documentation, these forums are no substitute for ABAP training.
    Edited by: Thomas Zloch on Dec 10, 2010 8:37 PM

    I'm afraid that I cannot get it. I had a look at the docs you suggested before posting, and still, no luck (...)
    JOptionPane.showMessageDialog(dialog, "Please input info");Can you please tell me what I'm doing wrong and I cannot add the JDialog to the JOptionPane?Re-read the API and tutorial. JOptionPane is meant specifically to spare you from instantiating manually a JDialog. The showXxxDialog(...) methods do create a JDialog of their own, based on the contents supplied as arguments.
    In particular, using the 2-arguments variation showMessageDialog(Component parentComponent, Object message):
    - The first argument parentComponent is not be the dialog you want to display, but the component over which you want the dialog to appear. The most typical value are this or null.
    - The second argument is the "message" to display, but as described in the API, it can be a JComponent, that is, even a JPanel with child widgets (in a word, a JPanel containing the specific form you'd display in the dialog if you were writing the dialog manually).
    Again, at the risk of insisting densely, I'm only quoting the API an tutorial, so please read them attentively.
    Edited by: jduprez on Nov 2, 2009 2:29 PM - Sorry Kevin, hadn't seen you latest reply. I completely subscribe to the thought process you recommend.
    Edited by: jduprez on Nov 2, 2009 2:32 PM
    Thinking about it further, I don't completely subscribe... Indeed it looks like a bad idea to make the OP wonder about dialog.setVisible() when JOptionPane enables him to forget about the hand-made dialog. I stand by my own advice ("JDialog" should not even appear in this code extract).

  • How to set a Japplet as parent for a JDialog ?

    Hi,
    I am using netbeans IDE 6.0 for swing development. I have a web application where i have main GUI as JApplet, In this I am calling a custom JDialog on a button click.
    Code for main GUI looks like,
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Demo extends JApplet implements ActionListener {
        JButton btn = new JButton();
        String msg;
        public void init(){
            add(btn);
            this.setBounds(200, 200, 200, 250);
            this.setVisible(true);
            btn.setText("Click");
            msg = "This is test message";
            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    MyDialog diag = new MyDialog(msg);
                    diag.setVisible(true);
         public void actionPerformed(ActionEvent arg0) {
    }The following code is for custom dialog. Here super(parent,modal) is commented as how don't know how to pass JApplet as container for JDialog.
    public class MyDialog extends javax.swing.JDialog {
        /** Creates new form MyDialog */
        public MyDialog(String msg) {
            //super(parent, modal);
            initComponents();
            jTextArea1.setText(msg);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            Jlbl = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    closeDialog(evt);
            Jlbl.setText("Text");
            add(Jlbl, java.awt.BorderLayout.NORTH);
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
            add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jButton1.setText("ok");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            add(jButton1, java.awt.BorderLayout.SOUTH);
            pack();
        /** Closes the dialog */
        private void closeDialog(java.awt.event.WindowEvent evt) {                           
            setVisible(false);
            dispose();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
            setVisible(false);
            dispose();
        // Variables declaration - do not modify                   
        private javax.swing.JLabel Jlbl;
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextArea jTextArea1;
        // End of variables declaration                 
    }My problem is that how can i set main window that is JApplet as parent to JDialog so that it should reside inside main window.
    Any suggestion would be helpfull.
    Thank you in advance.

    hi,
    I Got solution from following ;
    [Open a JDialog from an JApplet|http://forums.sun.com/thread.jspa?forumID=31&threadID=654054]
    But when I open the applet in browser and click button from applet to create JDialog, the dialog shown can be moved out side browser window (applet window). how is this happening ?
    Your suggestion would definitely help.
    Thank you

  • Update JPanel in JDialog

    Hey,
    need some help please....
    I've searched long and hard but can't find anything.
    I've got an application that opens a JDialog, then jDialog has a JPanel within
    it.
    Once the JDialog has loaded on the screen i want to update the Jpanel based on
    a button click.
    My problem is that the JPanel wont update.
    I've made a simple program that displays the same behaviour.
    Frame with a button on it to open a JDialog :
    public class testFrame extends javax.swing.JFrame {
        /** Creates new form testFrame */
        public testFrame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("Show Dialog");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(150, 150, 150)
                    .addComponent(jButton1)
                    .addContainerGap(159, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(135, 135, 135)
                    .addComponent(jButton1)
                    .addContainerGap(142, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            testJDialog test = new testJDialog(this,true);
            test.setVisible(true);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new testFrame().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        // End of variables declaration
    }JDialog code :
    import javax.swing.JTree;
    * @author  wesley
    public class testJDialog extends javax.swing.JDialog {
        /** Creates new form testJDialog */
        public testJDialog(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("TitleBorder"));
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 347, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 128, Short.MAX_VALUE)
            jButton1.setText("Add Tree");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(145, 145, 145)
                            .addComponent(jButton1)))
                    .addContainerGap(31, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            this.jPanel1.add(new JTree());
            this.pack();
            this.repaint();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    testJDialog dialog = new testJDialog(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                    dialog.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
    }Ive tried
    this.pack();
    this.repaint();but i cant get the JPanel to repaint.
    Im using Vista Java version
    C:\Users\wesley>java -version
    java version "1.6.0_03"
    Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
    Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)Cheers
    Wesley

    wesleyelder wrote:
    Thanks so much for taking the time to reply, that worked a treat.you're welcome
    i agree the netbeans code is a mess sometimes but when i just need a simple JDialog i sometimes use it, just lazy a guess :)But then you run into problems like this one. I'd much prefer to make my own simple JDialog:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    public class TestMyDialog
        private JPanel mainPanel = new JPanel();
        private JPanel centerPanel = new JPanel();
        public TestMyDialog()
            JButton addTreeBtn = new JButton("Add Tree");
            addTreeBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    addTreeAction();
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(addTreeBtn);
            centerPanel.setBorder(BorderFactory.createTitledBorder("Title Border"));
            centerPanel.setPreferredSize(new Dimension(400, 200));
            centerPanel.setLayout(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            mainPanel.setLayout(new BorderLayout(20, 20));
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        private void addTreeAction()
            JTree tree = new JTree();
            tree.setOpaque(false);
            centerPanel.add(new JScrollPane(tree), BorderLayout.CENTER);
            centerPanel.revalidate();
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            final JFrame frame = new JFrame("Test My Dialog");
            JPanel framePanel = new JPanel();
            framePanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
            framePanel.setPreferredSize(new Dimension(500, 500));
            JButton showDialogBtn = new JButton("Show Dialog");
            showDialogBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    showDialogAction(frame);
            framePanel.add(showDialogBtn);
            frame.getContentPane().add(framePanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        private static void showDialogAction(JFrame frame)
            JDialog dialog = new JDialog(frame, "My Dialog", true);
            dialog.getContentPane().add(new TestMyDialog().getMainPanel());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Changing Focus on JDialog Button

    Hi,
    I have created a JOptionPane with the optionType of YES_NO_OPTION. I then create a JDialog out of it. So the JDialog honestly does the job and Shows up a Dialog Box with YES and NO button. The Focus is set on YES button...but I want it changed to NO button....does anyone have a Idea how to do it???
    Cheers,
    Manjunath Rane

    NO It does NOT work.
    Instead I have successfully tried out by attaching a WindowListener to the Dialog I create. I then override the windowOpened method and set the requestFocus on NO Button (Getting the Handle of the NO button was a Tough task. I had iterated thru the Panels inside the JDialog to get the instance......does somebody have a Better Solution????)
    Cheers,
    Manjunath Rane

  • Can we force JOptionPane to show all possible selections?

    Hey all,
    I'm trying to create a JOptionPane which will allow multiple selections. Not much of a problem.
    String[] options = { "1", "2", "3" };
    String selectedValue = (String)JOptionPane.showInputDialog(null, "Message", "Title", JOptionPane.OK_CANCEL_OPTION,null, options, options[1]);
    Is there any way to force JOptionPane to show all 3 selections? Currently, I'm getting a pulldown list.
    If I want to force the issue, do I need to create my own JDialog instead of using a JOptionPane?
    thanks for any help in advance,
    Geoff

    JOptionPane.showOptionDialog(null, "Message", "Title", JOptionPane.OK_CANCEL_OPTION,JOptionPane.ERROR_MESSAGE, null, options, options[1]);
    ???

  • JOptionPane and Focus

    Hello All,
    I've got a small problem with setting the focus in a JOptionPane. My JOptionPane consists of one JComboBox and two JTextFields. I've created this JOptionPane by putting the components in an array and passing it to the JOptionPane constructor. Initially it starts with the focus on the top most component (the JComboBox). What i would like is to have it focussed on one of the JTextFields.
    Does anyone have any idea how to do this?
    Thanks in advance.

    Don't use a JOptionPane, why not use a modal JDialog? That way it is much easier to organise the components and arrange focus

  • JOptionPane getting it's icon

    I have created a JOptionPane and I am trying to get it's icon. I read that the icon was driven by the message type so why is the icon null? Better yet, how can I get get the error icon that it uses. That's my goal. This is what I have done
    String message = "msg";
    JOptionPane pane = new JOptionPane(message, JOptionPane.ERROR_MESSAGE);
    JDialog dlg = pane.createDialog(null, "title");
    Icon icon = pane.getIcon();
    //the Icon is null  BOOOO 
    //if I add do this then the icon shows up... uhm... icon is bound in the show.  How is does show get it?
    dlg.show();

    you can use :
    UIManager.getIcon("OptionPane.questionIcon")
    UIManager.getIcon("OptionPane.errorIcon")
    UIManager.getIcon("OptionPane.informationIcon")
    UIManager.getIcon("OptionPane.warningIcon")

  • JOptionPane Question...Help!

    Is there a way to create a JOptionPane and not have any buttons at the bottom to select from? Please help!

    Theoretically, you could create a class which extends JOptionPane and then override the createDialog method, so as to "remove" the buttons from the Panel. But practically, I would not advise you on it because
    1. The code will look messy
    2. It would be much more practical to create a JDialog and use it.
    hope this helps....
    if you have any particular requirements, where JOptionPane cannot substituted by JDialog, do let me know.

Maybe you are looking for