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

5
我知道这是一个非常简单的问题,但我找不到解决方案。
我有一个主Swing对话框和另一个Swing对话框。主对话框有一个按钮。如何使点击按钮后打开另一个对话框?
编辑:
当我尝试这样做:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
       NewJDialog okno = new NewJDialog();
       okno.setVisible(true);
    }

我遇到了一个错误:
Cannot find symbol NewJDialog

第二个窗口名为NewJDialog...

1
将ActionListener添加到按钮上(请参见例如http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html),其中您打开第二个对话框。 - Searles
1
关于你的编辑,你应该学习类名和成员名字之间的区别,您还应该查看变量的作用域。在您的情况下,NewJDialog是一个类名,由于这个类不存在,您会收到错误提示。 - Searles
@Searles:说得好。这个名字让人想起NetBeans GUI编辑器生成的那些名称。这里讨论了一个相关的例子:https://dev59.com/-UzSa4cB1Zd3GeqPqu7i - trashgod
1个回答

6

您肯定希望查看如何制作对话框,并查阅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);
            }
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接