我想创建一个包含许多JComboBox的palet。那样:
for(int x=0; x<MAX; x++){
box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}
在每个JComboBox的右边我想创建许多JTextField。所以,在我的palet中,我会有一些想法:
myJComboBox1 myJTextField
anotherJTextField
anotherJTextField
myJComboBox2 myJTextField
anotherJTextField
anotherJTextField
...
我该怎么办?我尝试了setBounds
和其他布局,例如FlowLayout
和GridLayout
,但没有成功。
答案 0 :(得分:2)
看看GridBagLayout。你可以像桌子一样使用你的窗口。
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设置权重等。它完全按照表格进行调整。这将产生类似的结果:
label textfield
textfield
重新阅读问题。只需用JComboBox替换JLabel,它就可以更好地回答你的问题;)
答案 1 :(得分:2)
GridBagLayout
是最佳解决方案。但是,如果您是Swing的新手,可能会有点过于复杂。在那种情况下:
并循环...
添加示例代码:
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);
}
});
}
}