我正在使用一个卡片布局,并希望第一张卡片上有一个按钮,当点击它时,会跳转到第二张卡片上并显示一个按钮,可以回到第一张卡片。以下是我的代码,我已尝试在 actionPerformed 方法中添加一些内容,但没有成功让它正常工作。此外,在 button1.addActionListener(this); 和 button2.addActionListener(this); 中,出现了“this” 语法错误,这可能是因为我的 actionPerformed 方法没有正确设置。希望能够提供帮助,让按钮正常工作。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ItemListener {
JPanel cards;
public void addComponentToPane(Container pane) {
//create cards
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
button1.addActionListener(this);
button2.addActionListener(this);
card1.add(button1);
card2.add(button2);
//create panel that contains cards
cards = new JPanel(new CardLayout());
cards.add(card1);
cards.add(card2);
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
public static void createAndShowGUI() {
//create and setup window
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and setup content pane
Main main = new Main();
main.addComponentToPane(frame.getContentPane());
//display window
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
}
public static void main(String[] args) {
//set look and feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//turn off metal's bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
//schedule job for the event dispatch thread creating and showing GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}