【问题标题】:Should open new window while clicking a button?单击按钮时应该打开新窗口吗?
【发布时间】:2011-02-09 10:18:43
【问题描述】:

我知道这是一个很简单的问题,但我找不到解决方案。

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

编辑:

当我尝试这个时:

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

我得到一个错误:

Cannot find symbol NewJDialog

第二个窗口名为 NewJDialog...

【问题讨论】:

  • 将 ActionListener 添加到打开第二个对话框的按钮(例如 java.sun.com/docs/books/tutorial/uiswing/events/…)。
  • 关于你的编辑,你应该了解类名和成员名之间的区别,你也应该看看变量的范围。在您的情况下,NewJDialog 是一个类名,由于此类不存在,您会收到错误消息。
  • @Searles:好点。该名称让人想起 NetBeans GUI 编辑器生成的名称。此处讨论了一个相关示例:stackoverflow.com/questions/2561480

标签: java netbeans


【解决方案1】:

您肯定想查看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);
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2018-12-18
    • 1970-01-01
    相关资源
    最近更新 更多