用JAVA卡片布局实现在一个页面中上面有三个按钮点击每个按钮实现页面不同的颜色
若以下回答无法解决问题,邀请你更新回答
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);
}
});
}
}
下边是代码
--------------------------------------------------------------------------------------------------------------
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);
}
});
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询