代码
import javax.swing.*;
import java.awt.*;
public class C5Ex1_3 {
static final int WIDTH = 600;
static final int HEIGHT = 400;
public static void setMargin(SpringLayout lay, JComponent c, JPanel panel, int north, int west, int east, int south) {
panel.add(c);
if(north != 9999) {
lay.putConstraint(SpringLayout.NORTH, c, north, SpringLayout.NORTH, panel);
}
if (west != 9999) {
lay.putConstraint(SpringLayout.WEST, c, west, SpringLayout.WEST, panel);
}
if(east != 9999) {
lay.putConstraint(SpringLayout.EAST, c, east, SpringLayout.EAST, panel);
}
if(south!=9999) {
lay.putConstraint(SpringLayout.SOUTH, c, south, SpringLayout.SOUTH, panel);
}
}
public static void setMargin(SpringLayout lay, JComponent c, JPanel panel, int north, int west, int east) {
setMargin(lay, c, panel, north, west, east, 9999);
}
public static void main(String[] args) {
JFrame jf = new JFrame("test program");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(WIDTH, HEIGHT);
JPanel panel = new JPanel();
jf.setContentPane(panel);
SpringLayout lay = new SpringLayout();
panel.setLayout(lay);
JTextField tf_out = new JTextField(15);
tf_out.setMaximumSize(tf_out.getPreferredSize());
setMargin(lay, tf_out, panel, 5, 50, -50);
String[] names = {
"1", "2", "3", "%", "ON",
"4", "5", "6", "=", "AC",
"7", "8", "9", ".", "+/-",
"0", "+", "-", "*", "C"
};
// GridLayout
for(int i=0;i<names.length;i++) {
JButton btn = new JButton(names[i]);
System.out.println("size:" + btn.getPreferredSize());
int north = 5 + (i/5+1) *50;
int west = WIDTH/5 * (i%5);
int east = - (5-1-i%5)*(WIDTH/5);
System.out.println("i:" + i+", north:" + north+", west:" + west+", east:" + east);
setMargin(lay, btn, panel, north, west, east);
}
jf.setVisible(true);
}
}
结果
为什么 btn 之间会有空隙呢?按理讲,应该没有呀