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.

1 Answer

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.