Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - 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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
   }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...