【问题标题】:How do I left and right align components in Swing?如何在 Swing 中左右对齐组件?
【发布时间】:2012-08-19 06:13:23
【问题描述】:

我有一个看似简单的问题。我有一些我想向左对齐的标签,但是当我调整大小时,它们开始向中间漂移。这会打乱我计划添加的其他组件的对齐方式。我该怎么做才能让它们保持在左侧?

代码很短,很简单,不知道我的问题出在哪里:

package com.protocase.notes.views;

import com.protocase.notes.model.Note;
import com.protocase.notes.model.User;
import java.awt.Component;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.BevelBorder;

/**
 * @author dah01
 */
public class NotesPanel extends JPanel{

    public NotesPanel(Note note){
        this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
        JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " @ "+note.getDateCreated());
        creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
        creatorLabel.setHorizontalAlignment(JLabel.LEFT);


        JTextArea notesContentsArea = new JTextArea(note.getContents());
        notesContentsArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(notesContentsArea);

        JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified());
        editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        editorLabel.setHorizontalAlignment(JLabel.LEFT);

        this.add(creatorLabel);
        this.add(scrollPane);
        this.add(editorLabel);
        this.setBorder(new BevelBorder(BevelBorder.RAISED));
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame("Notes Panel");
        Note note = new Note();
        User user = new User();
        user.setFirstName("d");
        user.setLastName("h");
        user.setUserID("dah01");
        note.setCreator(user);
        note.setLastEdited(user);
        note.setDateCreated(new Date());
        note.setDateModified(new Date());
        note.setContents("A TEST CONTENTS");
        NotesPanel np = new NotesPanel(note);

        JScrollPane scroll = new JScrollPane(np);
        frame.setContentPane(scroll);
        np.setVisible(true);
        frame.setVisible(true);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

【问题讨论】:

  • 但是您明确地将每个标签的水平对齐方式(即setAlignmentX)设置为左侧...您认为会发生什么?
  • 已编辑:我只是在示例中这样做,我在我的代码中将一个更改为正确的,但它什么也没做。
  • 带有存根用户/注释类:pastebin.com/Si0iCPnG
  • 它看起来像是BoxLayout 的限制。尝试改用BorderLayout。您也可以在自己的 JPanel 中对顶部/底部元素进行分组(使用自己的布局规则)。
  • @dah 你一定会找到知道如何使用BoxLayout 的人 ;) 为什么大多数 StackOverflow 都认为解决方案是在出现问题时更改布局管理器? (p.s. 我对在其他问题上提出相同的建议感到内疚 - BoxLayout 只是我最喜欢的一个,所以当人们建议将其关闭时我觉得很奇怪)。

标签: java swing alignment


【解决方案1】:

如果您想对齐面板中的内容,则必须对齐所有内容。你忘了对齐你的JScrollPane。如果将此行添加到代码中,则应该为您修复对齐方式:

    scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);

你的新构造函数会是什么样子:

public NotesPanel(Note note){
    this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
    JLabel creatorLabel = new JLabel("Note by "+note.getCreator()+ " @ "+note.getDateCreated());
    creatorLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    creatorLabel.setHorizontalAlignment(JLabel.LEFT);


    JTextArea notesContentsArea = new JTextArea(note.getContents());
    notesContentsArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(notesContentsArea);
    scrollPane.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);

    JLabel editorLabel = new JLabel(" -- Last edited by "+note.getLastEdited() +" at "+note.getDateModified());
    editorLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    editorLabel.setHorizontalAlignment(JLabel.LEFT);

    this.add(creatorLabel);
    this.add(scrollPane);
    this.add(editorLabel);
    this.setBorder(new BevelBorder(BevelBorder.RAISED));
}

【讨论】:

  • 这是我一直在寻找的答案。
  • 我想做的只是左对齐并保持代码简单,而无需使用嵌套布局管理器。
【解决方案2】:

根据您的cmets,我建议您与其他一些layout 一起去,我会推荐MigLayout

给你MigLayout:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JTextArea;


public class MigLayoutDemo {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new MigLayoutDemo();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MigLayoutDemo() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        frame.setContentPane(contentPane);
        contentPane.setLayout(new MigLayout("", "[grow]", "[][grow][]"));

        JLabel lblLabel = new JLabel("Label 1");
            lblLabel.setBorder(BorderFactory.createLineBorder(Color.red));
        contentPane.add(lblLabel, "cell 0 0,alignx left");

        JTextArea textArea = new JTextArea();
        contentPane.add(textArea, "cell 0 1,grow");

        JLabel lblLabel_1 = new JLabel("Label 2");
            lblLabel_1.setBorder(BorderFactory.createLineBorder(Color.red));
        contentPane.add(lblLabel_1, "cell 0 2,alignx left");
        frame.setVisible(true);
    }

}

输出:

如您所见,标有红色边框labels没有拉伸到中间,它们是左对齐的。

【讨论】:

  • 但是,我希望它们左对齐,垂直运行。
  • 赞成好的答案和例子,但我真的不想增加对外部库的依赖,因为像左对齐两个标签这样简单的事情。
【解决方案3】:

使用BorderLayout 绝对可以解决您的问题。

this.setLayout(new BorderLayout());

this.add(creatorLabel, BorderLayout.NORTH);
this.add(scrollPane);
this.add(editorLabel, BorderLayout.SOUTH);

或者,如果要在 UI 中显示的组件多于示例代码中显示的组件,您仍然可以使用 GridBagLayout。我知道没有多少人喜欢使用这个,因为它非常冗长,但在我看来,它是 Swing 中最强大的布局管理器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2015-05-09
    • 2014-12-17
    相关资源
    最近更新 更多