我創建了一個簡單的程序,當鼠標在JLabel上時顯示一個JFram窗口。這似乎很好地工作,直到你通過鼠標在JLabel的很多次:JComponents開始變得破碎像這樣的畫面:JComponent和mouseListener非常奇怪的行爲
JComponents開始出現在任何地方,而且應該要顯示的JLabel,有一個「奇怪的粗體」字體。我認爲這可能發生,因爲程序永遠不會「退出」小窗口,所以內存永遠不會被釋放?!我可能也是錯的......但我當然不知道爲什麼會發生這種情況!
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class finestra implements MouseListener{
private JFrame finestra = new JFrame();
private JFrame pagina = new JFrame();
private JButton submit1 = new JButton("press");
private JTextField text = new JTextField();
finestra(){
pagina.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pagina.setSize(500, 500);
JPanel cont = new JPanel();
cont.setLayout(new GridLayout(3,4));
JLabel label = new JLabel();
label.setText("ON MOUSEROVER THIS");
cont.add(label);
label.addMouseListener(this);
cont.add(submit1);
cont.add(text);
pagina.add(cont);
pagina.setVisible(true);
finestra.setUndecorated(true);
}
@Override
public void mouseClicked(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
Point punto = event.getLocationOnScreen();
punto.setLocation(punto.getX()+20, punto.getY()+20);
JLabel littlelabel = new JLabel();
littlelabel.setText("your mouse is on the jlabel");
finestra.add(littlelabel);
finestra.setLocation(punto);
finestra.setSize(100,100);
finestra.setVisible(true);
}
}
}
@Override
public void mouseExited(MouseEvent event) {
if(event.getSource() instanceof JLabel){
JLabel event_casted = (JLabel)event.getSource();
if(event_casted.getText().equals("ON MOUSEROVER THIS")){
finestra.setVisible(false);
}
}
}
@Override
public void mousePressed(MouseEvent event) {
}
@Override
public void mouseReleased(MouseEvent arg0) {}
public static void main(String[] args0){
new finestra();
};
}
好,解決了JComponents無意義出現的問題。但是這個「奇怪的粗體」字體呢? –
@ElMapoMapo:請忽略此答案 - 這是錯誤的。讓我看看發生了什麼。 –
@ElMapoMapo:請參閱編輯回答。 –