java - 在面板中排列项目

标签 java swing jframe jpanel layout-manager

我正在为我的高中类(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);


    }
}

最佳答案

“简单”是一个相对术语,例如,您可以做类似...

GridLayout

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);

    }

}

或者类似...

GridBagLayout

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);

    }

}

两者都很简单,都可以完成工作,但是您将使用哪个在很大程度上取决于您想要实现的目标...

看看Laying Out Components Within a Container了解更多详情

关于java - 在面板中排列项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499704/

相关文章:

java - JTable(TableModel)与H2数据库连接的任何方式

java - 在框架外显示元素

java - JFileChooser "Save As"复合文档 - 覆盖现有

java - JFrame 和 JOptionPane

java - JFileChooser 不会死?

java - 如何在 Spring Boot 中使用 cron 作业根据指定条件安排作业

java - 无法在 Java 中解析方法

java - 如何模拟 junit 测试的结果元数据

java - 在Java中从MIDI Controller 接收com.sun.media.sound.FastShortMessage,如何解码?

java - 有没有办法在全局范围内收听 swing 中新打开的窗口?