Java 单击按钮时应该打开新窗口吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2663199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should open new window while clicking a button?
提问by Devel
I know that it is very simple question, but I can't find a solution.
我知道这是一个非常简单的问题,但我找不到解决方案。
I have a main swing dialog and other swing dialog. Main dialog has a button. How can I make that after clicking a button the other dialog opens?
我有一个主摆动对话框和其他摆动对话框。主对话框有一个按钮。单击按钮后如何打开另一个对话框?
EDIT:
编辑:
When I try this:
当我尝试这个时:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
NewJDialog okno = new NewJDialog();
okno.setVisible(true);
}
I get an error:
我收到一个错误:
Cannot find symbol NewJDialog
The second window is named NewJDialog...
第二个窗口名为 NewJDialog...
回答by trashgod
You'll surely want to look at How to Make Dialogsand review the JDialog
API. Here's a short example to get started. You might compare it with what you're doing now.
您肯定想查看如何制作对话框并查看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);
}
});
}
}