kj5dz
asked on
Java LED Class
I wish to create a Java class for a visual indicator, i.e. LED. The class has a single method to control the LED on/off state.
The LED class swaps images as a function of the ledOn state. When the LED class is instantiated, the image does not appear in the window but the test label does. Below is the test code for the LED class.
When the CLed code is executed within main, i.e. not as a class, the LED image appears as expected. Not sure what I'm doing wrong. Please advise.
Regards,
John
public class CLed
{
public boolean ledOn;
private ImageIcon onLED = new ImageIcon("c:\\eclipseWorkspace\\testZone\\src\\grnLEDOn.jpg");
private ImageIcon offLED = new ImageIcon("c:\\eclipseWorkspace\\testZone\\src\\grnLEDOff.jpg");
private JLabel led;
// constructor
public CLed()
{
led = new JLabel(offLED);
this.ledOn = false;
}
public void setLEDState(boolean x)
{
if(x)
{
this.ledOn = true;
this.led.setIcon(onLED);
}
else
{
this.ledOn = false;
this.led.setIcon(offLED);
}
}
}
The LED class swaps images as a function of the ledOn state. When the LED class is instantiated, the image does not appear in the window but the test label does. Below is the test code for the LED class.
public class test01
{
public static void main(String[] args)
{
// define the main window frame
JFrame f = new JFrame();
f.setSize(500,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("LED Test");
f.setVisible(true);
f.setLocationRelativeTo(null);
f.setResizable(false);
// declare a panel
JPanel p = new JPanel(true);
p.setSize(400,300);
p.setVisible(true);
// declare a test label
JLabel lblName1 = new JLabel();
lblName1.setText("LED1");
lblName1.setVisible(true);
// declare a new led
CLed led1 = new CLed();
led1.ledOn = true;
// add led and label to the panel
p.add(led1);
p.add(lblName1);
// add panel to the frame
f.add(p);
} // end of main()
}
When the CLed code is executed within main, i.e. not as a class, the LED image appears as expected. Not sure what I'm doing wrong. Please advise.
Regards,
John
You'd probably be better off with a JLabel subclass
import javax.swing.*;
public class CLed extends JLabel {
public boolean ledOn;
private ImageIcon onLED = new ImageIcon("on.jpg");
private ImageIcon offLED = new ImageIcon("off.jpg");
// constructor
public CLed() {
setIcon(offLED);
ledOn = false;
}
public void setLEDState(boolean on) {
setIcon(on? onLED : offLED);
ledOn = on;
}
}
try including code to redraw the form when you switch the icon...
I believe it's something like this.Redraw() or something of that sort....
I believe it's something like this.Redraw() or something of that sort....
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you so much!
Try modifying the CLed class to inherit from JLabel like so. Then your main routine will be putting a JLabel into the JPanel
Open in new window