이미지 처리를위한 GUI를 개발 중이며 이미지 표시에 문제가 있습니다.JPanels 업데이트 및 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에서 polygon poly가 업데이트되고 업데이트 된 버전이 표시됩니다. 그러나 몇 번의 클릭 후 화면에로드 된 JLabel의 일부인 ImageIcon은 더 이상 볼 수 없습니다. clearRect 메서드를 제 위치에 유지하면서 어떻게 수정합니까? (이미 그린 다각형을 제거하고 새 다각형을 그리려면 clearRect 메서드가 필요합니다)?
결코 getGraphics()를 사용하십시오. Swing에서 페인팅이 수행되는 방식이 아닙니다. 사용자 정의 페인팅을 수행하는 방법은 [사용자 정의 페인팅 수행] (http://docs.oracle.com/javase/tutorial/uiswing/painting/)을 참조하십시오. 클래스 경계를 넘나 드는 변수에 접근하기 위해'static '에 의존하지 마십시오. 이것은 잘못된 디자인의 표시 일뿐입니다. 다른 클래스의 객체에 액세스해야하는 경우 해당 클래스에 대한 참조를 직접 클래스에 전달하십시오. – MadProgrammer