简体   繁体   中英

How to change colors at paint(Graph)

I have a code for paint in a JPanel, but i dont know how to change colors outside the method paint()

I give the code:

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

I only know to change the color at that method using g2.setColor(Color.RED); but I want to change it in an actionListener of a MenuItem.

Simply add a Color variable in your class and use that variable to set the color on your Graphics . It is also more appropriate to override paintComponent rather than paint and calling the super -method is always recommended.

See this example that randomly sets the color of the panel.

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();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM