【问题标题】:JPanel does not refresh Graphics component on resizeJPanel 在调整大小时不刷新图形组件
【发布时间】:2014-06-29 23:04:25
【问题描述】:

这个程序应该在JPanel 中绘制一个矩形网格。我通过覆盖其paintComponent 方法将网格绘制到JPanel 上,这样每次JPanel 调整大小时,网格的大小都会改变以适应JPanel 的高度。但是当我更改JFrame 的大小时,网格只会以特定间隔调整大小。有没有更好的方法来改变网格的大小?

import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

class TextFrame extends JPanel
{
int numOfCells = 99;
int cellSize, xOffSet;
Rectangle2D.Float[][] square = new Rectangle2D.Float[numOfCells][numOfCells];

public TextFrame()
{
    setSize(400, 400);
}

public void paintComponent(Graphics comp)
{
    Graphics2D comp2d = (Graphics2D)comp;

    cellSize = (int)getHeight()/numOfCells;
    if(getWidth()<=cellSize*numOfCells)
        cellSize = getWidth()/numOfCells;
    xOffSet = (getWidth()-(cellSize*numOfCells))/2;

    Color black = new Color(0,0,0);
    Color grey = new Color(128,128,128);
    boolean col = true;

    for(int i=0; i<square.length; i++)
    {
        for(int j=0; j<square[i].length; j++)
        {
            if(col)
                comp2d.setPaint(black);
            else
                comp2d.setPaint(grey);
            col = !col;
            square[i][j] = new Rectangle2D.Float(xOffSet+j*cellSize, i*cellSize, cellSize, cellSize);
            comp2d.fill(square[i][j]);
        }
    }

}

public static void main(String[] args)
{
    JFrame frame = new JFrame("Conway's Game Of Life");
    TextFrame life = new TextFrame();
    frame.add(life);
    frame.setSize(life.getHeight(), life.getWidth());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}

【问题讨论】:

    标签: java swing graphics jpanel paintcomponent


    【解决方案1】:

    间隔的原因是整数运算。变化:

    int cellSize, xOffSet;
    

    到:

    float cellSize, xOffSet;
    

    另外,改变:

    cellSize = (int)getHeight()/numOfCells;
    

    到:

    cellSize = getHeight()/(float)numOfCells;
    

    其他一些旁注:

    • 不要改变paintComponent的可见性,它被定义为protected。

    • 别忘了在paintComponent()中添加super.paintComponent(comp);

    • 不要调用setSize(),覆盖面板的getPreferredSize() 和pack() 框架。例如:

      public Dimension getPreferredSize(){return new Dimension(400, 400);}
      

      然后,在使框架可见之前添加frame.pack();。

    • 尽量使paintComponent 尽可能快,以获得更好的性能和用户体验。您可以从中移出一些东西,只留下绘画逻辑。

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多