所以我正在使用外部类和内部类制作示例 GUI。我做了两个内部类。首先是父类,它是“第一个面板”,其次我创建了一个子类,它是“第二个面板”,我在其中使用 GridBagLayout 添加了 JButton。我的问题是它不会移动到我想要的位置。我分配了我的 gridx = 2 和 gridy = 1。但它不会移动。任何帮助将不胜感激!
public class Login extends JFrame{
mainPanel mainpanel = new mainPanel(); // I create a class object for mainPanel so I can set as ContentPane.
//Constructor
public Login(){
setSize(500,400);
setTitle("Login Sample");
setVisible(true);
setLocationRelativeTo(null);
getContentPane().add(mainpanel);
//Window Listener
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}//window Closing
});
}
class mainPanel extends JPanel { //InnerClass
firstPanel firstpanel = new firstPanel();
//Constructor
public mainPanel(){
setPreferredSize(new Dimension (500,400));
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.green, 3));
add(firstpanel);
}
class firstPanel extends JPanel{
//Create Button
JButton loginButton = new JButton("Login");
//Constraints
GridBagConstraints loginConstraints = new GridBagConstraints();
public firstPanel(){
setLayout(new GridBagLayout());
loginConstraints.gridx = 1;
loginConstraints.gridy = 2;
add(loginButton,loginConstraints);
}
}
最佳答案
JButton keep position in the center
您的 JButton 始终将自己居中到框架中心的原因与内部类无关。每个容器(例如 JPanel、JFrame)都有一个默认布局。
JPanel 的默认布局是 FlowLayout。在这种布局下,所有添加的组件将以线性方式排成一行,以尽可能适应面板宽度。任何超过面板宽度的内容都会被推到下一行。 JPanel 使用的流布局的默认对齐方式是 FlowLayout.CENTER
,这就是为什么当您只添加一个按钮时,它总是居中。
由于它有一个布局来控制组件的位置,因此尝试更改组件的位置可能会徒劳无功。
My problem is it wont move in the location I want. I assigned my gridx = 2 and gridy = 1. But it won't move
如果您希望您的组件移动到您指定的特定位置,您可以将布局设置为null
(绝对定位)。但是,这样做时,您将必须设置您手动添加的每个组件的位置。否则,组件甚至不会显示在框架中。
要将面板的布局设置为空,您可以这样做:
JPanel pnlMain = new JPanel();
pnlMain.setLayout(null);
要设置组件的位置,我们可以使用setBounds()
:
JButton btn = new JButton();
btn.setBounds(x, y, width, height); //set location and dimension
但是,将容器的布局设置为 null
会给您带来许多无法预料的问题。随着布局被删除并且所有定位都被硬编码,当您的程序在不同的系统和环境中使用时,您几乎没有或没有控制权。用户的各种使用也可能导致不可预见的问题(例如,当用户调整窗口大小时)。
关于java - JButton 保持在中心的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701781/