【问题标题】:How to put a JPanel with 2DGraphics on a JFrame (same class)如何将具有 2DGraphics 的 JPanel 放在 JFrame 上(同一类)
【发布时间】:2019-08-12 23:31:04
【问题描述】:

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

}

【问题讨论】:

  • 一个问题 - 您的图形面板的首选大小看起来是 0、0,并且由于您没有扩展填充或使用会为您扩展的布局(例如网格布局),因此大小可能是 0, 0。
  • 不要覆盖paint()。只需将您的自定义绘画代码放在paintComponent() 方法中即可。阅读 Custom Painting 上的 Swing 教程部分,了解工作示例以及更多信息和工作示例,包括如何覆盖 getPreferredSize() 方法。
  • 我已经覆盖了getPreferredSize() 方法(将尺寸设置为700、700),并将我的自定义绘画代码转移到paintComponent() 方法(删除我最初使用的绘画方法)。面板仍然没有出现,我觉得我错过了一些东西。
  • "我已经覆盖了 getPreferredSize()...." 请更新你的代码

标签: java swing jframe jpanel graphics2d


【解决方案1】:

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

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

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

我怀疑你是否想使用 GridBadLayout。也许只是使用 BorderLayout。自定义绘画面板将位于中心,因此它会随着框架大小的变化而增长/缩小。另一个面板将转到 LINE_END,因此它将保持固定大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多