java drawImage无法从事件中运行

eas*_*ipt 1 java swing awt jlabel java-2d

我有一个扩展jlabel并使用paintComponent绘制它的类,如下所示:paintPhotos.java

package myApp;
import java.awt.*;
import javax.swing.*;
/**
*
* @author PAGOLINA
*/
public class paintPhotos extends javax.swing.JLabel {

    public Image img; int w; int h;
public paintPhotos(Image img, int w, int h) {
    this.img = img; this.w = w; this.h = h;
    System.out.println("am paintclass");
 }
@Override
public void paintComponent(Graphics p) {
    System.out.println("am here");
    super.paintComponent(p);
    Graphics2D g2 = (Graphics2D) p;
    p.drawImage(img, 0, 0, w, h, this);
}

}
Run Code Online (Sandbox Code Playgroud)

当我尝试从另一个类的构造函数中绘制时(AddScore.java).

public AddScore() {
    initComponents();
    setLocationRelativeTo(null);
    removeNotify();
    setUndecorated(true);
    Image imag = new  ImageIcon(this.getClass().getResource("img/top_bg.jpg")).getImage();
    showPix1.setLayout(new BorderLayout());
    showPix1.add(new paintPhotos(imag,40,40), BorderLayout.CENTER);
}
Run Code Online (Sandbox Code Playgroud)

以上工作正常,并按指定绘制图像.

但是当我尝试从这样的另一个类(AddScore.java)的actionperform事件中绘制图像时.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    Image imag = new ImageIcon(this.getClass().getResource("img/top_bg.jpg")).getImage();
            showPix1.setLayout(new BorderLayout());
            showPix1.add(new paintPhotos(imag,20,20), BorderLayout.CENTER);
}
Run Code Online (Sandbox Code Playgroud)

由于paintcomponent不起作用,上面的语句不起作用,我做错了什么?

Can someone pls help me on this cos i have try all posible method to call my paintPhotos class yet is not working, what is wrong with this code?

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Image imag = new ImageIcon(this.getClass().getResource("img/top_bg.jpg")).getImage();
        showPix1.setLayout(new BorderLayout());
        showPix1.add(new paintPhotos(imag,20,20), BorderLayout.CENTER);
}
Run Code Online (Sandbox Code Playgroud)

mKo*_*bel 5

  1. Image作为图标/ ImageIcon的的JLabel

  2. 在这种情况下,不要在飞行中加载图像,加载为局部变量

  3. for Icon/ ImageIconin JLabel使用正确LayoutManager

  4. 常见问题是Icon/ ImageIcon不返回任何异常,必须进行测试null value

  5. SSCCE发布后尽快提供更好的帮助