【发布时间】:2015-09-27 02:08:37
【问题描述】:
我有一个项目需要我创建一个简单的 GUI,该 GUI 在顶部有一个 jTextArea,并添加了从 0 到 9 的 JButton。这很简单,但是程序要求我将 0 放在底部的中心.下面的代码实现了这一点,但是我必须使用网格布局而不是 flowLayout。当我用 GridLayout 编写它时,我无法让 0 与左侧对齐。如何使用 GridLayout 并将 0 居中?
public class CalculatorProject {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
GUI gui = new GUI();
}
}
public class GUI extends JFrame {
public GUI() {
JFrame aWindow = new JFrame("Calculator");
aWindow.setBounds(30, 30, 175, 215); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField jta = new JTextField(20);
FlowLayout flow = new FlowLayout(); // Create a layout manager
flow.setHgap(5); // Set the horizontal gap
flow.setVgap(5);
flow.setAlignment(FlowLayout.CENTER);
Container content = aWindow.getContentPane(); // Get the content pane
content.setLayout(new GridLayout(4,3,5,5));
content.setLayout(flow); // Set the container layout mgr
content.add(jta);
// Now add six button components
int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3, 0};
for (int i = 0; i <= 9; i++) {
content.add(new JButton("" + array[i]));
}
aWindow.setVisible(true); // Display the window
}
}
【问题讨论】:
-
为什么不用BorderLayout?这很简单。
-
@CodeRunner:他需要一个使用 BorderLayout 的 JPanel,并在其中嵌套一个 GridLayout JPanel。
-
好的。也请查看我的答案。它可能会对你有所帮助。
标签: java swing jbutton containers