我在GridBagLayout上遇到了几个小时的问题,但我无法解决问题。我在JFrame中有两个JPanel(包含JTextFields)。第一个(上部)JPanel具有3行和2列的网格。第二个(较低的)JPanel有一个3行3列的网格。我需要将它们对齐,如下图所示(上部JPanel中的白列表示空格;数字表示相对宽度),并且随着窗口大小的变化,比例要保持一致。
我的代码是下一个:
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class FrameWithTwoPanels {
private GridBagConstraints constraints;
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameWithTwoPanels window = new FrameWithTwoPanels();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FrameWithTwoPanels() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 800, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Populate the frame with two Panels
frame.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
// PANEL 1: 3 rows and 2 columns
frame.add(this.createPanel(3, 2), c);
// PANEL 2: 3 rows and 3 columns
c.gridy = 1;
frame.add(this.createPanel(3, 3), c);
frame.pack();
frame.setLocationRelativeTo(null);
}
private JPanel createPanel(int numrows, int numcols){
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
//constraints.fill = GridBagConstraints.BOTH;
for(int row=0; row<numrows; row++){
for(int col =0; col<numcols; col++){
JTextField component = new JTextField(row + "-" + col);
if(col == 0){
constraints.weightx = 0.5;
}else if(col == 1){
constraints.weightx = 0.4;
}else if(col == 2){
constraints.weightx = 0.1;
}
constraints.gridy = row;
constraints.gridx = col;
panel.add(component, constraints);
if(numcols == 2 && col == 1){
// Add auxiliar panel
constraints.weightx = 0.1;
constraints.gridx = col + 1;
panel.add(new JLabel());
}
}
}
panel.setBorder(new TitledBorder("Number of columns: " + numcols));
return panel;
}
}
答案 0 :(得分:0)
这是一种使用普通GridLayout实际上更好的情况。我认为以下代码可以满足您的需求:
private JPanel createPanel(int numrows, int numcols) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(numrows, 3));
for (int row = 0; row < numrows; row++) {
for (int col = 0; col < numcols; col++) {
JTextField component = new JTextField(row + "-" + col);
panel.add(component);
if (numcols == 2 && col == 1) {
JPanel spacer = new JPanel();
panel.add(spacer);
}
}
}
panel.setBorder(new TitledBorder("Number of columns: " + numcols));
return panel;
}