JButtons在paintComponent()中扮演的角色

Zma*_*337 3 java graphics swing paintcomponent

我很抱歉没有描述性的标题,但我不知道如何沟通这些问题.对于初学者来说,JButton每次都会按照循环创建它们的顺序多次创建自己.我遇到的另一个问题是,当我使用setLocation()方法重新定位它时,它会在我想要它们的地方创建新的JButton,但也会留下旧的JButton.我不知道我是否只需刷新图形或发生了什么.谢谢您的帮助.

数组playerHand()在Player类中定义,长度为5.

public void paintComponent(java.awt.Graphics g){
    setBackground(Color.GREEN);

    // create a Graphics2D object from the graphics object for drawing shape
    Graphics2D gr=(Graphics2D) g;

    for(int x=0;x<Player.hand.size();x++){
        Card c = Player.hand.get(x);                    //c = current element in array
        c.XCenter = 30 + 140*x;                         
        c.XCord = c.XCenter - 30;
        c.YCord = 0;


        //5 pixel thick pen
        gr.setStroke(new java.awt.BasicStroke(3));            
        gr.setColor(Color.black);                       //sets pen color to black
        gr.drawRect(c.XCord, c.YCord, c.cardWidth-1, c.cardHeight-1);          //draws card outline
        gr.setFont(new Font("Serif", Font.PLAIN, 18));

        gr.drawString(c.name, c.XCord+10, c.YCord+20);

        gr.drawString("Atk: ", c.XCord+10, c.YCord+60);
        gr.drawString(""+c.attack, c.XCord+60, c.YCord+60);

        gr.drawString("Def: ", c.XCord+10, c.YCord+80);
        gr.drawString(""+c.defence, c.XCord+60, c.YCord+80);

        gr.drawString("HP: ", c.XCord+10, c.YCord+100);
        gr.drawString(""+c.health, c.XCord+60, c.YCord+100);

        JButton button = new JButton(c.name);
        button.setSize(c.cardWidth, c.cardHeight);
        //button.setLocation(c.XCord, c.YCord);
        this.add(button);
        repaint();
    }
}   //end of paintComponent
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

您的方法中有几个问题(标有"!!!!"注释):

public void paintComponent(java.awt.Graphics g){
    setBackground(Color.GREEN); // !!!!
    Graphics2D gr=(Graphics2D) g;
    for(int x=0;x<Player.hand.size();x++){

        // .... etc ....

        JButton button = new JButton(c.name);  // !!!! yikes !!!!
        button.setSize(c.cardWidth, c.cardHeight);
        //button.setLocation(c.XCord, c.YCord);
        this.add(button);  // !!!! yikes !!!!
        repaint();  // !!!!
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 不要在GUI中添加组件paintComponent(...).永远不要这样做.永远.
  • 此方法应仅用于绘图和绘图,而不应用于程序逻辑或GUI构建.
  • 您无法完全控制何时或是否将其被调用.
  • 它需要尽可能快,以免使您的程序响应不佳.
  • paintComponent(...)尽可能避免在对象内创建.
  • 避免使用此方法中的文件I/O(尽管上面的代码没有问题).
  • 不要打电话给setBackground(...)这个方法.在构造函数或其他方法中执行此操作.
  • 永远不要repaint()在这种方法中打电话.
  • 不要忘记paintComponent(g)在覆盖中调用super的方法.

回顾你的问题:

对于初学者来说,JButton每次都会按照循环创建它们的顺序多次创建自己.

这是因为您无法控制paintComponent的调用时间或频率.JVM可以响应来自操作系统的关于脏区域的信息来调用它,或者程序可以请求重新绘制,但是由于这个原因,程序逻辑和gui构建永远不应该在这种方法中.

我遇到的另一个问题是,当我使用setLocation()方法重新定位它时,它会在我想要它们的地方创建新的JButton,但也会留下旧的JButton.

你可能很难看到你没有调用super的paintComponent方法的图像残余.如果不这样做,则表示您没有重新绘制JPanel并删除需要替换或刷新的旧图像像素.

我不知道我是否只需刷新图形或发生了什么.

不,你需要改变一切.

看起来您必须重新考虑GUI的程序流和逻辑并重新编写一些代码.