colorChooser.addItem(new LabeledColor(Color.RED, "Red"));
Here is my LabeledColor class:
import java.awt.*;
public class LabeledColor extends Color {
private static final long serialVersionUID = 1L;
String colorName;
public LabeledColor(Color color, String name) {
super(color);
colorName = name;
}
public String toString() {
return colorName;
}
}
And here is where I'm using it:
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawStarMap extends GraphicsProgram {
//Set up a window with a canvas to click on to add stars and the control bar to choose the size and color of the stars
public void init() {
setBackground(Color.GRAY);
add(new JButton("Clear"), SOUTH);
sizeSlider = new JSlider(MIN_SIZE, MAX_SIZE, INITIAL_SIZE);
add(new JLabel(" Small"), SOUTH);
add(sizeSlider, SOUTH);
add(new JLabel("Large "), SOUTH);
initColorChooser();
add(colorChooser, SOUTH);
addMouseListeners();
addActionListeners();
}
//add the options to choose a color
private void initColorChooser() {
colorChooser = new JComboBox();
colorChooser.addItem(new LabeledColor(Color.WHITE, "White"));
colorChooser.addItem(new LabeledColor(Color.RED, "Red"));
colorChooser.setEditable(false);
colorChooser.setSelectedItem(Color.WHITE);
}
// get the size of the star from the slider
private double getCurrentSize() {
return sizeSlider.getValue();
}
//when the mouse is clicked add a star to the canvas per chosen size and color
public void mouseClicked(MouseEvent e) {
GStar star = new GStar(getCurrentSize());
star.setFilled(true);
star.setColor((Color) colorChooser.getSelectedItem());
add(star, e.getX(), e.getY());
}
//if the clear button is clicked, clear the canvas of any stars
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Clear")) {
removeAll();
}
}
private static final int MIN_SIZE = 1;
private static final int MAX_SIZE = 50;
private static final int INITIAL_SIZE = 16;
private JSlider sizeSlider;
private JComboBox colorChooser;
}
The problem I'm having is in passing the color to the LabeledColor constructor. According to the assignment I'm supposed to pass a color field. If I try to pass Color.WHITE (or any color), I get the error "The constructor Color(Color) is undefined." If I change the LabeledColor constructor to expecting an int like the parent constructor then I get the error, "The constructor LabeledColor(Color, String) is undefined." I can't win. How do I make both happy?
Thanks,
Mickey

New Topic/Question
Reply



MultiQuote




|