我是Java的新手,我在玩一个简单的GUI示例:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class DrawTest {
class DrawingPanel extends JPanel {
private Rectangle2D shape;
public DrawingPanel(Rectangle2D shape) {
this.shape = shape;
}
public void paintComponent(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
super.paintComponent(g2D);
g2D.setColor(new Color(31, 21, 1));
g2D.fill(shape);
}
}
public void draw() {
JFrame frame = new JFrame();
Rectangle2D shape = new Rectangle2D.Float();
final DrawingPanel drawing = new DrawingPanel(shape);
shape.setRect(0, 0, 400, 400);
frame.getContentPane().add(BorderLayout.NORTH, new JButton("TestN"));
frame.getContentPane().add(BorderLayout.SOUTH, new JButton("TestS"));
frame.getContentPane().add(BorderLayout.EAST, new JButton("TestE"));
frame.getContentPane().add(BorderLayout.WEST, new JButton("TestW"));
frame.getContentPane().add(BorderLayout.CENTER, drawing);
frame.pack();
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
public class DrawMain {
public static void main(String[] args) {
DrawTest test = new DrawTest();
test.draw();
}
}
正如预期的那样,此代码生成一个框架,该框架的中心是矩形,周围是按钮。但是,如果我这样更改代码:
frame.getContentPane().add(BorderLayout.NORTH, drawing);
frame.getContentPane().add(BorderLayout.SOUTH, new JButton("TestS"));
frame.getContentPane().add(BorderLayout.EAST, new JButton("TestE"));
frame.getContentPane().add(BorderLayout.WEST, new JButton("TestW"));
frame.getContentPane().add(BorderLayout.CENTER, new JButton("TestC"));
“ TestC”按钮在中间有一个很大的区域,而矩形没有足够的空间。如果我删除其他按钮(TestS,TestE,TestW),这甚至是正确的:我在顶部得到一个巨大的TestC按钮和一小部分矩形(即使不是缩放矩形)。
为什么矩形在顶部绘制时(北方)没有足够的空间,而在CENTER绘制时却得到了?
DrawingPanel
应该为@Override getPreferredSize()
以返回适当的大小。
然后,布局管理器将首选大小作为提示。一些布局管理器会根据布局和约束的逻辑来扩展组件的高度或宽度(例如BorderLayout
会将PAGE_START
/ PAGE_END
中的组件拉伸到GUI的宽度,以及LINE_START
/ [LINE_END
OTOH会完全隐藏/删除一个组件,该组件的[空间将以首选大小显示它。这就是“ pack”进来的地方。
CENTER
(这不比猜测好)更改为GridBagLayout
,这将使框架成为需要
的最小尺寸,以显示其包含的组件。