JPanel
以下是使用 NetBeans GUI 编辑器向图像添加图像的两种方法。下面的类ImagePanel
是使用New JPanel Form
命令创建的。
非设计者:第一种方式修改构造函数设置背景图片,类覆盖paintComponent()
绘制图片。编辑器折叠内没有代码更改。
设计器:使用 GUI 设计器,第二种方法添加一个JLabel
命名的imageLabel
. 创建JLabel
居中的代码Icon
位于名为 的属性中Custom Creation Code
,而以下两行位于Post-Creation Code
.
package overflow;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class ImagePanel extends javax.swing.JPanel {
private Image image;
/** Creates new form ImagePanel */
public ImagePanel(Image image) {
this.image = image;
this.setPreferredSize(new Dimension(
image.getWidth(null), image.getHeight(null)));
initComponents();
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
imageLabel = new JLabel(new ImageIcon("image2.jpg"), JLabel.CENTER);
imageLabel.setHorizontalTextPosition(JLabel.CENTER);
imageLabel.setVerticalTextPosition(JLabel.TOP);
setLayout(new java.awt.GridLayout());
imageLabel.setText("imageLabel");
add(imageLabel);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel imageLabel;
// End of variables declaration
}
这是显示面板的合适Main
类和main()
方法:
package overflow;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
f.add(new ImagePanel(ImageIO.read(new File("image1.jpg"))));
} catch (IOException ex) {
ex.printStackTrace();
}
f.pack();
f.setVisible(true);
}
});
}
}
