我正在尝试做一些事情,用户得到一个提示,他们可以从JColorChooser中选择一种颜色,一旦他们这样做,一个矩形弹出同一个JFrame,它的颜色与用户选择
到目前为止代码:
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);
}
}
对于具有按钮,监听器以及我希望Rectangle出现的位置的类
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.
}
}
);
}
}
答案 0 :(得分:3)
作为提示,请勿覆盖paint
等顶级容器JFrame
,创建自定义JPanel
并覆盖其paintComponent
方法并在那里进行自定义绘画(不要忘记致电super.paintComponent
)。
提供允许您更改矩形颜色的方法,并调用repaint
以请求更新面板。