我正在嘗試爲裝滿文本的幾個JLabel元素創建mouseOver視覺效果。這個想法是當鼠標進入時使每個標籤變暗,然後當鼠標離開它時返回到正常狀態。同樣所有的標籤都放在有背景圖像的面板上。兩個JLabel在鼠標上覆制背景和對象的內容
雖然很簡單,但我遇到了一個我無法克服的令人討厭的行爲。
錯誤1:我第一次將鼠標移動到標籤上時,它顯示了我的主窗口的左上角作爲背景。
問題2:然後,每次將鼠標移動到一個標籤上一次,然後將其移動到第二個標籤上時,第二個將其背景更改爲第一個標籤的「summ背景」(面板圖像+半透明背景) 。在上面看來,即使第一個標籤的文本內容被「複製」到第二個標籤的背景。每次標籤更改時只發生一次:如果將鼠標移到同一標籤上兩次,第二次鼠標懸停事件就會正確繪製。
我已經嘗試使用MouseMotionListener,一個不同的元素(JButton),使用組件修改方法,並試圖重寫繪製方法。沒有結果。
我們已經附上一個GIF動畫顯示所描述的行爲: Two JLabels copying backgrounds and contents from each other
我是比較新的擺動,所以我不熟悉它的注意事項。任何想法可能會導致這種情況?
定義面板類:
public class ImagePanel extends JPanel{
private static final long serialVersionUID = -3995745756635082049L;
private Image image = null;
public ImagePanel(Image image){
this.image = image;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
}
的MouseListener類:
public class MouseHoverPiece implements MouseListener{
private static final Cursor CURSOR_HAND = new Cursor(Cursor.HAND_CURSOR);
private static final Cursor CURSOR_DEFAULT = new Cursor(Cursor.DEFAULT_CURSOR);
private static final Color HOVER_SHADOW = new Color(40, 80, 60, 50);
@Override
public void mouseEntered(MouseEvent e) {
JLabel component = (JLabel)e.getComponent();
component.setBackground(HOVER_SHADOW);
component.setCursor(CURSOR_HAND);
component.setOpaque(true);
component.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
JLabel component = (JLabel)e.getComponent();
component.setBackground(null);
component.setCursor(CURSOR_DEFAULT);
component.setOpaque(false);
component.repaint();
}
MainWindow類:
Image background = ResourceLoader.loadImage("board.png");
ImagePanel panel = new ImagePanel(background);
panel.setBounds(10, 55, 480, 480);
panel.setLayout(null);
panel_main.add(panel);
final JLabel lblNewLabel1 = new JLabel("N");
lblNewLabel1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel1.setOpaque(false);
lblNewLabel1.setBounds(25, 24, 52, 52);
lblNewLabel1.setFont(lblNewLabel1.getFont().deriveFont(42f));
lblNewLabel1.addMouseListener(new MouseHoverPiece());
panel.add(lblNewLabel1);
final JLabel lblNewLabel2 = new JLabel("O");
lblNewLabel2.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel2.setOpaque(false);
lblNewLabel2.setBounds(25+52+2, 24, 52, 52);
lblNewLabel2.setFont(lblNewLabel2.getFont().deriveFont(42f));
lblNewLabel2.addMouseListener(new MouseHoverPiece());
panel.add(lblNewLabel2);
請避免'的setBounds(...)',通常新手代碼的標誌。我猜你的形象是半透明的,是真的? –
我應該用什麼來代替邊界?我只需要將標籤的尺寸強制爲固定的尺寸。面板的圖像和標籤的背景不透明,而我想應用的鼠標懸停背景是50%透明。 – akaine
'我應該用什麼來代替邊界?' - 您使用[佈局管理器](http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)。 – camickr