问题描述
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public test() {
setLocationByPlatform(true);
setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationByPlatform(true);
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.LINE_START;
constraints.insets = new Insets(5,5,5);
JRadioButton button1 = new JRadioButton("Aaaaaaaaa");
JRadioButton button2 = new JRadioButton("Bbbb");
JRadioButton button3 = new JRadioButton("cccccC");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(new JLabel("Test"),createConstraints(0,0));
panel.add(button1,1));
panel.add(button2,createConstraints(1,1));
panel.add(button3,createConstraints(2,1));
JTextField text = new JTextField();
GridBagConstraints c = createConstraints(0,2);
c.gridwidth = 3;
panel.add(text,c);
add(panel,BorderLayout.PAGE_START);
setSize(350,360);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokelater(() -> {
Test frame = new test();
frame.setVisible(true);
});
}
private GridBagConstraints createConstraints(int x,int y) {
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(5,5);
c.gridx = x;
c.gridy = y;
return c;
}
}
它创建:
但我需要文本字段始终跨越 2 列并且所有内容都要左对齐:
我该怎么做?