[英]Java Swing GUI BorderLayout: Location of components
我是 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 按鈕和矩形的一小部分(甚至不是縮放的矩形)。
為什么矩形在頂部(北)繪制時沒有足夠的空間,但在中心繪制時卻得到了?
DrawingPanel
應該@Override getPreferredSize()
以返回適當的大小。
然后,布局管理器將采用該首選尺寸作為提示。 一些布局管理器會根據布局和約束的邏輯擴展組件的高度或寬度。 例如, BorderLayout
會將PAGE_START
/ PAGE_END
中的組件拉伸到內容窗格的寬度,並將LINE_START
/ LINE_END
到其中最高者或CENTER
的高度。 GridBagLayout
OTOH 將完全隱藏/刪除沒有足夠空間以首選大小顯示它的組件,這就是“pack”的用武之地。
所以改變frame.setSize(500,500);
(這並不比猜測更好)到frame.pack();
,這將使框架成為它需要的最小尺寸,以便顯示它包含的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.