How do you draw a filled square box in Java that is exactly in the center of an applet window? and when resizing the开发者_开发百科 window, it is centered horizontally and vertically within the applet window? I want it to adapt to the vertical height of the screen but stay square even as the horizontal width edges. If the window is resized to be too narrow, then the sides might cut off?
Here's an example of a panel that will either make a 30px square in the middle, or resize with the panel. Perhaps it can give you enough to make progress.
private class MyPanel extends JPanel{
int height = 30;//30 pixels high.
int width = 30;//30 pixels wide.
boolean resize = true;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int verticalCenter = this.getHeight()/2;
int horizontalCenter = this.getWidth()/2;
if(!resize){
int topLeftSquareCornerY = verticalCenter - (height/2);
int topLeftSquareCornerX = horizontalCenter - (width/2);
g.setColor(Color.BLUE);
g.drawRect(topLeftSquareCornerX, topLeftSquareCornerY, width, height);
}else{
g.setColor(Color.GREEN);
g.drawRect(15,15,(this.getWidth()-30), this.getHeight()-30);
}
}
}
Sounds like your basic problem is figuring out how to place a given rectangle correctly. You need to have the middle of the screen in the middle of the rectangle.
The distance from the middle of the rectangle to its sides are half the height and length respectively.
So x1, x2 = middle_x ± width/2, and y1, y2 = middle_y ± height/2.
I'm guessing you want to draw a square with a fixed size
that stays in the center
of the panel as the panel is resized. One approach to such problems is start from the end and work backward. You know about fillRect()
, so write down what you need to "fill on the blanks" required by that method. Call the center
coordinates x
and y
. The top corner would be half of size
up, and the left corner would be half of size
to the left; the square's width and height would be just size
:
g.fillRect(left, top, width, height);
g.fillRect(x - size/2, y - size/2, size, size);
Now go back and figure out that x
and y
are half the panel's width and height, respectively:
int x = getWidth() / 2;
int y = getHeight() / 2;
Now put it all together in your paintComponent()
method.
精彩评论