最終的に機能的な描画プログラムを形成する一連のいくつかのクラスを実装しなければならなかったプロジェクトに取り組んでいます。私の問題は、テスト プログラムを実行すると、描画が正しく機能しないことです。基本的な考え方を説明するために、形状のサブクラスを実装しました。MyLine, MyRectangle, MyOval
これらはすべてスーパークラスの下にありますMyShape
。これらのサブクラスはそれぞれdraw
、Graphics パラメーターを引数として取る独自のメソッドを実装します。次に、2 つのクラスを実装して、マウスを使用してこれらの図形を描画できるインターフェイスを設計しました。これら 2 つのクラスおよびは、それぞれDrawPanel
およびDrawFrame
を拡張します。JPanel
JFrame
paintComponent
のオーバーライドされたメソッドDrawPanel
、またはrepaint()
メソッドが呼び出される方法にエラーがあると感じています。プログラムを実行すると、ウィンドウ全体がすべてのメニューなどとともに適切に表示されますが、図形を描画しようとすると、次の 2 つのいずれかが発生します。
- 画面には何も起きていません。
- マウスを非常に速く動かすと、適切な色と形で表示される小さな走り書きが表示される場合があります。
super.paintComponent(g2)
また、コマンドを追加すると、適切な白い背景が得られ、図形が非常にすばやくドラッグされるのを見ることができますが、実際には画面に留まらないことに気付きました。
のコードはDrawPanel
次のとおりです。エラーが発生した場所であると確信しています。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicTabbedPaneUI.MouseHandler;
public class DrawPanel extends JPanel {
private MyShape[] shapes;
private int shapeCount;
private int shapeType;
private MyShape currentShape;
private Color currentColor;
private boolean filledShape;
private JLabel statusLabel;
private Graphics gTest;
DrawPanel(JLabel P){
shapes= new MyShape[100];
shapeCount=0;
statusLabel=P;
currentColor= Color.black;
currentShape=null;
setBackground(Color.white);
shapeType=1;
Mouse handler= new Mouse();
addMouseListener(handler);
addMouseMotionListener(handler);
}
@Override
protected
void paintComponent(Graphics g2){
super.paintComponent(g2);
while(shapeCount>1 && currentShape!=null)
{
currentShape.draw(g2);
shapeCount--;
}
}
//set methods
void setColor(Color c){
currentColor=c;
}
void setFill(boolean f){
filledShape= f;
}
void setShape(int s){
shapeType=s;
}
void clearLastShape(){
if(shapeCount==0)
System.out.print("There are no more shapes to clear");
else
shapeCount--;
repaint();
}
void clearDrawing(){
shapeCount=0;
repaint();
}
class Mouse extends MouseAdapter implements MouseMotionListener{
@Override
public
void mousePressed(MouseEvent e){
if(shapeType==1)
currentShape= new MyLine();
else if(shapeType==2)
currentShape= new MyRectangle();
else
currentShape= new MyOval();
currentShape.setX1(e.getX());
currentShape.setY1(e.getY());
currentShape.setColor(currentColor);
if(shapeType==2 || shapeType==3){
((MyBoundedShape) currentShape).setFill(filledShape);
}
}
@Override public void mouseReleased(MouseEvent e){
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
shapes[shapeCount]=currentShape;
shapeCount++;
currentShape=null;
repaint();
}
@Override
public void mouseMoved(MouseEvent e){
statusLabel.setText("("+e.getX()+","+e.getY()+")");
}
@Override
public void mouseDragged(MouseEvent e){
mouseMoved(e);
currentShape.setX2(e.getX());
currentShape.setY2(e.getY());
repaint();
}
}
}
どんな助けでも大歓迎です。