gpt4 book ai didi

Java 组织的网格布局

转载 作者:行者123 更新时间:2023-12-01 16:35:58 25 4
gpt4 key购买 nike

我正在制作一个程序,要求用户提供一个整数,然后它应该根据整数的大小显示一个像这样的新窗口。

如果用户输入 2,这将是布局:

Enter test score:    JTextField over here
Enter test score: JTextField over here
Reset Submit

出于某种原因,我无法使 java 中的网格布局每行只有 2 列。

这是我的代码:

public void createAverageGUI()
{
averageFrame = new JFrame("Get All Test Scores");
txtAllAverages = new JTextField[testCount];
averageFrame.setLayout(new GridLayout(2, testCount));
for (int i = 0; i < testCount; i++)
{
averageFrame.add(new JLabel("Enter test score: "));
JTextField field = new JTextField(10);
averageFrame.add(field);
txtAllAverages[i] = field;
}
averageFrame.add(resetAverages);
averageFrame.add(submitAverages);
averageFrame.setSize(400, 600);
averageFrame.setVisible(true);
}

最佳答案

这个 GUI 真正需要的是完全不同的布局。这是您计划的 GUI 的外观。

enter image description here

以下是它应该如何布局。

enter image description here

ExcellentGUI.java

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class ExcellentGUI {

private JTextField[] txtAllAverages;
int testCount = 2;

public void createAverageGUI()
{
txtAllAverages = new JTextField[testCount];

JPanel inputControls = new JPanel(new BorderLayout(5,5));

JPanel inputControlsLabels = new JPanel(new GridLayout(0,1,3,3));
JPanel inputControlsFields = new JPanel(new GridLayout(0,1,3,3));
inputControls.add(inputControlsLabels, BorderLayout.WEST);
inputControls.add(inputControlsFields, BorderLayout.CENTER);
for (int i = 0; i < testCount; i++)
{
inputControlsLabels.add(new JLabel("Test score: "));
JTextField field = new JTextField(10);
inputControlsFields.add(field);
txtAllAverages[i] = field;
}

JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER,5,2));

controls.add(new JButton("Reset"));
controls.add(new JButton("Submit"));

JPanel gui = new JPanel(new BorderLayout(10,10));
gui.setBorder(new TitledBorder("Averages"));
gui.add(inputControls, BorderLayout.CENTER);
gui.add(controls, BorderLayout.SOUTH);

JFrame averageFrame = new JFrame("Get All Test Scores");
averageFrame.setContentPane(gui);
// let the components assume the natural size
// averageFrame.setSize(400, 600);
averageFrame.pack();
averageFrame.setLocationByPlatform(true);
averageFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
averageFrame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ExcellentGUI().createAverageGUI();
}
});
}
}

关于Java 组织的网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9051151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com