尝试使用 MouseEvent 更改 JLabel

Trying to change JLabel using MouseEvent

我的任务是通过单击标签来更改 jlabel,但我们还没有进入鼠标适配器和鼠标处理,我们只是覆盖了 5 个鼠标事件,所以我们可以使用这些。这是我目前所做的,但它所做的只是更改我名字的字体,我希望它在我单击我的名字时也将 JLabel 的颜色更改为红色。

class FontFrame extends JFrame implements ActionListener{
JButton FirstFont;
JButton SecondFont;
JLabel myName;

public FontFrame(){
setSize(600, 200);
setLocation(300, 200);
Container contentpane = getContentPane();
myName = new JLabel("Aly");
FirstFont = new JButton("Chalkboard 14");
SecondFont = new JButton("Harrington 18");
JPanel panel = new JPanel();
panel.add(FirstFont);
panel.add(SecondFont);
panel.add(myName);
FirstFont.addActionListener(this);
SecondFont.addActionListener(this);
contentpane.add(panel, "Center");
}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
Font f1 = new Font("Chalkboard", Font.PLAIN, 14);
Font f2 = new Font("Harrington", Font.PLAIN, 18);
if(source == FirstFont){
    myName.setFont(f1);
}
else if(source == SecondFont){
        myName.setFont(f2);
    }
}
}

class mouseFrame extends FontFrame implements MouseListener{

public mouseFrame(){
    addMouseListener(this);
    myName.addMouseListener(this);
    FirstFont.addMouseListener(this);
    SecondFont.addMouseListener(this);
    add(myName);
    add(FirstFont);
    add(SecondFont);
    Container contentpane = getContentPane();
    contentpane.add(new FontFrame());
}

public void mouseClicked(MouseEvent e) {
    int fontbutton = e.getButton();
    if(fontbutton == MouseEvent.BUTTON1 ){
        myName.setForeground(Color.red);
    }
}

public void mouseEntered(MouseEvent e) {
    }

public void mouseExited(MouseEvent e) {
    }

public void mousePressed(MouseEvent e) {

}
public void mouseReleased(MouseEvent e) {
    }
}

public class ChangeFont {
    public static void main(String[] args){
        JFrame frame = new FontFrame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
  1. 您实际上从未创建或显示 MouseFrame
  2. 的实例
  3. MouseFrame 不调用 FontFrame 的构造函数 (super()),而是尝试向其添加 FontFrame 的新实例,即非法操作

首先更改 MouseFrame 以便它调用 super 构造函数并且仅将 MouseListener 添加到 JLabel

public static class MouseFrame extends FontFrame implements MouseListener {

    public MouseFrame() {
        super();
        myName.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e) {
        System.out.println("...");
        int fontbutton = e.getButton();
        if (fontbutton == MouseEvent.BUTTON1) {
            myName.setForeground(Color.red);
        }
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {
    }

}

接下来,在main方法中,创建MouseFrame...

的实例
public static void main(String[] args) {
    JFrame frame = new MouseFrame();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}