如何将带有2DGraphics的JPanel放在JFrame上(相同的类)

时间:2019-03-22 01:59:03

标签: java swing jframe jpanel graphics2d

我有一个扩展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();
    }

}

1 个答案:

答案 0 :(得分:1)

当我使用(200,200)之类的尺寸时,对我来说效果很好。

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

因此(700,700)是否起作用取决于您的屏幕分辨率。我的屏幕也可以在(700,600)下工作。

我问您是否要使用GridBadLayout。也许只是使用BorderLayout。自定义绘画面板将进入CENTER,因此它将随着帧大小的变化而增大/缩小。另一个面板将转到LINE_END,因此它将保持固定大小。