【发布时间】: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