我有一个看起来很简单的问题。我有一些我想向左对齐的标签,但是当我调整大小时,它们开始向中间漂移。这会打乱我计划添加的其他组件的对齐方式。我该怎么做才能让它们保持在左侧?
这是简短而简单的代码,不确定我的问题出在哪里:
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);
}
}