I'm trying to do something where the user gets a prompt where they can pick a colour from the JColorChooser and once they've done that, a rectangle pops up in the same JFrame and it has the same colour as what the user picked
Code so far:
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class TestProjectDialog {
static String name;
public String getName(){
return name;
}
TestProjectJPanel jpp = new TestProjectJPanel();
public static void main(String[] args){
JOptionPane.showMessageDialog(null, "Just about to draw a REALLY GOOD 2D car \n just need input please.");
name= JOptionPane.showInputDialog("Imagine a car, what is it's name?");
if(name == null || (name != null && ("".equals(name))))
{
JOptionPane.showMessageDialog(null, "Invalid input/pressed cancel, closing program.");
System.exit(0);
}
JOptionPane.showMessageDialog(null, "Ah okay, so it's name is " + name);
JFrame f = new JFrame(name);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestProjectJPanel jpp = new TestProjectJPanel();
jpp.setBackground(Color.WHITE);
f.setSize(1440,900);
f.add(jpp.panel, BorderLayout.CENTER);
f.add(jpp.b, BorderLayout.SOUTH);
f.setVisible(true);
}
}
And for the class which has the button, listener and where I want the Rectangle to appear
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestProjectJPanel extends JFrame {
public JButton b;
public Color color = (Color.WHITE);
public JPanel panel;
public Color bodyColour;
public Color doorColour;
public Color wheelColour;
public void paintComponent(Graphics g){ // Surely this shouldn't be void as it's returning a Rectangle?
super.paintComponents(g);
Rectangle r = new Rectangle(430,50,250,400);
g.fillRect((int)r.getX(),(int)r.getY(),(int)r.getHeight(),(int)r.getWidth());
g.setColor(bodyColour);
}
public TestProjectJPanel(){
panel = new JPanel();
panel.setBackground(color);
// bodyColour button
b = new JButton("Choose a colour for the body of the car");
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
bodyColour = JColorChooser.showDialog(null, "Pick the colour", bodyColour);
if(bodyColour==null)
bodyColour = (Color.BLACK);
// TRYING TO DRAW THE RECTANGLE HERE ONCE THE USER PICKED THEIR COLOUR.
}
}
);
}
}
See Performing Custom Painting.
As a hint, don't override paint
of top level containers like JFrame
, create a custom JPanel
and override it's paintComponent
method and perform your custom painting there (don't forget to call super.paintComponent
).
Provide methods to that allow you to change the color of the rectangle and call repaint
to request that the panel should be updated.