嗨,我是java的初学者,使用GridBagLayout做小GUI . 请参阅附加的代码以及输出 . 我想要的是按照gridx和gridy中指定的位置将JButtons放在左上角 . 但是如果我使用Insets,gridx / gridy所有工作但不是从正确的坐标,它将组件放置在中心而不是左上方,所以请查看附加的代码和图像并指导我
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);
}
OUTPUT :想要左上角的这些按钮请指导我
1 回答
我认为问题更多的是使用
setSize(..)
,你应该在_24544800_实例上使用适当的LayoutManager
并调用pack()后将所有组件添加到JFrame
并且在设置JFrame
可见之前,也不需要panel.setVisible(..)
: