对于你原来的问题:
如何给按钮添加动作?
您可能想查看How to write an Action Listener。
第二个问题:
现在我想输入我制作的另一个 JFrame,并使第一个消失。怎么样?
请检查这两种方法:)
选项 1(推荐)
如果您想以正确的方式进行操作,您应该使用@AndrewThompson 在上面的comment 中推荐的CardLayout。
我还看到您使用的是 Null 布局(因为 setBounds() 方法),您可能还想摆脱它,请参阅 Why is it frowned upon to use a null layout in Swing? 和 Null Layout is Evil 了解原因,您应该使用 @ 987654326@ 或它们的组合,如以下代码所示,基于@AndrewThompson 的answer (与上面评论中链接的相同),但稍作修改以使用JFrame 而不是JOptionPane,所以给他也通过投票支持他的原始答案!
这会产生以下输出:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo {
JButton button1, button2;
CardLayoutDemo() {
JFrame gui = new JFrame("CardLayoutDemo");
button1 = new JButton("Go to pane 2");
button2 = new JButton("Go to pane 1");
JPanel pane1 = new JPanel();
pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
JPanel pane2 = new JPanel();
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
final CardLayout cl = new CardLayout();
final JPanel cards = new JPanel(cl);
pane1.add(new JLabel("This is my pane 1"));
pane1.add(button1);
pane2.add(new JLabel("This is my pane 2"));
pane2.add(button2);
gui.add(cards);
cards.add(pane1, "frame1");
cards.add(pane2, "frame2");
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
cl.show(cards, "frame2");
} else if (ae.getSource() == button2) {
cl.show(cards, "frame1");
}
}
};
button1.addActionListener(al);
button2.addActionListener(al);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
使用此选项,您只有 1 个JFrame,但您可以通过不同的视图进行更改,并且不会因任务栏上的多个窗口而惹恼用户。
这里还有一个提示:如果您要打开第二个JFrame 以防止用户在第一个做某事,您应该考虑使用JOptionPane 或第二个JFrame 将只包含一个一些你不想一直在那里的信息(类似于弹出窗口)。
选项 2(不推荐)
但如果你真的真的很想使用多个JFrames(即not recommended)你可以dispose()它。当时您正在调用要创建的新JFrame。例如,下面的代码会产生这样的输出:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
JFrame frame;
JButton button;
TwoJFrames() {
frame = new JFrame("1st frame");
button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new AnotherFrame();
frame.dispose();
}
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new TwoJFrames();
}
class AnotherFrame {
JFrame frame2;
JLabel label;
AnotherFrame() {
frame2 = new JFrame("Second Frame");
label = new JLabel("This is my second frame");
frame2.add(label);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.pack();
frame2.setVisible(true);
}
}
}
在这种情况下,如果您想返回上一个状态或在关闭第二个 JFrame 时重新打开此状态,您可能需要考虑 setVisible()
我上面的两个代码都称为 Minimal, Complete, and Verifiable example (MCVE) 或 Runnable Example 或 Short, Self Contained, Correct Example (SSCCE) 这些代码您可以复制粘贴并看到与我相同的输出,当您的代码中有错误时,这些示例非常方便,因为我们可以看到您的错误在哪里,或者能够更轻松和/或更快地找到它们。
您应该考虑阅读我提供的所有链接(包括这些链接),并为您未来的问题做出类似我在上面所做的事情,这样您就可以防止混淆,并且您会得到更多、更快和更好的回复.