【发布时间】:2014-11-28 06:16:27
【问题描述】:
public class a5Frame2 extends JFrame implements KeyListener
{
public a5Frame2()
{
super("TV");
setLocation(450, 75);
setFocusable( true );
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel panel = new JPanel();
this.setLayout(new BorderLayout());
panel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
JLabel channelNumber = new JLabel("hello");
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(2, 0, 0, 2);
panel.add(channelNumber, gc);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
mainPanel.add(panel, BorderLayout.NORTH);
this.add(mainPanel);
this.setVisible(true);
this.addKeyListener(this);
}
}
JLabel hello 当前位于 JFrame 的顶部北部。我希望它位于 JFrame 的左上角。我很确定gc.anchor = GridBagConstraints.NORTHWEST; 可以完成这项工作,但在这种情况下它不起作用。有谁知道为什么它不起作用?
【问题讨论】:
-
将
gc.weightx = 1添加到您的约束中 -
this.addKeyListener(this);对于 Swing,我们通常使用 key bindings 而不是较低级别的KeyListener。
标签: java swing jlabel layout-manager gridbaglayout