根据你的意见,你是通过你的工厂方法没有意义
addGB(new JButton("four"),1,1,1,1,1,2); //spans 2 rows
addGB(new JButton("five"),0,2,1,1,2,1); //spans 2 columns
基本上你是说你想跨越2行的坐标...,然后跨越2列,但参数是南辕北辙......
addGB(new JButton("four"),1,1,1,1,2,1); //spans 2 rows
addGB(new JButton("five"),0,2,1,1,1,2); //spans 2 columns
会导致你的意见要求,例如...
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBag2 extends JPanel {
GridBagConstraints constraints = new GridBagConstraints();
public static void main(String args[]) {
JFrame fr = new JFrame("GridBag2 Span R&C");
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
fr.setSize(600, 600);
fr.add(new GridBag2());
fr.setVisible(true);
}
GridBag2() {
setLayout(new GridBagLayout());
constraints.fill = GridBagConstraints.BOTH;
addGB(new JButton("one"), 0, 0, 1.0, 1.0, 1, 1);
addGB(new JButton("two"), 1, 0, 1.0, 1.0, 1, 1);
addGB(new JButton("three"), 2, 0, 1.0, 1.0, 1, 1);
addGB(new JButton("four"), 1, 1, 1, 1, 2, 1); //spans 2 rows
addGB(new JButton("five"), 0, 2, 1, 1, 1, 2); //spans 2 columns
}
void addGB(Component comp, int gx, int gy, double wx, double wy, int h, int w) {
constraints.gridx = gx;
constraints.gridy = gy;
constraints.weightx = wx;
constraints.weighty = wy;
constraints.gridheight = h;
constraints.gridwidth = w;
this.add(comp, constraints);
}
}
但是,别急,什么发生在第二/第三排?第二行基本崩溃,它不再包含任何东西(可用于计算可行高度)
您可以通过使用“空白”组件来解决此问题,这将有助于它做出决定......
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBag2 extends JPanel {
GridBagConstraints constraints = new GridBagConstraints();
public static void main(String args[]) {
JFrame fr = new JFrame("GridBag2 Span R&C");
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
fr.setSize(600, 600);
fr.add(new GridBag2());
fr.setVisible(true);
}
GridBag2() {
setLayout(new GridBagLayout());
constraints.fill = GridBagConstraints.BOTH;
addGB(new JButton("one"), 0, 0, 1.0, 1.0, 1, 1);
addGB(new JButton("two"), 1, 0, 1.0, 1.0, 1, 1);
addGB(new JButton("three"), 2, 0, 1.0, 1.0, 1, 1);
addGB(new JLabel(), 0, 1, 1, 1, 1, 1); //spans 2 rows
addGB(new JButton("four"), 1, 1, 1, 1, 2, 1); //spans 2 rows
addGB(new JButton("five"), 0, 2, 1, 1, 1, 2); //spans 2 columns
}
void addGB(Component comp, int gx, int gy, double wx, double wy, int h, int w) {
constraints.gridx = gx;
constraints.gridy = gy;
constraints.weightx = wx;
constraints.weighty = wy;
constraints.gridheight = h;
constraints.gridwidth = w;
this.add(comp, constraints);
}
}
能否请您发表您预期的结果为PIC? – 2014-09-02 03:52:46
'gridWidth'和'gridHeight'跨越左/下分别... – MadProgrammer 2014-09-02 03:56:04
我没有足够的信誉张贴图片 – mhrzn 2014-09-02 03:58:41