如何在 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);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP