2014-02-19 10 views
0

JLabel 색상을 변경하는 데 문제가 있습니다. 3 개의 JLabel 변수를 사용하고 있습니다. 이 JLabel 변수에 마우스 이벤트를 걸고 있습니다. 나는 마우스를 움직일 때 JLabels에 색을 바꾼다. 그게, 내가 JLabel 변수에 마우스를 입력 할 때 JLabel의 색을 바꿀 때입니다.JLabel 색상을 변경하는 방법

이 문제를 해결하십시오. ... 나는 당신의 문제는 당신이 레이블이 때이다 가정 당신이 요구하는 것을 완전히 확인

entry.addMouseListener(this); 
entry.setOpaque(true); 
profile.addMouseListener(this); 
profile.setOpaque(true); 

public void mouseClicked(MouseEvent mc) 
{} 

public void mouseEntered(MouseEvent me) 
{ 
    entry.setForeground(Color.red); 
    profile.setForeground(Color.red); 
} 

public void mouseExited(MouseEvent me) 
{ 
    entry.setForeground(Color.white); 
    profile.setForeground(Color.white); 
} 
public void mousePressed(MouseEvent mp) 
{} 
public void mouseReleased(MouseEvent mr) 
{} 
+0

무엇이 질문입니까? 나는 이해하지 못한다 .Btw isnt setForeground (color) 뭘 원해? 그 변경 글꼴 색상. –

+2

왜 마우스를 _one_ 위에 올려 놓았을 때 레이블이 바뀌는 지 묻고 있습니까? 이 경우'me.getSource(). setBackground (...)'를 시도해보십시오. –

+0

@tobias_k : 바람직하지 않으면'getSource()'대신'getComponent()'가 필요합니다. 그렇지 않으면 타입 캐스트가 필요합니다. 하지만 네가 꼼짝 못하게했다고 생각해. – Holger

답변

1

하지 :

entry.addMouseListener(this); 
    entry.setOpaque(true); 
    profile.addMouseListener(this); 
    profile.setOpaque(true); 

    public void mouseClicked(MouseEvent mc) 
    { 


    } 
    public void mouseEntered(MouseEvent me) 
    { 
     entry.setBackground(color); 
     profile.setBackground(color); 
    } 
    public void mouseExited(MouseEvent me) 
    { 

    entry.setBackground(Color.white); 
    profile.setBackground(Color.white); 

    } 
    public void mousePressed(MouseEvent mp) 
    { 

    } 
    public void mouseReleased(MouseEvent mr) 
    { 

    } 
1

귀하의 문제는 방법 setBackground() 변경 setForeground()에있다 그들 중 하나에 마우스를 입력하면 그저 레이블이 빨간색 배경이되고 싶지 만, 둘 다 원하지 않습니다.

이렇게하려면 e.getComponent()을 사용하여 마우스 이벤트를 트리거 한 레이블을 가져온 다음 해당 레이블의 배경 만 설정하면됩니다. 또한 기본 프레임의 배경이 항상 흰색이 아니기 때문에 setBackground(null)을 사용하여 배경색을 재설정 할 수 있습니다. 마지막으로, MouseListener 대신 MouseAdapter 클래스를 사용할 수 있으며, 필요하지 않은 다른 모든 메소드에 기본값 (no-op)을 제공 할 수 있습니다.

MouseListener ma = new MouseAdapter() { 
    public void mouseEntered(MouseEvent e) { 
     e.getComponent().setBackground(Color.RED); 
    } 
    public void mouseExited(MouseEvent e) { 
     e.getComponent().setBackground(null); 
    } 
}; 
관련 문제