GUI - ActionListener的构造函数,如何使它们工作?

时间:2016-09-13 19:24:38

标签: java

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();
  }

}

我需要创建一个GUI并将一个ActionListener添加到JMenuItems。

GUI工作正常,但我无法使ActionListener正常工作。

代码给出我无法改变它(它需要实现ActionListener,我需要编写一个构造函数)。

当我按下菜单项“黑色”时,它会更改为背景颜色。

1 个答案:

答案 0 :(得分:1)

针对您的具体问题;我会说:只需将传递给你的听众,就像这样:

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);
 }

}

通过将本地变量转换为Background类的字段,您可以更轻松地完成工作,例如:

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

  public Background() {
    frame.setVisible();

依此类推...现在;你不再需要绕过框架对象了,因为你的内部课程只会知道它。