基于OOP使用JButton修改JFrame背景色失效问题
问题解决:JFrame点击按钮修改背景色无效果
问题原因
你调用Main.frame.setBackground(Color.blue)修改的是JFrame的边框背景,而窗口中实际承载按钮等组件的内容显示区域是JFrame的ContentPane,所以直接修改JFrame的背景色不会产生视觉上的变化。
修复代码
修改MyButton类中的actionPerformed方法,将操作对象改为JFrame的ContentPane:
@Override public void actionPerformed(ActionEvent e) { if(use.equals("exit")){ System.exit(0); }else if(use.equals("changeColor")){ // 改为设置内容面板的背景色 Main.frame.getContentPane().setBackground(Color.blue); // setBackground会自动触发重绘,repaint可以省略 } }
额外优化建议
- 避免使用静态变量
Main.frame,可以通过构造方法传递Frame实例,降低代码耦合度 - 建议先添加所有组件,再调用
frame.setVisible(true),避免组件显示异常:public static void main(String[] args) { MyButton change = new MyButton("Change Color", "changeColor"); MyButton exit = new MyButton("Exit", "exit"); frame.add(change); frame.add(exit); frame.setSize(500, 250); frame.setVisible(true); }
内容的提问来源于stack exchange,提问作者Bootfahrer
相关产品推荐
相关产品推荐

