gpt4 book ai didi

java - Swing样本表格申请

转载 作者:行者123 更新时间:2023-11-30 07:18:49 25 4
gpt4 key购买 nike

我想出了下面的代码:

    String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;

JFrame frame = new JFrame("SpringDemo1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.

Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);

for (int i = 0; i < numPairs; i++)
{
JLabel lable = new JLabel(labels[i]);
contentPane.add(lable);
contentPane.add(new JTextField(15));
}
//Display the window.
frame.pack();
frame.setVisible(true);

期望:

enter image description here

我得到了什么:
默认值:

enter image description here


调整大小时:

enter image description here

结果与代码实际/正常的样子无关!

我还尝试复制粘贴并运行现成的代码:从here 下载:

结果是这样的:

enter image description here

最佳答案

要使用 SpringLayout 将组件放在正确的位置,您应该使用 ( SpringUtilities class ),下载它然后将其包含在您的项目中。你的代码应该是:

private static void createAndShowGUI() {
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;

//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < numPairs; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}

//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad

//Create and set up the window.
JFrame frame = new JFrame("SpringForm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set up the content pane.
p.setOpaque(true); //content panes must be opaque
frame.setContentPane(p);

//Display the window.
frame.pack();
frame.setVisible(true);
}

希望对你有帮助!

关于java - Swing样本表格申请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15113600/

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