Java Swing GUI BorderLayout:组件的位置

问题描述 投票:0回答:1

我是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绘制时却得到了?

java swing layout-manager border-layout
1个回答
0
投票

DrawingPanel应该为@Override getPreferredSize()以返回适当的大小。

然后,布局管理器将首选大小作为提示。一些布局管理器会根据布局和约束的逻辑来扩展组件的高度或宽度(例如BorderLayout会将PAGE_START / PAGE_END中的组件拉伸到GUI的宽度,以及LINE_START / [LINE_ENDOTOH会完全隐藏/删除一个组件,该组件的[空间将以首选大小显示它。这就是“ pack”进来的地方。

因此,将CENTER(这不比猜测好)更改为GridBagLayout,这将使框架成为

需要

的最小尺寸,以显示其包含的组件。
© www.soinside.com 2019 - 2024. All rights reserved.