1. 程式人生 > >swing元件JLabel

swing元件JLabel

JLabel 物件可以顯示文字、影象或同時顯示二者。可以通過設定垂直和水平對齊方式,指定標籤顯示區中標籤內容在何處對齊。預設情況下,標籤在其顯示區內垂直居中對齊。預設情況下,只顯示文字的標籤是開始邊對齊;而只顯示影象的標籤則水平居中對齊。 還可以指定文字相對於影象的位置。預設情況下,文字位於影象的結尾邊上,文字和影象都垂直對齊。

構造方法如下:
JLabel() 建立無影象並且其標題為空字串的 JLabel。

JLabel(Icon image) 建立具有指定影象的 JLabel 例項。

JLabel(Icon image, int horizontalAlignment) 建立具有指定影象和水平對齊方式的 JLabel 例項。

JLabel(String text) 建立具有指定文字的 JLabel 例項。

JLabel(String text, Icon icon, int horizontalAlignment) 建立具有指定文字、影象和水平對齊方式的 JLabel 例項。

JLabel(String text, int horizontalAlignment) 建立具有指定文字和水平對齊方式的 JLabel 例項。

在JLabel中增加圖片和文字

import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class MixingIconLabel {
    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame();
        frame.setTitle("JLabel Test");
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ImageIcon imageIcon = new ImageIcon("yourFile.gif");
        JLabel label = new JLabel("Mixed", imageIcon, SwingConstants.RIGHT);
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
    }
}

將JLabel增加到JScrollPane中便於顯示大圖片

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JLabel image = new JLabel(new ImageIcon("A.jpg"));
        frame.getContentPane().add(new JScrollPane(image));
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

JLabel中增加HTML文字

import javax.swing.JFrame;
import javax.swing.JLabel;
public class HTMLLabel {
    public static void main(String[] a) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("<html>bold <br> plain</html>");
        frame.add(label);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}