我想在一行上放置多个JTextField,但不希望它们具有相同的宽度。如何控制其宽度并使某些JTextField更宽?我希望它们共同占据总宽度的100%,因此最好使用一些权重来调整宽度。
我尝试使用 .setColumns()
,但没有效果。
以下是一个示例,在该示例中,我使用了三行和三个字符串,应该按列显示:
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class RowTest extends JPanel {
class Row extends JComponent {
public Row(String str1, String str2, String str3) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
JTextField fld1 = new JTextField(str1);
JTextField fld2 = new JTextField(str2);
JTextField fld3 = new JTextField(str3);
fld1.setColumns(5); // makes no sense
this.add(fld1);
this.add(fld2);
this.add(fld3);
}
}
public RowTest() {
this.setLayout(new GridLayout(5,0));
this.add(new Row("Short", "A long text that takes up more space",
"Short again"));
this.add(new Row("Longer but short", "Another long string", "Short"));
this.add(new Row("Hello", "The long field again",
"Some info"));
}
public static void main(String[] args) {
new JFrame() {{ this.getContentPane().add(new RowTest());
this.pack(); this.setVisible(true); }};
}
}