我正在尝试使用自定义图标(在地图上显示为城市)创建程序,其中图标在鼠标悬停时显示标签(在本例中为城市1,城市2等)。它适用于城市2,3和4;然而,城市1有一些意想不到的行为。当第一次悬停时,标签会显示在图标上,但如果鼠标退出并重新进入城市,则标签会显示在城市图标的后面。如果鼠标首先进入任何其他城市,则城市1的标签默认为图标后面。看到所有四个城市都是同一个班级的实例,我对于为什么会发生这种情况感到非常困惑。
希望一切都有道理。这是主窗口的代码:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
@SuppressWarnings("serial")
public class MainWindow extends JFrame{
static JLabel hoverText = new JLabel("", JLabel.CENTER);
static JLayeredPane panel = new JLayeredPane();
public MainWindow(){
ImageIcon cityImg = new ImageIcon("Resources/mock_city.png");
CustomButton city1, city2, city3, city4;
city1 = new CustomButton(cityImg, "City 1");
city2 = new CustomButton(cityImg, "City 2");
city3 = new CustomButton(cityImg, "City 3");
city4 = new CustomButton(cityImg, "City 4");
Dimension cityDims = new Dimension(cityImg.getIconWidth(),cityImg.getIconHeight());
city1.setSize(cityDims);
city1.setLocation(50,50);
city2.setSize(cityDims);
city2.setLocation(50,150);
city3.setSize(cityDims);
city3.setLocation(150,50);
city4.setSize(cityDims);
city4.setLocation(150,150);
panel.add(city1, new Integer(2));
panel.add(city2, new Integer(2));
panel.add(city3, new Integer(2));
panel.add(city4, new Integer(2));
add(panel);
setSize(300,300);
setVisible(true);
}
public static void setHoverText(String label, Point p) {
hoverText.setText(label);
hoverText.setForeground(Color.RED);
hoverText.setSize(77,13);
hoverText.setLocation(p);
panel.add(hoverText, new Integer(3));
}
public static void delHoverText() {
hoverText.setText("");
panel.add(hoverText, new Integer(3));
}
public static void main (String[] args) throws IOException {
new MainWindow();
}
}
以下是图标的代码:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
@SuppressWarnings("serial")
public class CustomButton extends JComponent implements MouseListener{
ImageIcon buttonImg;
String label;
public CustomButton(ImageIcon buttonImg, String label){
super();
addMouseListener(this);
this.buttonImg = buttonImg;
this.label = label;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(buttonImg.getImage(), 0, 0, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
MainWindow.setHoverText(label, getLocation());
}
@Override
public void mouseExited(MouseEvent arg0) {
MainWindow.delHoverText();
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}