我有JFrame
一些子JPanel
对象。当我调整 JFrame 的大小并使其变大时,一切正常,子面板的大小也正确调整。但是,如果我缩小 JFrame,面板会保持不变,并且会被裁剪。无论我使用什么布局,都会发生这种情况。
我知道我可以使用EventListener
并手动设置尺寸,但我的问题是:为什么会发生这种情况?为什么放大时可以正常工作,但缩小时却不行?我可以在没有EventListener
(可能是一些配置问题)的情况下解决它吗?
我正在使用 Netbeans 7.3,以防万一。
==== 编辑 ====
在尝试获取最小示例时,我意识到问题是我尝试添加的组件之一,它是由我制作的。它是一个延伸java.awt.Canvas
和绘制排球场的物体。
但是,我无法找出为什么它不能正确收缩。这是代码:
import java.awt.*;
import java.util.Arrays;
import javax.print.attribute.standard.OrientationRequested;
public class CourtCanvas extends Canvas {
private int courtHeight = 100;
private int courtWidth = 200;
private int left = 10;
private int top = 10;
private Point center = new Point();
private Color bgColor = new Color(52, 153, 204);
private Color lineColor = new Color(255, 255, 255);
private Color floorColor = new Color(255, 153, 0);
private OrientationRequested orientation;
public CourtCanvas() {
calcDimensions();
setBackground(bgColor);
for (int i = 0; i < localCoords.length; i++) {
localCoords[i] = new Point();
visitCoords[i] = new Point();
}
}
private void calcDimensions() {
if (this.getHeight() > this.getWidth()) {
orientation = OrientationRequested.PORTRAIT;
courtHeight = (int) Math.min(this.getHeight() * 0.9, this.getWidth() * 1.8);
courtWidth = (int) (courtHeight / 2.0);
}
else {
orientation = OrientationRequested.LANDSCAPE;
courtWidth = (int) Math.min(this.getWidth()* 0.9, this.getHeight() * 1.8);
courtHeight = (int) (courtWidth / 2.0);
}
center.x = (int) (getWidth() / 2.0);
center.y = (int) (getHeight() / 2.0);
left = (int) (center.x - courtWidth / 2.0);
top = (int) (center.y - courtHeight / 2.0);
}
@Override
public void paint(Graphics g) {
setBackground(bgColor);
calcDimensions();
drawFloor(g);
drawLines(g);
}
private void drawFloor(Graphics g) {
g.setColor(floorColor);
g.fillRect(left, top, courtWidth, courtHeight);
}
private void drawLines(Graphics g) {
if (orientation == OrientationRequested.PORTRAIT) {
drawLines_Portrait(g);
}
else {
drawLines_Landscape(g);
}
}
private void drawLines_Portrait(Graphics g) {
g.setColor(lineColor);
// perimeter
g.drawRect(left, top, courtWidth, courtHeight);
// center line
g.drawLine(left, center.y, left + courtWidth, center.y);
// local attack line
g.drawLine(left, center.y + courtHeight / 6, left + courtWidth, center.y + courtHeight / 6);
// visitor attack line
g.drawLine(left, center.y - courtHeight / 6, left + courtWidth, center.y - courtHeight / 6);
}
private void drawLines_Landscape(Graphics g) {
g.setColor(lineColor);
// perimeter
g.drawRect(left, top, courtWidth, courtHeight);
// center line
g.drawLine(center.x, top, center.x, top + courtHeight);
// local attack line
g.drawLine(center.x - courtWidth / 6, top, center.x - courtWidth / 6, top + courtHeight);
// visitor attack line
g.drawLine(center.x + courtWidth / 6, top, center.x + courtWidth / 6, top + courtHeight);
}
}