我有一个带有“输入鼠标”文字的JLabel。一旦用户在其上输入鼠标,我就会想要出现一个JTextField,这样用户就可以搜索一些东西。如果删除鼠标,则必须再次显示先前的JLabel。我用:
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ML extends JFrame {
private static final long serialVersionUID = 1L;
public ML() {
GridLayout gl = new GridLayout(1, 2);
setLayout(gl);
JPanel jp = new JPanel();
CardLayout cl = new CardLayout();
jp.setLayout(cl);
JPanel jp1 = new JPanel();
JLabel jl = new JLabel("Enter mouse!");
jp1.add(jl);
JPanel jp2 = new JPanel();
JTextField jtf = new JTextField(20);
jp2.add(jtf);
jp.add(jp1, "1");
jp.add(jp2, "2");
cl.show(jp, "1");
jp.addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent evt)
{
cl.show(jp, "2");
}
public void mouseExited(MouseEvent evt)
{
cl.show(jp, "1");
}
});
add(jp);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ML();
}
});
}}
一切都运行得很好但是当我将鼠标悬停在JLabel“Enter mouse”上时,它在这个和JTextField之间有些错误/闪烁。为什么会这样,我该怎么做才能解决它? TY
答案 0 :(得分:3)
这是因为当显示JTextField
时,会立即调用mouseExited()
方法。然后当然再次显示JLabel
,当你继续移动鼠标时,它会循环。
以下作品:
jl.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
cl.show(jp, "2");
}
});
jtf.addMouseListener(new MouseAdapter() {
public void mouseExited(MouseEvent evt) {
cl.show(jp, "1");
}
});
答案 1 :(得分:3)
即使它没有出现故障,它也不会起作用,因为文本字段大于标签,并且您只将监听器添加到标签中。导致故障是因为仅显示了文本字段,因此它会触发标签上的mouseExited
事件。要解决此问题,您需要标签上的mouseEntered
事件 ,但文本字段上的mouseExited
事件仅。
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class ML extends JFrame {
private static final long serialVersionUID = 1L;
public ML() {
GridLayout gl = new GridLayout(1, 2);
setLayout(gl);
JPanel jp = new JPanel();
CardLayout cl = new CardLayout();
jp.setLayout(cl);
JPanel jp1 = new JPanel();
JLabel jl = new JLabel("Enter mouse!");
jp1.add(jl);
JPanel jp2 = new JPanel();
JTextField jtf = new JTextField(20);
jp2.add(jtf);
jp.add(jp1, "1");
jp.add(jp2, "2");
cl.show(jp, "1");
jl.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
cl.show(jp, "2");
}
});
jtf.addMouseListener(new MouseAdapter() {
public void mouseExited(MouseEvent evt) {
cl.show(jp, "1");
}
});
add(jp);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ML();
}
});
}
}