確かに、これは非常にばかげた標準的な問題のようなものですが、これを検索して修正しようと何時間も費やしましたが、うまくいきません...ここで間違いを見つけることができません...
JComponent に何かを出力する単純なプログラムを作成しようとしています。paintComponent() メソッドはいくつかの変数を参照しており、私がそう言うなら、JComponent のみを再描画したいのです! しかし、変数を変更するたびに常に再描画されます...
私の2つのクラスのコードは次のとおりです。
import java.awt.Dimension;
import javax.swing.*;
public class SimplePaint extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private PaintingCanvas pc;
public SimplePaint() {
super("SimplePaint");
this.pc = new PaintingCanvas();
this.pc.setPreferredSize(new Dimension(800, 600));
this.add(pc);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
SimplePaint sp = new SimplePaint();
sp.pc.setxStart(50);
sp.pc.setyStart(60);
sp.pc.setxEnd(140);
sp.pc.setyEnd(300);
}
}
と
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
public class PaintingCanvas extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private int xStart, yStart;
private int xEnd, yEnd;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(xStart, yStart, xEnd, yEnd);
}
/**
* @param xStart the xStart to set
*/
public void setxStart(int xStart) {
this.xStart = xStart;
}
/**
* @param yStart the yStart to set
*/
public void setyStart(int yStart) {
this.yStart = yStart;
}
/**
* @param xEnd the xEnd to set
*/
public void setxEnd(int xEnd) {
this.xEnd = xEnd;
}
/**
* @param yEnd the yEnd to set
*/
public void setyEnd(int yEnd) {
this.yEnd = yEnd;
}
}
表示されるもの: 長方形のキャンバス (50、60、140、300)...
表示する必要があるもの: 空白のキャンバス。次に sp.pc.repaint() またはそのようなものをメイン メソッドに配置すると、再描画して四角形を表示する必要があります...