2016-10-08 7 views
0

ボタンを押すたびにサークルを再描画したい。円を描く

現在、ボタンを押すたびに、押したボタンをコンソールに表示します。たとえば、「ペイントレッド」ボタンを押すと、赤で円を塗りつぶし、他の色でも塗りつぶします。私は全体のペイント/ paintComponentの違いの周りに私の頭をラップしようとしています。あなたはあなたのコード内の任意の場所に "再描画" 誘発しない

public class testCircle extends JPanel { 

public void paint(Graphics g) 
{ 
    setSize(500,500); 

    int R = (int) (Math.random()*256); 
    int G = (int)(Math.random()*256); 
    int B= (int)(Math.random()*256); 
    Color randomColor = new Color(R, G, B); 
    g.setColor(randomColor); 
    g.drawOval(75, 100, 200,200); 
    g.fillOval(75, 100, 200, 200); 
} 

public static void main(String[] args) 
{ 

    JFrame frame = new JFrame(); 
    frame.setSize(400, 400); 
    testCircle circlePanel = new testCircle(); 
    frame.add(circlePanel); 



    JButton redButton = new JButton("Paint Red"); 
    redButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) 
     { 
      System.out.println("Red Button Pressed!"); 
     } 
    }); 
    JButton blueButton = new JButton("Paint Blue"); 
    blueButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) 
     { 
      System.out.println("Blue Button Pressed!"); 
     } 
    }); 

    JButton greenButton = new JButton("Paint Green"); 
    greenButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) 
     { 
      System.out.println("Green Button Pressed!"); 
     } 
    }); 

    redButton.setPreferredSize(new Dimension(100,100)); 
    blueButton.setPreferredSize(new Dimension(100,100)); 
    greenButton.setPreferredSize(new Dimension(100,100)); 

    frame.setLayout(new FlowLayout()); 
    frame.add(redButton); 
    frame.add(blueButton); 
    frame.add(greenButton); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

} 

}

答えて

0

これは私がこれまで持っているものである

...。それは動作するはずです:

redButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       System.out.println("Red Button Pressed!"); 
       frame.invalidate(); 
       frame.validate(); 
      } 
     }); 
+1

「コンテナ」全体を 'validate()'する必要はありません。ここで概説されているように、パネルだけを 'repaint()'することができるはずです(http://stackoverflow.com/a/39941735/230513)。 – trashgod

3

があなたのコードにこれらの変更を考えてみましょう:

  • としては、Swingプログラムは、代わりにpaint()をオーバーライドするpaintComponent()をオーバーライドする必要があり、here議論しました。

  • パネルにcurrentColorの属性を付けます。

    private Color currentColor; 
    
  • 各ボタンのActionListenerセットcurrentColorをしようとrepaint()を呼び出します。あなたのプログラムの機能をカプセル化するための

    currentColor = color; 
    repaint(); 
    
  • 使用Action

完全な例は、hereです。

image