【发布时间】: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