【问题标题】:Repaint a circle重新画一个圆圈
【发布时间】:2016-10-08 23:41:41
【问题描述】:

我想在按下按钮时重新绘制一个圆圈。

目前,每当我按下按钮时,它都会将我按下的按钮打印到控制台。例如,如果我按下“绘制红色”按钮,我希望它用红色填充圆圈,其他颜色也一样。我正试图围绕整个paint/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);

}

}

【问题讨论】:

    标签: java swing paint paintcomponent


    【解决方案1】:

    考虑对您的代码进行这些更改:

    • 正如 here 所讨论的,Swing 程序应该覆盖 paintComponent() 而不是覆盖 paint()

    • 为您的面板指定currentColor 的属性。

      private Color currentColor;
      
    • 让每个按钮的ActionListener设置currentColor并调用repaint()

      currentColor = color;
      repaint();
      
    • 使用Action 封装程序的功能。

    检查了一个完整的例子here

    【讨论】:

      【解决方案2】:

      您不会在代码中的任何地方触发“重绘”。这应该工作:

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

      【讨论】:

      • 你不应该validate()整个Container;应该可以repaint() 只是面板,如here 所述。
      猜你喜欢
      • 2012-11-12
      • 2021-06-24
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      相关资源
      最近更新 更多