Java 网格布局组件';他的位置不起作用
大家好,我是java初学者,使用GridBagLayout做小型GUI。请参阅所附代码和输出。我想要的是根据在gridx和gridy中指定的位置将JButtons放置在左上角。但它将组件放置在中间,而不是预期的左上角,如果我使用插图,gridx/gridy,所有这些都在工作,但不是从正确的坐标,所以请参阅附加的代码和图像,并指导我Java 网格布局组件';他的位置不起作用,java,swing,gridbaglayout,Java,Swing,Gridbaglayout,大家好,我是java初学者,使用GridBagLayout做小型GUI。请参阅所附代码和输出。我想要的是根据在gridx和gridy中指定的位置将JButtons放置在左上角。但它将组件放置在中间,而不是预期的左上角,如果我使用插图,gridx/gridy,所有这些都在工作,但不是从正确的坐标,所以请参阅附加的代码和图像,并指导我 public rect() { JPanel panel = new JPanel( new GridBagLayout());
public rect()
{
JPanel panel = new JPanel( new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton nb1= new JButton("Button1 ");
JButton nb2= new JButton("Button2 ");
gbc.gridx=0;
gbc.gridy=0 ;
panel.add(nb1, gbc);
gbc.gridx=1;
gbc.gridy=1;
panel.add(nb2, gbc);
panel.setVisible(true);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300 );
frame.add(panel);
frame.setVisible(true);
}
输出:想要左上角的这些按钮,请引导我
我认为问题更多的是使用
setSize(..)
,你应该使用合适的LayoutManager
,在将所有组件添加到JFrame
之后,在设置JFrame
可见之前,调用JFrame
实例,也不需要panel.setVisible(..)
:
我认为问题更多的是使用
setSize(..)
,您应该使用适当的LayoutManager
,在将所有组件添加到JFrame
之后,在设置JFrame
可见之前,调用JFrame
实例,也不需要panel.setVisible(..)
:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel(new GridBagLayout());
JButton nb1 = new JButton("Button1 ");
JButton nb2 = new JButton("Button2 ");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(nb1, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(nb2, gbc);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}