关于 swing springlayout 的问题

2019-01-08 20:40:26 +08:00
 chenqh

代码

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 之间会有空隙呢?按理讲,应该没有呀

455 次点击
所在节点    问与答
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/525147

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX