import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
public class moon extends JFrame{
private static final long serialVersionUID = 1L;
private JButton button = new JButton("选择颜色");
public moon(){
super("Moon");
setLocation(300,300);
setSize(300,300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(Color.white);
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JColorChooser.showDialog(null, "选择颜色", Color.black);
}
});
}
public void paint(Graphics g)
{
int x0 = this.getWidth()/2-60;
int y0 = this.getHeight()/2-60;
g.fillOval(x0, y0, 120, 120);
g.setColor(Color.white);
g.fillOval(x0-25, y0-25, 120, 120);
}
public static void main(String[] args) {
new moon();
}

}写到目前的代码如上,已经能显示月亮,但是不知道要怎么改变它的颜色,JColorChooser选中的颜色不知道怎么传到paint里去。

解决方案 »

  1.   

    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JFrame;public class moon extends JFrame {
    private static final long serialVersionUID = 1L;
    private JButton button = new JButton("选择颜色");
    private Color moonColor = Color.WHITE; public moon() {
    super("Moon");
    setLocation(300, 300);
    setSize(300, 300);
    setVisible(true);
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setBackground(Color.white);
    add(button);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
    moonColor = JColorChooser.showDialog(null, "选择颜色", Color.black);
    repaint();
    }
    });
    } public void paint(Graphics g) {
    int x0 = this.getWidth() / 2 - 60;
    int y0 = this.getHeight() / 2 - 60;
    g.setColor(moonColor);
    g.fillOval(x0, y0, 120, 120);
    g.setColor(Color.WHITE);
    g.fillOval(x0 - 25, y0 - 25, 120, 120);
    } public static void main(String[] args) {
    new moon();
    }}用一个Color变量记录你get的颜色
      

  2.   

    你这样写还有个错误  就是  改变大小不会重画的  ,你得把 paintComponent方法重写下