简体   繁体   中英

How to make a function like JOptionPane.showMessageDialog(xxx,“xxx”)?

It take a full weekend with stressful in trying to make a function that show dialog and could return value after click ok (like JOptionPane.showMessageDialog(xxx,"xxx"))? could anyone help me about writing the code ?

Thanks in advance

Makara

Use a JOptionPane.showInputDialog().

Other alternatives are to hand a GUI control(s) to the JOptionPane.showMessageDialog() and query the state of the control(s) once it is closed, or use a JDialog.

If you spend more than 15 minutes trying to get a JOptionPane to do exactly as required, it is a good sign that a JOptionPane is not the class for the job.

Here you have a trivial approach. It is a class and not a function. If you want to construct it with just have two parameters, make an additional constructor that has the two parameters you need.

Here you can take a look at the real McCoy...

public class MyOwnJDialog extends javax.swing.JDialog {
    private String theMessage;

    public MyOwnJDialog(java.awt.Frame parent, boolean modal, String theMessage) {
        super(parent, modal);
        initComponents();
        this.theMessage = theMessage;
        jLabel1.setText(theMessage);
        setVisible(true);
    }


    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);

        getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
        pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;

}
  1. Design what classes you will need and what you want the GUI to look like
  2. Create a skeleton of the classes and methods and start filling in the details.
  3. Create a method that could put this together and return the output.

Some useful items:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM