【问题标题】:positioning with Java Swing使用 Java Swing 定位
【发布时间】:2011-04-17 17:20:55
【问题描述】:

我是 Swing 新手。这是我写的代码

import java.awt.*;
import javax.swing.*;
public class NewMain {
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame("test");
        frame.setVisible(true);
        frame.setSize(300,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        addItem(panel, new JLabel("Label"), 0, 0, GridBagConstraints.EAST);
        frame.add(panel);
    }

    private static void addItem(JPanel p, JComponent gc, int i, int i0, int align) {
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5,5,5,5);
        c.gridx = i;
        c.gridy = i0;
        c.anchor = align;
        p.add(gc,c);

    }

当我运行程序时,无论我作为align 参数传递什么(GridBagConstraints.NORTHGridBagConstraints.SOUTH 等...),我的标签都在面板的中心对齐。

如何更改标签的对齐方式?

提前致谢。

【问题讨论】:

    标签: java swing alignment


    【解决方案1】:

    这是因为 JLabel 是 GUI 中的唯一组件。如果您添加更多组件,它将根据其位置相对于它们进行布局。这是您的 prog 的扩展,添加了一个空面板:

    import java.awt.*;
    import javax.swing.*;
    
    
    public class NewMain {
    
        public static void main(String[] args) {
            // TODO code application logic here
            JFrame frame = new JFrame("test");
            frame.setVisible(true);
            frame.setSize(300,300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            panel.setLayout(new GridBagLayout());
    
            JPanel emptyArea = new JPanel();
            emptyArea.setPreferredSize(new Dimension(200, 200));
            addItem(panel, new JLabel("Label"), 0, 0, GridBagConstraints.WEST);
            addItem(panel, emptyArea, 0, 0, GridBagConstraints.CENTER);
            frame.add(panel);
        }
    
        private static void addItem(JPanel p, JComponent gc, int i, int i0, int align) {
            GridBagConstraints c = new GridBagConstraints();
            c.insets = new Insets(5,5,5,5);
            c.gridx = i;
            c.gridy = i0;
            c.anchor = align;
            p.add(gc,c);
    
        }
    }
    

    【讨论】:

    • 澄清@DrDipShit 所说的:您的标签确实按照您在面板中所需的方式对齐。但是,这是您的面板,位于 JFrame 内容窗格的中心。您可以尝试做 frame.setLayout(new GridBagLayout()) 并在任何地方用 frame.getContentPane() 替换面板。
    • ^okay 会试试的,也想问一下,如果我必须将我的组件放在左上角,GridBagConstraints.NORTHWEST 会起作用吗?
    • 是的,它应该可以工作。这意味着它的单元格的“左上角”,当然不是整个面板。
    【解决方案2】:

    由于 GridBagConstraint 中 weightx 的默认值为零,因此整个布局保持尽可能小并以父组件为中心。使用非零正数weightx 使组件使用整个水平长度,因此布局将占用所有可用空间。对于垂直方向,weighty 相同。

    ...
    c.anchor = align;
    c.weightx = 1.0:
    ...
    

    Javadoc:weightx

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2019-02-06
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多