默認JLabel
在其邊界的中間繪製其文本。例如,如果標籤的height
是20,font height
是14,則Y
座標將是(20 - 14)/2 = 3
。就像這樣:JLabel text Y繪製座標
,我應該怎麼做,如果要對齊文本到JLabel
bounds
的TOP
?就像這樣:
UPD:
public class LabelTest extends JFrame {
public LabelTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(Box.createHorizontalStrut(10));
final JLabel label1 = new JLabel("JLabel");
label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
label1.setBorder(BorderFactory.createLineBorder(Color.RED));
label1.setFont(new Font("Arial", Font.PLAIN, 14));
contentPanel.add(label1);
setContentPane(contentPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LabelTest();
}
});
}
}
謝謝,但沒有,它並不能幫助。 – SeniorJD
我寫過* label1.setVerticalAlignment(SwingConstants.TOP)*,但我仍然看到JLabel與附加的第一張圖片相似。 – SeniorJD
然後你需要發佈一個[SSCCE](http://sscce.org)來證明你所做的事情,因爲setVerticalAlignment()方法完全適合我。 –