positionnig myJTextField 在 JComboBox 旁边

positionnig myJTextField beside JComboBox

我想创建一个包含许多 JComboBox 的调色板。像那样:

for(int x=0; x<MAX; x++){
    box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}

在每个 JComboBox 的右侧,我想创建许多 JTextField。所以,在我的调色板中,我会有这样的想法:

myJComboBox1          myJTextField
                      anotherJTextField
                      anotherJTextField



myJComboBox2          myJTextField
                      anotherJTextField
                      anotherJTextField
...

请问我该怎么做?我尝试了 setBounds 和其他布局,如 FlowLayoutGridLayout 但没有成功。

看看GridBagLayout。您可以像 table 一样使用 window。

myPanel.setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;

JLabel lbl = new JLabel("bla");
myPanel.add(lbl, gbc);

gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 3;

JTextField tf = new JTextField();
myPanel.add(tf, gbc);

gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 3;

JTextField othertf = new JTextField();
myPanel.add(othertf, gbc);

您甚至可以为 GridBagConstraints 设置权重等。完全调整为table。这将导致类似的结果:

label      textfield
           textfield

重新阅读问题。只需将 JLabel 替换为 JComboBoxes 即可更好地回答您的问题 ;)

GridBagLayout 是最好的解决方案。但是,如果您是 Swing 新手,它可能有点过于复杂。在那种情况下:

  1. 主面板使用 GridLayout(0, 2)。
  2. 将组合框包裹在具有边框布局的面板中,并将其添加到北方。将其添加到主面板。
  3. 使用带有 GridLayout(0,1) 的另一个面板,将您的文本字段添加到其中并将其添加到主面板。

并循环...

添加示例代码:

package snippet;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class BorderLayoutTest extends JFrame {

    static private int MAX = 10 ;

    public BorderLayoutTest() {
        super(BorderLayoutTest.class.getName());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridLayout(0, 2));
        for(int i = 0; i < MAX; i++) {
            add(createComboPanel());
            add(createPanelWithTextFields());
        }
        pack();
    }

    public Component createComboPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JComboBox<>(new String[] { "First Option", "Second Option", "Third Option" }), BorderLayout.NORTH);
        return panel;
    }

    private Component createPanelWithTextFields() {
        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(new JTextField(30));
        panel.add(new JTextField(30));
        panel.add(new JTextField(30));
        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override public void run() {
                new BorderLayoutTest().setVisible(true);
            }
        });
    }

}