This question already has answers here:
MouseListener doesn't appear to be working for me
(3个答案)
3年前关闭。
我的鼠标单击不起作用。我尝试了不同的类型。
这是按钮类和显示类。我的项目中没有错误。但是鼠标不起作用。在这里,我在按钮类中实现了鼠标侦听器接口。然后我创建了一个按钮类对象,然后将ation侦听器添加到该按钮对象。
按钮类别:
显示类别:
(3个答案)
3年前关闭。
我的鼠标单击不起作用。我尝试了不同的类型。
这是按钮类和显示类。我的项目中没有错误。但是鼠标不起作用。在这里,我在按钮类中实现了鼠标侦听器接口。然后我创建了一个按钮类对象,然后将ation侦听器添加到该按钮对象。
按钮类别:
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
public class Button extends JButton implements MouseListener{
private boolean click = false;
public Button(String text) {
super(text);
setFont(new Font(null, Font.BOLD, 30));
setText(text);
}
@Override
public void mouseClicked(MouseEvent arg0) {
click = true;
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
public boolean getClick() {
return click;
}
}
显示类别:
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import com.js.CandyThief.CustomButton.Button;
public class Display{
private String title;
private int width;
private int height;
private JFrame frame;
Button btnPlay = new Button("Play");
Button btnHelp = new Button("Help");
Button btnCredits = new Button("Credits");
public Button btnExit = new Button("Exit");
public Display(String title, int width, int height){
super();
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setFocusable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnPlay.setBounds(300, 285, 450, 50);
btnPlay.setBorderPainted(true);
frame.add(btnPlay);
btnHelp.setBounds(300, 350, 450, 50);
btnHelp.setBorderPainted(true);
frame.add(btnHelp);
btnCredits.setBounds(300, 415, 450, 50);
btnCredits.setBorderPainted(true);
frame.add(btnCredits);
btnExit.setBounds(300, 480, 450, 50);
btnExit.setBorderPainted(true);
frame.add(btnExit);
Background background = new Background();
frame.add(background);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/windowIcon.png")));
btnExit.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (btnExit.getClick()) {
System.exit(0);
}
}
});
}
}
最佳答案
实现MouseListener接口不会使类使用MouseListener。
在这种情况下,您必须将MouseListener添加到Button中:
http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#addMouseListener(java.awt.event.MouseListener)
public Button(String text) {
super(text);
setFont(new Font(null, Font.BOLD, 30));
setText(text);
addMouseListener(this);
}
关于java - JButton在我的Java代码中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40692812/
10-11 02:33