如何在JFrame上放置带有2DGraphics的JPanel(同一个类)

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

我有一个扩展JFrame的类,我想向该JFrame添加两个JPanel:文本面板和图形面板。我的文本面板是一个包含带文本标签的面板。我的图形面板将包含一个图形(使用2DGraphics创建)。我使用gridbaglayout方法将图形面板添加到左侧(0,0),将文本面板添加到右侧(1,0)。但是,图形面板不会显示在框架中。我尝试了很多方法试图让面板显示没有成功。

import java.awt.*;
import javax.swing.*;

public class GraphicsTest extends JFrame {

    private final JPanel textPanel;
    private final JLabel textLabel;

    public GraphicsTest() {
        textPanel = new JPanel(new BorderLayout());
        textLabel = new JLabel("Home label");

        this.setBounds(180, 112, 1080, 675);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridBagLayout());

        textPanel.add(textLabel, BorderLayout.NORTH);

        addComponent(this, new GraphicPanel(), 0, 0, 1, 1, GridBagConstraints.CENTER);
        addComponent(this, textPanel, 1, 0, 1, 1, GridBagConstraints.CENTER);

        this.setVisible(true);
    }

    public class GraphicPanel extends JPanel {

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        public void paintComponents(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            // drawing lots of shapes and lines, removed for readibility
        }   

    }

    public void addComponent(JFrame frame, JComponent component, int x, int y, int width, int height, int align) {
        GridBagConstraints c = new GridBagConstraints();

        c.gridx = x;
        c.gridy = y;
        c.gridwidth = width;
        c.gridheight = height;
        c.weightx = 100.0;
        c.weighty = 100.0;
        c.insets = new Insets(5, 0, 5, 0);
        c.anchor = align;
        c.fill = GridBagConstraints.NONE;

        frame.add(component, c);
    }

    public static void main(String[] args) {
        GraphicsTest gui = new GraphicsTest();
    }

}

java swing jframe jpanel graphics2d
1个回答
1
投票

当我使用像(200,200)这样的尺寸时,对我来说工作正常。

GridbagLayout的工作原理是,如果某个组件无法以其首选大小显示,那么它将以其最小大小显示,即(0,0)。

因此(700,700)是否有效取决于您的屏幕分辨率。它也适用于(700,600)我的屏幕。

我怀疑你是否想使用GridBadLayout。也许只使用BorderLayout。自定义绘画面板将进入CENTER,以便随着框架尺寸的变化而增大/缩小。另一个面板将转到LINE_END,因此它将保持固定大小。

© www.soinside.com 2019 - 2024. All rights reserved.