如何在 Java 中使用影像圖示建立 JLabel?


讓我們使用影像圖示建立一個標籤 -

JLabel label = new JLabel("SUBJECT ");
label.setIcon(new ImageIcon("E:\
ew.png"));

現在,建立另一個元件 -

JTextArea text = new JTextArea();
text.setText("Add subject here...");

使用 GridBagLayout 對齊這些元件 -

panel.setLayout(new GridBagLayout());

以下是一個使用影像圖示居中顯示標籤的示例 -

示例

package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("SUBJECT ");
      label.setIcon(new ImageIcon("E:\
ew.png"));       JTextArea text = new JTextArea();       text.setText("Add subject here...");       panel.setLayout(new GridBagLayout());       panel.add(label);       panel.add(text);       panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));       frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);       frame.add(panel);       frame.setSize(500, 300);       frame.setVisible(true);    } }

輸出

更新於: 2019 年 7 月 30 日

5K+ 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.