用JAVA卡片布局实现在一个页面中上面有三个按钮点击每个按钮实现页面不同的颜色

2025-01-05 13:33:28
推荐回答(1个)
回答1:

不知道为什么一定要用卡片布局
下边是代码
--------------------------------------------------------------------------------------------------------------

import javax.swing.JFrame;

public class App extends JFrame {

public App() {

setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 300);
setResizable(false);
getContentPane().setLayout(new CardLayout(0, 0));
getContentPane().add(new MyPanel(), "Main");
setVisible(true);
}

public static void main(String[] args) {
new App();
}
}

class MyPanel extends JPanel {

public MyPanel() {

JButton btnRed = new JButton("red");
add(btnRed);
btnRed.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
setBackground(Color.red);
}
});

JButton btnYellow = new JButton("Yellow");
add(btnYellow);
btnYellow.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
setBackground(Color.yellow);
}
});

JButton btnBlue = new JButton("blue");
add(btnBlue);
btnBlue.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
setBackground(Color.blue);
}
});
}
}