基本上我需要让一个JLabel组件与它的父JPanel顶部对齐。
这是我的代码:
public static JPanel createBoldLabelPanel(String labelText, Component c, Font font, Color c1){
c.setFont(new Font(font.getName(), Font.PLAIN, font.getSize()));
c.setBackground(c1);
JPanel jp = new JPanel();
if(!labelText.isEmpty()){
jp.setLayout(new BoxLayout(jp, BoxLayout.LINE_AXIS));
JLabel label = new JLabel(labelText);
label.setFont(new Font(font.getFontName(), Font.BOLD, font.getSize()));
label.setBackground(c1);
label.setAlignmentY(Component.TOP_ALIGNMENT);
jp.add(label);
}
jp.add(c);
jp.setBackground(c1);
return jp;
}
这是我的测试代码:
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTextArea jta = new JTextArea("Sed ut perspiciatis, unde " +
"omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem " +
"aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, " +
"explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia " +
"consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, " +
"qui dolorem ipsum, quia dolor sit amet, consectetur, adipisci[ng] velit, sed quia non numquam [do] " +
"eius modi tempora inci[di]dunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim " +
"ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex " +
"ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, " +
"quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?");
jta.setEditable(false);
jta.setLineWrap(true);
jta.setWrapStyleWord(true);
frame.add(DisplayPanel.createBoldLabelPanel("Test:", jta, new Font(Font.SERIF, Font.PLAIN, 14), Color.GRAY));
frame.setSize(400, 400);
frame.setVisible(true);
}
如果你运行它,我想要的东西应该变得清晰,如果它还没有。谢谢!
答案 0 :(得分:4)
还设置文本区域的对齐属性:
jta.setAlignmentY(Component.TOP_ALIGNMENT);
然后两者将对齐到面板内的顶部。
答案 1 :(得分:1)
或将LayoutManager更改为BorderLaoyut
public static JPanel createBoldLabelPanel(String labelText, Component c, Font font, Color c1) {
c.setFont(new Font(font.getName(), Font.PLAIN, font.getSize()));
c.setBackground(c1);
JPanel jp = new JPanel();
if (!labelText.isEmpty()) {
//jp.setLayout(new BoxLayout(jp, BoxLayout.LINE_AXIS));
jp.setLayout( new BorderLayout());
JLabel label = new JLabel(labelText);
label.setFont(new Font(font.getFontName(), Font.BOLD, font.getSize()));
label.setBackground(c1);
label.setAlignmentY(Component.TOP_ALIGNMENT);
jp.add(label, BorderLayout.NORTH);
}
jp.add(c);
jp.setBackground(c1);
return jp;
}