![](/img/trans.png)
[英]Why isn't my Java GUI GridBagLayout putting my JPanel Grid in the middle of the frame?
[英]Why isn't my JLabel centering in the middle of JPanel (GridBagLayout) in Java GUI?
我正在嘗試將以下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
甚至不會顯示。 怎么了? 謝謝
0x0
,因為這是默認大小 0x0
... JLabel
擴展? JLabel
具有足夠復雜的功能,而您無需嘗試添加它。 您應該基於已知值(例如組件的寬度和高度)進行計算,還應該提供一些有關希望組件在最佳環境下的首選尺寸的想法,例如...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(new DrawingPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawingPanel extends JPanel {
public DrawingPanel() {
setBorder(new EmptyBorder(8, 8, 8, 8));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Insets insets = getInsets();
g2d.translate(insets.top, insets.left);
int width = getWidth() - 1 - (insets.left + insets.right);
int height = getHeight() - 1 - (insets.top + insets.bottom);
int vHalf = height / 2;
int hHalf = width / 2;
int vPos = vHalf / 4;
int hPos = hHalf / 4;
int[] xpoints = {
0,
hHalf - hPos,
hHalf + hPos,
width,
width,
hHalf + hPos,
hHalf - hPos,
0
};
int[] ypoints = {
vHalf - vPos,
0,
0,
vHalf - vPos,
vHalf + vPos,
height,
height,
vHalf + vPos,
};
g2d.setColor(Color.BLACK);
g2d.drawPolygon(xpoints, ypoints, xpoints.length);
g2d.dispose();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.