如何在油漆处更改颜色(图表)

时间:2013-04-18 13:49:35

标签: java swing graphics 2d paint

我在JPanel中有一个paint的代码,但我不知道如何更改方法paint()之外的颜色

我给出了代码:

public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.RED);
        for (Shape linea : lineas) { // dibuja todos las elipses
            g2.draw(linea);
        }
    }

我只知道使用g2.setColor(Color.RED);更改该方法的颜色,但我想在MenuItem的actionListener中更改它。

1 个答案:

答案 0 :(得分:3)

只需在您的班级中添加Color变量,然后使用该变量设置Graphics上的颜色。覆盖paintComponent而不是paint也更合适,并且始终建议调用super - 方法。

请参阅此示例,该示例随机设置面板的颜色。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestColoredPanel {

    private static class ColoredPanel extends JPanel {

        private Color color = Color.RED;

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(getColor());
            g.fillRect(0, 0, getWidth(), getHeight());
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
            repaint();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }

    }

    protected void initUI() {
        final JFrame frame = new JFrame(TestColoredPanel.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final ColoredPanel panel = new ColoredPanel();
        frame.add(panel);
        JButton button = new JButton("Click me");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Random r = new Random();
                panel.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            }
        });
        frame.add(button, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestColoredPanel().initUI();
            }
        });
    }
}