0

ユーザーが自分の GUI に描きたい形状を選択できるようにしようとしています。円形、正方形、長方形のボタンを選択できます。私の actionListener は、文字列をコンソールに出力するように機能しますが、GUI に形状が表示されません。actionCommandを使用してパネルにその形状を描画するにはどうすればよいですか。

public void paintComponent(Graphics g) {
    g2D = (Graphics2D) g;
    //Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y);
    //g2D.draw(rect);
      repaint();
}

public void actionPerformed(ActionEvent arg0) { 
    if(arg0.getActionCommand().equals("Rect")){     
        System.out.println("hello");
        Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y);
        g2D.draw(rect); //can only be accessed within paintComponent method
        repaint();
    }
4

2 に答える 2

3

最初に長方形をペイントしてから再ペイントを要求すると、長方形は消えます。

新しいシェイプを一時変数に保存し、paintComponent 内でレンダリングする必要があります。

private Rectangle2D temp;

// inside the actionPerformed
    temp = new Rectangle2D.Double(x, y, x2-x, y2-y);
    repaint();

// inside the paintComponent
    if(temp != null) {
        g2D.draw(temp);
    }
于 2013-01-23T00:04:08.077 に答える
2

rectをローカル変数のフィールドntoにします。actionPerformedで、適切なrectを作成し、repaint()を呼び出します。次に、paintComponent()が呼び出されます。こんな感じになります

public void paintComponent(Graphics g) {
    g2D = (Graphics2D) g;
    g2D.draw(rect);
}
于 2013-01-23T06:54:25.790 に答える