【问题标题】:paintComponent is not erasing JPanelpaintComponent 没有擦除 JPanel
【发布时间】:2016-10-06 13:30:56
【问题描述】:

程序是在 JPanel 上显示 3 个按钮。程序编译成功。 GUI 窗口随即出现并且为空。当我最小化窗口然后再次最大化它时,会出现按钮。再次执行此操作时会出现另一组按钮。当窗口刷新并且旧数据保持不变时,按钮会继续出现。

JPanel 类

class MyJPanel extends JPanel {
JButton jb1, jb2, jb3;

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    jb1 = new JButton();
    jb2 = new JButton("Green");
    jb3 = new JButton("Blue");
    //g.drawString("Welcome!", 100, 100);
    ImageIcon img = new ImageIcon("next.png");
    jb1.setIcon(img);
    jb1.setToolTipText("Button 1");
    this.add(jb1);
    this.add(jb2);
    this.add(jb3);
}
}

JFrame 类

class MyJFrame extends JFrame {
MyJPanel mjp;

public MyJFrame(String title) {
    super(title);

    mjp = new MyJPanel();

    Container ct = getContentPane();
    ct.add(mjp);

    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

驱动类

class Gui5JButton {
public static void main(String[] args) {
    MyJFrame mjf = new MyJFrame("Prakhar");
    mjf.repaint();
}
}

【问题讨论】:

    标签: java swing jpanel jbutton paintcomponent


    【解决方案1】:

    paintComponent 每次需要重绘面板时都会调用,因此每次最小化窗口时都会再次放置按钮。如果我理解您想要正确执行的操作,您需要删除覆盖并输入以下代码:

    jb1 = new JButton();
    jb2 = new JButton("Green");
    jb3 = new JButton("Blue");
    //g.drawString("Welcome!", 100, 100);
    ImageIcon img = new ImageIcon("next.png");
    jb1.setIcon(img);
    jb1.setToolTipText("Button 1");
    this.add(jb1);
    this.add(jb2);
    this.add(jb3);
    

    在 MyJPanel 类的构造函数中。

    【讨论】:

    • 感谢您的及时回复。成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多