1

Im trying to make an application that will change the state of a traffic light in the click of a button. My code: Main

import javax.swing.*;

public class PP416 
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Traffic light");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new TrafficPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

JPanel Class:

import javax.swing.*;
import java.awt.*;
import java.awt.Event;

public class TrafficPanel extends JPanel 
{
    private JButton button;
    private int indicator = 0; // Light is off

    public TrafficPanel()
    {
        button = new JButton("Change");

        this.add(button);
    }

    public void paint(Graphics g)
    {
        if (indicator == 0)
        {
            g.drawOval(30, 40, 30, 30);
            g.drawOval(30, 70, 30, 30);
            g.drawOval(30, 100, 30, 30);
        }
    }

}

the button just not appearing , just the ovalls. anyone can help me with this?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
God
  • 1,238
  • 2
  • 18
  • 45

1 Answers1

2

Don't override paint but rather paintComponent and Most important, call the super's method. Your lack of a super call may be preventing your JPanel from drawing its child components well.

e.g.,

@Override
protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   if (indicator == 0) {
       g.drawOval(30, 40, 30, 30);
       g.drawOval(30, 70, 30, 30);
       g.drawOval(30, 100, 30, 30);
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thnaks.just Overriden the paintComponent and its working. One more question: Am i doing it the right way? with the idicator switching states from 0 to 4 each click? cause its a lot of code and it seems clumsy. – God Mar 13 '15 at 17:35
  • @God: the cause of your problem though was that you didn't call the super paint method. But you're better off with paintComponent regardless, as long as you also call the super method. – Hovercraft Full Of Eels Mar 13 '15 at 17:36
  • @God: Your idea is to use a field to represent the *state* of the light and change what is drawn within paintComponent based on this state, and this is a good idea. Using an int could work, so could using an enum to represent the *state* of the light. The devil of course is in the details. – Hovercraft Full Of Eels Mar 13 '15 at 17:37