我正在使用一个JLabel数组,其中可以点击多个对象(为简单起见,下面只显示一个)。单击每个时,它应运行一小段代码,根据单击的对象更改开关。之后,它应运行为每个JLabel运行的通用代码,但基于交换机执行略有不同。
问题是以下示例运行" //运行此代码第二个"首先,然后运行" //首先运行此代码"位。有没有办法扭转这种行为?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ListenToMice extends JFrame implements MouseListener
{
private JLabel[] difference = new JLabel[11];
public ListenToMice( )
{
difference[1].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
//run this code first
}
});
}
public void mouseClicked(MouseEvent e) {
//run this code second
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
答案 0 :(得分:0)
解决方案是首先将您想要的事件设置为“mousePressed”,将第二个事件设置为“mouseReleased”。这样,当用户按下时调用第一个事件,当用户释放按钮时调用第二个事件。不确定天气是否可以使用较长的代码使计算机需要处理一段时间,但对于这个简短的代码,它可以正常工作。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ListenToMice extends JFrame implements MouseListener
{
private JLabel[] difference = new JLabel[11];
public ListenToMice( )
{
difference[1].addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e) {
//this code will now run first (see how it is "mousePressed" above this text
}
});
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
//put code you want second here
}
}