jTextArea
Hi, well i was wondering iff you could help me with this problem,well, i want to avoid or disable all the Mouse Events in a jTextArea but without having to make it NonEditable, how can i do this?, because i really have no idea, i meant, i tried by doing a MouseListener and creating all the mouse functions as empty or making the MouseEvent variable = null, but it didnt work, so i really dont know when these events are processed.
[438 byte] By [
JFAa] at [2007-10-2 20:34:37]

If you know, please tell me man, im trying to do a console window, very similar to the MS DOS console if you look at it, so, its important to me that the user can't use the mouse to erase everything or something like that, so,, please tell me if you know how i can avoid all the Mouse
JFAa at 2007-7-13 23:17:46 >

If you are sure this is something you want to do, one way of doing it is to tap into the event queue and filter out all MouseEvents that originates in your JTextArea. You can do that using the method addAWTEventListener in the Toolkit class, like in this simple demo program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NoMouseEventTextArea extends JFrame {
private JTextArea textWithMouseControl;
private JTextArea textWithoutMouseControl;
public NoMouseEventTextArea() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
textWithMouseControl = createTextArea("Allows mosue control");
textWithoutMouseControl = createTextArea("Does not allow mouse control");
disableMouseEventsForTextArea();
JPanel p = new JPanel(new GridLayout(0, 1, 10, 10));
p.add(new JScrollPane(textWithMouseControl));
p.add(new JScrollPane(textWithoutMouseControl));
setContentPane(p);
pack();
setLocationRelativeTo(null);
}
private void disableMouseEventsForTextArea() {
// This is core of this trick:
AWTEventListener consumer = new MouseEventConsumer();
Toolkit.getDefaultToolkit().addAWTEventListener(consumer,
AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
private class MouseEventConsumer implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
if (event.getSource() == textWithoutMouseControl) {
// This cast is safe, because the listener is only
// registered for MouseEvents (see above)
((MouseEvent) event).consume();
}
}
}
private JTextArea createTextArea(String text) {
JTextArea ta = new JTextArea(text, 5, 40);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
return ta;
}
public static void main(String[] args) {
new NoMouseEventTextArea().setVisible(true);
}
}
> Thanks a lot man!!, it worked!!
Glad I could help. I just realized that there is a much simpler way of doing it though, and that is to override the processMouseEvent method:
JTextArea ignoresMouseEvents = new JTextArea("I won't accept any MouseEvents") {
protected void processMouseEvent(MouseEvent e) {
// Do nothing.
}
};
Not sure if the two alternatives are completely identical with respect to side-effects, but you could give it a try.