单击按钮时应该打开新窗口?

时间:2010-04-18 17:33:42

标签: java netbeans

我知道这是一个非常简单的问题,但我无法找到解决方案。

我有一个主摆动对话框和其他摆动对话框。主对话框有一个按钮。 如何在单击按钮后打开其他对话框?

编辑:

当我尝试这个时:

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
       NewJDialog okno = new NewJDialog();
       okno.setVisible(true);
    }

我收到错误:

Cannot find symbol NewJDialog

第二个窗口名为NewJDialog ...

1 个答案:

答案 0 :(得分:6)

您肯定希望查看How to Make Dialogs并查看JDialog API。这是一个简单的例子来开始。您可以将它与您现在正在做的事情进行比较。

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class DialogTest extends JDialog implements ActionListener {

    private static final String TITLE = "Season Test";

    private enum Season {
        WINTER("Winter"), SPRING("Spring"), SUMMER("Summer"), FALL("Fall");
        private JRadioButton button;
        private Season(String title) {
            this.button = new JRadioButton(title);
        }
    }

    private DialogTest(JFrame frame, String title) {
        super(frame, title);
        JPanel radioPanel = new JPanel();
        radioPanel.setLayout(new GridLayout(0, 1, 8, 8));
        ButtonGroup group = new ButtonGroup();
        for (Season s : Season.values()) {
            group.add(s.button);
            radioPanel.add(s.button);
            s.button.addActionListener(this);
        }
        Season.SPRING.button.setSelected(true);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.add(radioPanel);
        this.pack();
        this.setLocationRelativeTo(frame);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JRadioButton b = (JRadioButton) e.getSource();
        JOptionPane.showMessageDialog(null, "You chose: " + b.getText());
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new DialogTest(null, TITLE);
            }
        });
    }
}