I am to change color of an Icon, with 3 different buttons.
So far I have this, but the ColorIcon will not compile.
Compiler says: cannot resolve class ColorIcon.
This is a working example of what you need, with comment about bad things and corrections made.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
class ColorIcon implements Icon {
private int width;
private Color color;
private ChangeColor c; // Class ChangeColor is not defined
public ColorIcon(int aWidth, ChangeColor c) { // Class ChangeColor is not defined
this.c = c; //So c has no type
width = aWidth;
color = Color.RED;
}
public int getIconWidth() {
return width;
}
public int getIconHeight() {
return width / 2;
}
public void setColor(Color c) { //This method is not used ?
color = c;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
color = this.c.color; //Field color is not defined in Class Component
//prefix c by this.c to reference a ChangeColor object
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double ellipse = new Ellipse2D.Double(x,y, width, width);
g2.setColor( color );
g2.fill( ellipse );
}
}
public class ChangeColor {//Rename TestColorIcon to ChangeColor
public java.awt.Color color = java.awt.Color.RED;
public Component createComponents() {
JButton buttonRed = new JButton("R?d"); //The e char in Red is not regular
JButton buttonBlue = new JButton("Bl?"); //The e char in Blue is not regular
JButton buttonGreen = new JButton("Gr?n"); //The e char in Green is not regular
final ColorIcon icon = new ColorIcon( 20, this); // This constructor does not exists, add ,this
final JLabel label = new JLabel( icon );
JPanel panel = new JPanel();
panel.setLayout( new GridLayout(0, 3) );
panel.add( buttonRed );
panel.add( buttonBlue );
panel.add( buttonGreen );
panel.add( label );
buttonRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
color = Color.RED;
label.repaint();
}
});
buttonBlue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
color = Color.BLUE;
label.repaint();
}
});
buttonGreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
color = Color.GREEN;
label.repaint();
}
});
return panel;
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
}
catch (Exception e) {
}
JFrame frame = new JFrame("Change Color");
ChangeColor changeColor = new ChangeColor(); //Class ChangeColor is not defined
Component content = changeColor.createComponents();//So changeColor has no type, so does not have a createComponents method
frame.getContentPane().add( content );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.show();//show is deprecated use setVisible(true) instead
}
}