如何在 Java 中將標籤的內容設定為右對齊和頂部對齊?
要將標籤元件的文字設定為右對齊和頂部對齊,你需要設定對齊方式。將標籤設定為在右側且頂部對齊,如下所示 -
JLabel label = new JLabel("Fav Sports", JLabel.RIGHT); label.setVerticalAlignment(JLabel.TOP);
在這裡,我們已經設定了標籤的大小以及顏色,其中包括前景和背景顏色 -
label.setPreferredSize(new Dimension(220, 70)); label.setOpaque(true); label.setBackground(Color.YELLOW); label.setForeground(Color.RED);
以下是一個示例,用於將標籤的內容設定為右對齊和頂部對齊 -
package my; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Frame"); frame.setLayout(new FlowLayout()); JLabel label = new JLabel("Fav Sports", JLabel.RIGHT); label.setPreferredSize(new Dimension(220, 70)); label.setOpaque(true); label.setVerticalAlignment(JLabel.TOP); label.setBackground(Color.YELLOW); label.setForeground(Color.RED); Font font = new Font("Serif", Font.BOLD, 18); label.setFont(font); JTextArea text = new JTextArea(); text.setText("Football"); font = new Font("Serif", Font.BOLD, 14); text.setFont(font); frame.add(label); frame.add(text); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setVisible(true); } }
輸出
廣告