首页 > 解决方案 > 初学者 Graphics2D Java:重绘()

问题描述

我当时正试图在动作处理程序中更改我的红色圆圈的颜色,但repaint()我无法弄清楚它为什么不起作用。

在这里进口

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

我的课在这里:

public class CirclePanel extends JPanel implements ActionListener  {
    static JFrame f;
    static JButton run1, run2, reset, quit;
    static JPanel btnPanel;
    static CirclePanel circlePanel;
    static final int NUM = 5;
    static Color c;
    static Graphics2D g2;
    static Graphics2D g3; 

    public CirclePanel(){

        f = new JFrame();

        f.setTitle("Dining Philosophers");
        f.setDefaultCloseOperation(EXIT_ON_CLOSE);
        f.setSize(1000,1000);
        f.setLayout(new BorderLayout());

        btnPanel = new JPanel();
        btnPanel.setPreferredSize(new Dimension(250, 100));
        btnPanel.add(run1 = new JButton("Run 1"));
        btnPanel.add(run2 = new JButton("Run 2"));
        btnPanel.add(reset = new JButton("Reset"));
        btnPanel.add(quit = new JButton("Quit"));

        run1.setPreferredSize(new Dimension(180, 50));
        run2.setPreferredSize(new Dimension(180, 50));
        reset.setPreferredSize(new Dimension(180, 50));
        quit.setPreferredSize(new Dimension(180, 50));

        run1.addActionListener(this);


        f.add(btnPanel, BorderLayout.SOUTH);

        f.add(this, BorderLayout.CENTER);

        f.setVisible(true);
    }


    @Override
    public void paintComponent(Graphics g){

        super.paintComponent(g);
        g2 = (Graphics2D) g;
        g3 = (Graphics2D) g;
        g2.translate(470, 400);

        c = Color.red;

        for(int i = 0; i <  NUM; ++i){
            c = Color.red;

            g2.setColor( c);

            g2.fillOval(150, 0, 100, 100);

            g3.setColor(Color.BLACK);
            g3.fillOval(90, 0, 30, 30);

            g2.rotate(2*Math.PI/ NUM);
        }
    }

正如您所看到的,当我按下 Run1 按钮时,它确实进入了动作处理程序并执行了重绘方法,但没有任何变化。

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == run1) {
            System.out.println("Entered Action Handler");

            g2.setColor(Color.green);

            repaint();

        }
    }

这是我的主要内容:

    public  static void main(String[] args) {

         new CirclePanel();
    }

}

标签: javaswinggraphics2d

解决方案


Graphics 对象的寿命不长,也不稳定,您不应该以这种方式使用它们。不要设置 g2 或任何其他 Graphics field,而是创建一个 Color 字段,比如称为Color circleColor = ...;,然后更改this。在protected void paintComponent(Graphics g)方法中, call g.setColor(circleColor);,这应该工作。

删除这些字段,因为它们很危险:

// static Graphics2D g2;
// static Graphics2D g3; 

此外,您的代码显示了对 static 修饰符的过度使用,我冒昧地建议您的任何字段都不应是静态的,除了常量:

static final int NUM

推荐阅读