不知道为什么一定要用卡片布局
下边是代码
--------------------------------------------------------------------------------------------------------------
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);
}
});
}
}