如何在 Java 中创建带有图像图标的 JLabel?
java 8object oriented programmingprogramming更新于 2025/4/26 16:52:17
让我们创建一个带有图像图标的标签 −
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); } }