多次调用绘制组件方法,同时最大化窗口

时间:2015-07-25 17:05:34

标签: java swing user-interface graphics paintcomponent

所以我创建了一个GUI,用户点击一个JButton来改变圆圈的颜色......我使用了paintComponent方法,我知道在显示GUI时以及GUI窗口是最小化然后重新打开。

然而,当我在mac上最大化我的窗口时,paintComponent方法被多次调用,并且圆圈循环通过许多不同的颜色,为什么会出现这种情况,因为为什么paintComponent方法被多次调用。

源代码:

GUI类

   import javax.swing.*;
   import java.awt.event.*;
   import java.awt.*;

public class Gui extends JFrame {

JPanel row1 = new JPanel();
JPanel drawingSpace = new MyDrawPanel();
JButton colourChange = new JButton("Click here to change colors");

public Gui(){
    setTitle("Circle Colors");
    setSize(400,650);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BorderLayout layoutMaster = new BorderLayout();
    colourChange.addActionListener(new EventHandler(this));
    setLayout(layoutMaster);


    setLayout(layoutMaster);
    row1.add(colourChange);
    add(drawingSpace, BorderLayout.CENTER);
    add(row1, BorderLayout.SOUTH);

    setVisible(true);
}

public static void main(String[] args){
    Gui createPage = new Gui();
}

}

事件处理班

import java.awt.event.*;
import java.awt.*;

public class EventHandler implements ActionListener {

Gui refRemote;

public EventHandler(Gui obj){
    refRemote = obj;
}

public void actionPerformed(ActionEvent e1){
    String buttonTitle = e1.getActionCommand();

    if(buttonTitle.equals("Click here to change colors"))
    {
        refRemote.repaint();
    }
}

}

绘图面板类

 import javax.swing.*;
 import java.awt.*;

  public class MyDrawPanel extends JPanel {

   public void paintComponent(Graphics g1){

    Graphics2D g2D = (Graphics2D) g1;

    int red = (int) (Math.random()*256);
    int green = (int) (Math.random()*256);
    int blue = (int) (Math.random()*256);

    Color initialColor = new Color(red, green, blue);

    red = (int) (Math.random()*256);
    green = (int) (Math.random()*256);
    blue = (int) (Math.random()*256);

    Color finalColor = new Color(red, green, blue);

    ///GradientPaint gradient = new GradientPaint(50, 50, initialColor, 100, 100, finalColor);

    g2D.setPaint(initialColor);
    g2D.fillOval(100, 150, 200, 200);

}

}

1 个答案:

答案 0 :(得分:2)

使用特定的方法更改将从ActionListener调用的颜色,而不是更改重绘的颜色。当paintComponent被调用时,它应该只使用当前颜色。