我正在開發用於處理圖像的GUI,並且我無法顯示圖像。更新JPanel並保持JLabels可見
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BottomLeftPanel extends JPanel {
public static BottomLeftPanel BLP;
public static BufferedImage original;
public static ImageIcon icon;
public static Polygon poly;
public static JLabel label;
public BottomLeftPanel() throws IOException {
super();
this.setBackground(new Color(255, 255, 255, 0));
original = Methods2.loadImage("bowser jr.png");
original = Methods2.toFourChannel(original);
poly = null;
icon = new ImageIcon(original);
label = new JLabel(icon);
this.add(new JLabel(icon));
this.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
}
@Override
public void mousePressed(MouseEvent me) {
Point2D P = me.getPoint();
if(poly == null) {
poly = new Polygon(new int[]{(int) P.getX()}, new int[]{(int) P.getY()}, 1);
return;
}
int[] B = poly.xpoints;
int[] C = poly.ypoints;
int[] X = new int[poly.npoints + 1];
int[] Y = new int[poly.npoints + 1];
System.arraycopy(B, 0, X, 0, B.length);
System.arraycopy(C, 0, Y, 0, C.length);
X[B.length] = (int) P.getX();
Y[C.length] = (int) P.getY();
poly = new Polygon(X, Y, poly.npoints + 1);
System.out.println(poly.toString());
BLP.getGraphics().clearRect(0, 0, BLP.getHeight(), BLP.getWidth());
BLP.repaint(BLP.getGraphics());
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
});
BLP = this;
}
public void repaint(Graphics g) {
g.setColor(Color.black);
g.drawPolygon(poly);
icon = new ImageIcon(original);
label.setIcon(icon);
}
}
在mousePressed方法中,更新多邊形多邊形,並顯示更新後的版本。但是,點擊幾下後,作爲加載到屏幕上的JLabel的一部分的ImageIcon將不再可見。我如何解決這個問題,同時保持clearRect方法(我需要clearRect方法來刪除已經繪製的多邊形並繪製新的多邊形)?
永遠不要使用'getGraphics()',這不是如何在Swing中完成繪畫。請參閱[執行自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting/)瞭解如何完成自定義繪畫。不要依賴'static'來提供跨類邊界的變量訪問,這只是設計不好的一個標誌。如果您需要訪問另一個類中的對象,請直接將它的引用傳遞給該類。 – MadProgrammer