-1

i'd like this button to (on click) draw an Oval. Problem is that eclipse says something about missing semicolons (in the action listener definition) and i dont understand why. Whats the proper way of passing methods (bulid in or custom) to the action listeners?

public class figury implements ActionListener {

    public figury() {

        frame();
    }

    public void frame() {

        JFrame f = new JFrame();
        f.setVisible(true);
        f.setSize(480, 480);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel p = new JPanel();
        JButton kolo = new JButton("Rysuj kolo");


        JButton kolo = new JButton("Rysuj kwadrat");
        kwadrat.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                public void paintComponent(Graphics g){
                    g.fillOval(50,50,100,100);
                    g.setColor(Color.RED);
                }
            }
        });

        p.add(kolo);
        f.add(p);
    }

    public static void main(String[] args) {

        new figury();

    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Are you using an IDE like Eclipse? If so, the IDE should highlight which line has the problems. – mdewitt Feb 03 '14 at 20:55

2 Answers2

3

You are trying to define a method inside another method there. In your case, the problem is in the line containing

public void paintComponent(Graphics g) {
...

This cannot be defined inside another method in java. There are good ideas for painting in java in these official documentation links and stackoverflow questions:

How to make canvas with Swing?

http://www.oracle.com/technetwork/java/painting-140037.html

Community
  • 1
  • 1
Jorge_B
  • 9,712
  • 2
  • 17
  • 22
2

If your figury class implements ActionListener, it should implement public void actionPerformed(ActionEvent e) method.

Also you are trying to declare a method paintComponent() inside another actionPerformed() method.

I think your code should look something like this:

public class figury implements ActionListener {

     public figury() {

         frame();
     }

     public void frame() {

         JFrame f = new JFrame();
         f.setVisible(true);
         f.setSize(480, 480);
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         JPanel p = new JPanel();
         JButton kolo = new JButton("Rysuj kolo");


         JButton kwadrat = new JButton("Rysuj kwadrat");
         kwadrat.addActionListener(this);

         p.add(kolo);
         p.add(kwadrat);
         f.add(p);
     }

     @Override
     public void actionPerformed(ActionEvent e) {
         paintComponent(/*pass here a Graphics object*/);
     }

     public void paintComponent(Graphics g) {
         g.fillOval(50,50,100,100);
         g.setColor(Color.RED);
     }

     public static void main(String[] args) {
         new figury();
     }
}