Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Swing中左右对齐组件?_Java_Swing_Alignment - Fatal编程技术网

Java 如何在Swing中左右对齐组件?

Java 如何在Swing中左右对齐组件?,java,swing,alignment,Java,Swing,Alignment,我有一个看似简单的问题。我有一些标签,我想左对齐,但当我调整大小,他们开始向中间漂移。这将摆脱我计划添加的其他组件的对齐。我该怎么做才能把它们保持在左边 这是一个简短、简单的代码,不确定我的问题是什么: package com.protocase.notes.views; import com.protocase.notes.model.Note; import com.protocase.notes.model.User; import java.awt.Component; import

我有一个看似简单的问题。我有一些标签,我想左对齐,但当我调整大小,他们开始向中间漂移。这将摆脱我计划添加的其他组件的对齐。我该怎么做才能把它们保持在左边

这是一个简短、简单的代码,不确定我的问题是什么:

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);
    }
}

根据您的评论,我建议您使用其他
布局
,我建议

这里您可以使用
migrayout

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);
    }

}
输出:


如您所见,标有红色边框的
标签
没有拉伸到中间,而是左对齐

使用
BorderLayout
肯定能解决您的问题

this.setLayout(new BorderLayout());

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


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

如果你想对齐面板中的内容,你必须对齐所有内容。您忘记对齐
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));
}

但是,您明确地将每个标签的水平对齐(即,
setAlignmentX
)设置在左侧……您认为会发生什么?编辑:在示例中,我只是这样做,我的代码中有一个更改为右侧,但它什么也不做。对于存根用户/注释类:它看起来像是
BoxLayout
的限制。试着改用。您还可以在自己的JPanel中对顶部/底部元素进行分组(使用它们自己的布局规则)。@dah您一定会找到知道如何使用
BoxLayout
;)为什么大多数StackOverflow认为只要出现问题,解决方案就会更改布局管理器?(顺便说一句,我对在其他问题上提出同样的建议感到内疚——BoxLayout只是我最喜欢的一个,所以当人们建议把它关掉时,我觉得很奇怪。)但是,我希望他们保持左对齐,垂直运行。向上投票选择好的答案和示例,但我真的不想增加对外部库的依赖性,例如左对齐两个标签。这就是我一直在寻找的答案。我只想左对齐,并保持代码简单,而不必使用嵌套的布局管理器。