【发布时间】: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 只是我最喜欢的一个,所以当人们建议将其关闭时我觉得很奇怪)。