我是Swing的新手。这是我写的代码
import java.awt.*;
import javax.swing.*;
public class NewMain {
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("test");
frame.setVisible(true);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
addItem(panel, new JLabel("Label"), 0, 0, GridBagConstraints.EAST);
frame.add(panel);
}
private static void addItem(JPanel p, JComponent gc, int i, int i0, int align) {
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5,5,5,5);
c.gridx = i;
c.gridy = i0;
c.anchor = align;
p.add(gc,c);
}
运行程序时,无论我作为
align
参数(GridBagConstraints.NORTH
或GridBagConstraints.SOUTH
等...)通过什么,我的标签都在面板中央对齐。如何更改标签的对齐方式?
提前致谢。
最佳答案
这是因为JLabel是GUI中的唯一组件。如果添加更多组件,它将根据其位置相对于它们进行布局。这是您的编的扩展,其中添加了一个空面板:
import java.awt.*;
import javax.swing.*;
public class NewMain {
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("test");
frame.setVisible(true);
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
JPanel emptyArea = new JPanel();
emptyArea.setPreferredSize(new Dimension(200, 200));
addItem(panel, new JLabel("Label"), 0, 0, GridBagConstraints.WEST);
addItem(panel, emptyArea, 0, 0, GridBagConstraints.CENTER);
frame.add(panel);
}
private static void addItem(JPanel p, JComponent gc, int i, int i0, int align) {
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5,5,5,5);
c.gridx = i;
c.gridy = i0;
c.anchor = align;
p.add(gc,c);
}
}