我最近制作了一个程序,其中在内容窗格中设置了MouseListener
。问题是,当我点击JTextField
时,即使我在其上调用setEnabled(false)
和setEditable(false)
,我的mousePressed()
也不会发生。其余的工作正常。所以我的问题是:如何禁用MouseListener
包含的默认JTextField
?
编辑:用于测试目的:
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class test extends JFrame implements MouseListener{
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test frame = new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
test(){
setBounds(0,0,500,500);
addMouseListener(this);
setLayout(null);
JTextField n = new JTextField("test");
n.setEditable(false);
n.setBounds(200,200,40,20);
add(n);
}
@Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("test");
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
我禁用了它,因此您无法选择它的字符。
您可以通过使用自定义Caret始终使选择的开头/结尾相同来阻止在任何文本字段中选择文本:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class NoTextSelectionCaret extends DefaultCaret
{
public NoTextSelectionCaret(JTextComponent textComponent)
{
setBlinkRate( textComponent.getCaret().getBlinkRate() );
textComponent.setHighlighter( null );
}
@Override
public int getMark()
{
return getDot();
}
private static void createAndShowUI()
{
JTextField textField1 = new JTextField("No Text Selection Allowed");
textField1.setCaret( new NoTextSelectionCaret( textField1 ) );
textField1.setEditable(false);
JTextField textField2 = new JTextField("Text Selection Allowed");
JFrame frame = new JFrame("No Text Selection Caret");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textField1, BorderLayout.NORTH);
frame.add(textField2, BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}