klarz
klarz

Reputation: 33

GUI - Constructor for ActionListener, how to make them work?

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

public class Background {
  JFrame frame = new JFrame();
  JMenuBar menubar;
  JTextArea field;
  JMenuItem black, white;

  Background(){

    frame.setLayout(new GridLayout(1,2));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(new Dimension(600,200));

    JPanel jp1 = new JPanel();
    jp1.setBackground(Color.BLACK);

    field = new JTextArea();
    field.setLayout(new BoxLayout(field, BoxLayout.Y_AXIS));
    for(String m : message){
        field.add(new JLabel(m));
    }

    menubar = new JMenuBar();
    frame.setJMenuBar(menubar);
    JMenu changecolor = new JMenu("change color");
    menubar.add(changecolor);
    black = new JMenuItem("black");
    white = new JMenuItem("black");

    black.addActionListener(new FarbListener(frame, Color.WHITE));


    changecolor.add(black);
    changecolor.add(white);

    frame.add(field);
    frame.add(jp1);
    frame.setVisible(true);
   }

   class FarbListener implements ActionListener{
      private final JFrame frameToWorkOn;
      private final Color colorToSet;

      FarbListener(JFrame frameToWorkOn, Color colorToSet){
        this.frameToWorkOn = frameToWorkOn;
        this.colorToSet = colorToSet;
     }

     public void actionPerformed(ActionEvent e) {
       frameToWorkOn.setBackground(colorToSet);
     }
  }

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

}

I need to creat a GUI and add an ActionListener to the JMenuItems.

The GUI works just fine, but I have trouble making the ActionListener work properly.

The code is given I cannot change it (it needs to implement ActionListener and I need to write a constructor).

When I press the MenuItem "black" it doenst change to background color.

Upvotes: 0

Views: 78

Answers (1)

GhostCat
GhostCat

Reputation: 140457

For your specific problem; I would say: just pass the things into your Listener, like this:

class FarbListener implements ActionListener{
  private final JFrame frameToWorkOn;
  private final Color colorToSet;

  FarbListener(JFrame frameToWorkOn, Color colorToSet){
    this.frameToWorkOn = frameToWorkOn;
    this.colorToSet = colorToSet;
 }

 public void actionPerformed(ActionEvent e) {
   frameToWorkOn.setBackground(colorToSet);
 }

}

You might make things overall easier by turning your local variables into fields of the Background class, like:

public class Background {
  private final JFrame frame = new JFrame();

  public Background() {
    frame.setVisible();

and so on ... and now; you don't need to pass around the frame object any more, as your inner class would simply know about it.

Upvotes: 1

Related Questions