我想制作一个具有一个按钮和多个字段的简单程序。当我在脑海中计划这个时,我想使用网格布局,或者至少从我学习开始就把按钮分出来。这是我目前所拥有的,我要引出的问题是我应该将网格布局放在哪里,或者我是否在面板、框架或按钮中设置对齐中心?
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
//button
button.setSize(50, 50);
//Field
field.setSize(250, 25);
//Frame
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(panel);
frame.add(field);
frame.add(button);
}
}
最佳答案
始终将组件添加到 JFrame
的 Container
中。将 Container
的 Layout 设置为 GridLayout
。例如,您可以按如下方式更改代码:
import java.awt.GridLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Normal {
public static void main(String[] args) {
JFrame frame = new JFrame("test");
JButton button = new JButton("why");
JPanel panel = new JPanel();
JTextField field= new JTextField();
Container c = frame.getContentPane();
c.setLayout(new GridLayout(3,1));//Devides the container in 3 rows and 1 column
c.add(panel);//Add in first row
c.add(button);//Add in second row
c.add(field);//Add in third row
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
关于java - 我如何在java中居中对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15442334/