【发布时间】:2014-10-15 05:47:13
【问题描述】:
我正在尝试将以下 JLabel 添加到 JPanel 的中心:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JLabel;
public class DrawingPanel extends JLabel {
protected void paintComponent(Graphics g){
super.paintComponent(g);
int[] xpoints = {230, 270, 290, 290, 270, 230, 210, 210};
int[] ypoints = {37, 37, 87, 115, 165, 165, 115, 87};
g.setColor(Color.white);
g.fillPolygon(xpoints, ypoints, 8 );
}
}
致以下JPanel:
JPanel jp = new JPanel(new GridBagLayout());
DrawingPanel dp = new DrawingPanel();
jp.add(dp);
但是DrawingPanel JPanel 甚至不会出现。有什么问题?谢谢
【问题讨论】:
-
考虑提供一个runnable example 来证明您的问题。这将导致更少的混乱和更好的响应
-
GridBagLayout使用GridBagConstraints来管理定位。创建一个GridBagConstraints对象,并在添加面板时添加它:jp.add(dp, gbc) -
您的
DrawingPanel没有定义大小的详细信息,因此布局管理器已将其大小调整为0x0以供初学者使用... -
你的“形状”不会居中,因为,嗯......它不是。您的坐标应该根据已知值(如组件的宽度和高度)计算,而不是您编造的一些幻数......另外,为什么从
JLabel...扩展? -
@MadProgrammer 为什么没有定义大小?它有坐标。这些不应该是大小吗?
标签: java swing user-interface graphics layout-manager