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“黑色”时,它会改变为背景颜色。
你是什么意思“实际听”?它是不是像它应该被称为?你看过“actionPerformed”的参数吗? – ChiefTwoPencils
请阅读有关Java命名约定。类名开始UpperCase。总是。 – GhostCat
是的先生,我标记了空间的问题,我不知道该写什么......如果我在操作中写jp1.setBackground()执行它给了我错误“创建类jp1”....我没有明白,我应该写什么作为构造函数... – klarz