2016-09-13 48 views
0
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的构造函数,如何让它们工作?

我需要创造一个GUI,并添加一个ActionListener到JMenuItems。

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

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

当我按下MenuItem“黑色”时,它会改变为背景颜色。

+0

你是什么意思“实际听”?它是不是像它应该被称为?你看过“actionPerformed”的参数吗? – ChiefTwoPencils

+0

请阅读有关Java命名约定。类名开始UpperCase。总是。 – GhostCat

+0

是的先生,我标记了空间的问题,我不知道该写什么......如果我在操作中写jp1.setBackground()执行它给了我错误“创建类jp1”....我没有明白,我应该写什么作为构造函数... – klarz

回答

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

}

您可能会使事情总通过转动你的局部变量到领域背景类的容易,像:

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

    public Background() { 
    frame.setVisible(); 

等等......现在;你不需要再传递框架对象,因为你的内部类只是简单地知道它。

+0

它帮助了很多。谢谢我终于明白了! – klarz