我正在为我的高中类(class)编写一个小项目,但现在我在使用框架时遇到了一些问题。我正在尝试找到在 Java 7 中安排面板内容的最简单和最有效的方法(注意:这意味着 SpringUtilities 不是一个选项)
对于每个项目的排列,我希望它可以选择在顶部输入你的名字,然后在名称框下方的同一行中有 3 个按钮
我目前的代码是
private static void userInterface(){
//Declare and assign variables
final String[] options = {"Lvl 1", "Lvl 2", "Lvl 3"};
int optionsAmt = options.length;
//Create the panel used to make the user interface
JPanel panel = new JPanel(new SpringLayout());
//Create the name box
JTextField tf = new JTextField(10);
JLabel l = new JLabel("Name: ");
l.setLabelFor(tf);
panel.add(l);
panel.add(tf);
//Create 3 buttons with corresponding values of String options
for(int a = 0; a < optionsAmt; a++){
JButton b = new JButton(options[a]);
panel.add(new JLabel());
panel.add(b);
}
//Layout the panel
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.pack();
f.setTitle("Number Game");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
最佳答案
“简单”是一个相对术语,例如,您可以做类似...
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(2, 1));
JPanel fieldPane = new JPanel();
fieldPane.add(new JTextField(10));
add(fieldPane);
JPanel buttonPane = new JPanel();
buttonPane.add(new JButton("1"));
buttonPane.add(new JButton("2"));
buttonPane.add(new JButton("3"));
add(buttonPane);
}
}
或者类似...
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 3;
gbc.gridx = 0;
gbc.gridy = 0;
add(new JTextField(10), gbc);
gbc.gridwidth = 1;
gbc.gridy = 1;
add(new JButton("1"), gbc);
gbc.gridx++;
add(new JButton("2"), gbc);
gbc.gridx++;
add(new JButton("3"), gbc);
}
}
两者都很简单,都可以完成工作,但是您将使用哪个在很大程度上取决于您想要实现的目标...
关于java - 在面板中排列项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499704/