我有一个扩展jpanel的主类,和一个使用图形参数的内部类Brick在屏幕上绘制矩形,我试图使这些矩形在面板大小更改时可调整大小 这些Bricks在paintComponent方法中绘制()的宽度和高度也分配在 相同的方法中,我调用paintComponent()每30millis 砖的宽度是面板宽度的百分比,所以我试图将旧的砖宽度保存在一个变量,并增加x砖的坐标由旧砖和新砖宽度之间的差异,但它不会工作如何调整重绘的JComponent?
我有以下代码:
int width,height,brickHeight,brickWidth,tempBWidth,diffrence;
ArrayList<Brick> listOfBricks = new ArrayList<Panel.Brick>();
Timer timer = new Timer(30,this);
boolean bricksFilled,resized;
public Panel() {
setBackground(Color.BLACK);
setVisible(true);
timer.start();
} //end constructor Panel().
protected void paintComponent(Graphics g) {
width = getWidth(); height = getHeight();
setSize(width,height);
tempBWidth = brickWidth;
brickHeight = height/20; brickWidth = width/10;
if(width != 0 && tempBWidth != brickWidth) { diffrence = brickWidth - tempBWidth; }
super.paintComponent(g);
if(bricksFilled == false) { fillListOfBricks(); }
drawBricks(listOfBricks, g);
diffrence = 0;
} //end method paintComponent().
public void actionPerformed(ActionEvent event) {
repaint();
} //end method actionPerformed().
void fillListOfBricks() {
for (int row = 0;row < height/2;row += brickHeight+1) {
for (int column = 0;column < width;column += brickWidth+1) {
if(brickWidth != 0){
listOfBricks.add(new Brick(column,row,true,brickWidth,brickHeight));
bricksFilled = true;
} //end if.
} //end inner loop.
} //end outer loop.
} //end method fillListOfBricks().
void drawBricks(ArrayList<Brick> listOfBricks,Graphics g) {
for (Brick brick:listOfBricks) {
if(listOfBricks.isEmpty() == false) {
if (brick.visible) {
brick.draw(g);
} //end inner if.
} //end outer if.
} //end loop.
} //end method drawBricks().
class Brick {
int x,y;
int width,height,xDiff,yDiff;
boolean visible;
Color randomColor;
Brick(int x,int y,boolean visible,int width,int height) {
this.x = x; this.y = y; this.visible = visible;
this.width = width; this.height = height;
this.randomColor = getRandomColor();
} //end constructor Brick().
void draw(Graphics g) {
if(this.visible) {
System.out.println(diffrence);
g.setColor(this.randomColor);
System.out.println(x+" "+diffrence);
g.fillRect(x+diffrence, y, brickWidth,brickHeight);
g.setColor(Color.WHITE);
g.drawRect(x-1, y-1, brickWidth+1, brickHeight+1);
} // end if block.
} //end method draw().
Color getRandomColor() {
int R = (int)(255*(Math.random()));
int G = (int)(255*(Math.random()));
int B = (int)(255*(Math.random()));
return new Color(R,G,B);
} //end Method getRandomColor.
}
}
感谢您的帮助
'的setSize(宽度,高度)样本代码;'在'paintComponent'方法 - 从未设置paint方法 –
此外内部组件状态,您的要求是不清楚。请尝试添加更具描述性/可理解的问题描述,同时指出问题出现的位置 –
希望它现在更好 – user3612007