Java Swing调用repaint后组件被复制到左上角如何解决?
Swing调用repaint后界面元素重复显示问题解决方案
核心故障原因
- 自定义绘制时未正确重写
paintComponent方法,也没有调用父类方法清除上一次的绘制缓存,导致旧内容残留 - JFrame未关闭默认布局管理器,
setBounds绝对定位不生效,且在窗口显示后才添加组件,触发异常绘制 - 字符串比较错误使用
==而非equals,可能导致选择逻辑异常
修复步骤
1. 修正Gui类绘制逻辑
- 将重写的
paint方法改为重写paintComponent - 方法第一行添加
super.paintComponent(g)清除历史绘制内容,这是解决残留重叠的核心
修复后代码:
public class Gui extends JPanel { private int y; // 重写paintComponent而非paint @Override public void paintComponent(Graphics g) { // 调用父类方法清除旧绘制内容 super.paintComponent(g); g.setColor(Color.white); g.fillRect(50, 300, 300, 300); g.setColor(Color.white); g.fillRect(550, 300, 300, 300); if (y == 1) { g.setColor(Color.blue); g.fillRect(50, 300, 300, 300); } if (y == 2) { g.setColor(Color.black); g.fillRect(50, 300, 300, 300); } if (y == 3) { g.setColor(Color.yellow); g.fillRect(50, 300, 300, 300); } } public void selector(String x){ // 字符串比较用equals而非== if (x.equals("paper")){ y = 1; repaint(); System.out.println("paper" + y); } else if (x.equals("rock")) { y = 2; repaint(); System.out.println("rock" + y); } else if (x.equals("scissors")) { y = 3; repaint(); System.out.println("scissors" + y); } } }
2. 修正窗口初始化逻辑
- 先设置JFrame布局为null启用绝对定位
- 给绘制面板设置铺满窗口的尺寸
- 所有组件添加完成后再调用
setVisible(true) - 移除重复的属性设置代码
修复后代码:
public class RockPaperScissors implements ActionListener { JButton rock =new JButton("Select rock"); JButton paper =new JButton("Select paper"); JButton scissors =new JButton("Select scissors"); Gui gui = new Gui(); public void frame() { JFrame b = new JFrame("Rock paper scissors"); // 关闭默认布局,启用绝对定位 b.setLayout(null); rock.setBounds(150,100,120,30); paper.setBounds(350,100,120,30); scissors.setBounds(550,100,120,30); // 设置绘制面板铺满整个窗口 gui.setBounds(0,0,905,705); b.setSize(905,705); b.setLocation(300,60); b.setResizable(false); b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 先添加所有组件 b.add(rock); b.add(paper); b.add(scissors); b.add(gui); rock.addActionListener(this); paper.addActionListener(this); scissors.addActionListener(this); // 所有组件加载完成后再显示窗口 b.setVisible(true); } public static void main(String[] args) { RockPaperScissors start = new RockPaperScissors(); start.frame(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == rock){ gui.selector("rock"); } else if (e.getSource() == paper) { gui.selector("paper"); } else if (e.getSource() == scissors) { gui.selector("scissors"); } } }
内容的提问来源于stack exchange,提问作者jon doe
相关产品推荐
相关产品推荐

