JPanel不会在调整大小时刷新Graphics组件

时间:2014-06-29 23:04:25

标签: java swing graphics jpanel paintcomponent

该程序应该在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);
}
}

1 个答案:

答案 0 :(得分:4)

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

int cellSize, xOffSet;

到:

float cellSize, xOffSet;

另外,改变:

cellSize = (int)getHeight()/numOfCells;

到:

cellSize = getHeight()/(float)numOfCells;

其他一些旁注:

  • 请勿更改paintComponent的展示次数,定义为protected

  • 不要忘记在super.paintComponent(comp);

  • 中添加paintComponent()
  • 请勿致电setSize(),覆盖小组getPreferredSize()pack()。例如:

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

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

  • 尽量提高paintComponent以获得更好的性能和用户体验。你可以移动一些东西,只留下绘画逻辑。