【发布时间】:2010-01-27 15:27:42
【问题描述】:
您好,我想在 JPanel 中获得这个摇摆布局:
JLabel - JTextField - JComboBox
当面板调整大小时,我希望 textField 扩展,而不是其他两个。一切都必须保持一致。我尝试了网格袋布局但不起作用......或者我不能。想法?
【问题讨论】:
-
分享你的代码!这样我们会更容易提供帮助......
您好,我想在 JPanel 中获得这个摇摆布局:
JLabel - JTextField - JComboBox
当面板调整大小时,我希望 textField 扩展,而不是其他两个。一切都必须保持一致。我尝试了网格袋布局但不起作用......或者我不能。想法?
【问题讨论】:
如果您有三个组件并希望中间的一个扩展,例如,您可以使用 BorderLayout,将 JLabel 放在 BorderLayout.WEST,将 JComboBox 放在 BorderLayout.EAST 和你想在 BorderLayout.CENTER 展开的(JTextField)。
以下内容很丑陋,但意图是最小化但显示您想要的行为:
public class Gotch {
public static void main( String[] args ) {
JFrame main = new JFrame();
JPanel p = new JPanel();
p.setLayout( new BorderLayout() );
p.add( new JLabel( "test" ), BorderLayout.WEST );
p.add( new JTextField( "growable" ), BorderLayout.CENTER );
p.add( new JComboBox(), BorderLayout.EAST );
main.add( p );
main.pack();
main.setVisible( true );
}
}
【讨论】:
我想我也会发布一些如何使用 GridBagLayout 来实现它的代码。当您有一些与 BorderLayout 不完全匹配的东西时可能很有用,这在制作 GUI 时很常见。
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setLayout(new GridBagLayout());
JLabel label = new JLabel("Demo Label");
JTextField textField = new JTextField("Demo Text");
JComboBox comboBox = new JComboBox(new String[] {"hello", "goodbye", "foo"});
GridBagConstraints cons = new GridBagConstraints();
cons.insets = new Insets(10, 10, 10, 10);
frame.add(label, cons);
cons.gridx = 1;
cons.weightx = 1;
cons.weighty = 1;
cons.insets = new Insets(10, 0, 10, 10);
cons.fill = GridBagConstraints.HORIZONTAL;
frame.add(textField, cons);
cons.gridx = 2;
cons.weightx = 0;
cons.weighty = 0;
cons.insets = new Insets(10, 0, 10, 10);
cons.fill = GridBagConstraints.NONE;
frame.add(comboBox, cons);
frame.pack();
frame.setVisible(true);
}
}
【讨论】:
扩展Box 是一个不错的选择:
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MyPanel extends Box {
public MyPanel(int axis) {
super(axis);
this.setPreferredSize(new Dimension(320, 240));
JLabel lb = new JLabel("label");
lb.setAlignmentX(JLabel.CENTER_ALIGNMENT);
this.add(lb);
JTextField tf = new JTextField("field");
this.add(tf);
String [] items = { "One", "Two", "Three" };
JComboBox c = new JComboBox(items);
c.setMaximumSize(new Dimension(100, Short.MAX_VALUE));
this.add(c);
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
MyPanel p = new MyPanel(BoxLayout.Y_AXIS);
f.add(p);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
create();
}
});
}
}
【讨论】: