Anonymous awt.event

Hello, This code is copied from a Sun tutorial and I am getting a compiler error that states that
init:
deps-jar:
Compiling 1 source file to C:\271\SwingPaintDemo1\build\classes
C:\271\SwingPaintDemo1\src\SwingPaintDemo1.java:67: addMouseMotionListener(java.awt.event.MouseMotionListener) in java.awt.Component cannot be applied to (<anonymous java.awt.event.MouseAdapter>)
addMouseMotionListener(new MouseAdapter() {
1 error
BUILD FAILED (total time: 0 seconds)
Here is the code: Can someone help please?
* SwingPaintDemo1.java
* Created on October 8, 2007, 8:07 AM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package painting;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
public class SwingPaintDemo1 {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+
        SwingUtilities.isEventDispatchThread());
        JFrame f = new JFrame("Swing Paint Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
class MyPanel extends JPanel {
    private int squareX = 50;
    private int squareY = 50;
    private int squareW = 20;
    private int squareH = 20;
    public MyPanel() {
        setBorder(BorderFactory.createLineBorder(Color.black));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                moveSquare(e.getX(),e.getY());
    private void moveSquare(int x, int y) {
        int OFFSET = 1;
        if ((squareX!=x) || (squareY!=y)) {
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
            squareX=x;
            squareY=y;
            repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
    public Dimension getPreferredSize() {
        return new Dimension(250,200);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);      
        g.drawString("This is my custom Panel!",10,20);
        g.setColor(Color.RED);
        g.fillRect(squareX,squareY,squareW,squareH);
        g.setColor(Color.BLACK);
        g.drawRect(squareX,squareY,squareW,squareH);
}

Use
addMouseMotionListener(new MouseMotionAdapter()

Similar Messages

  • Flush pending AWT events programmatically

    Hello, everybody.
    Is there a way to flush pending AWT events programmatically? I would like to be able to use it in a code like this:
    if (comp.requestFocusInWindow())
        // flush pending AWT events...
        KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        if (focusManager.getPermanentFocusOwner() == comp)
            // do something...
    }Thank you.
    Marcos
    PS: I know I can use a FocusListener in comp, but it is not an option in my case.

    Maxideon wrote:
    You can get to the system EvenQueue and pending AWTEvents with,
    java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue()As of java 7, there's a method called #createSecondaryLoop that might be morphed into the kind of functionality you want. I'm basing this off the api description. I have not tried using the method myself.Thank you for the suggestion, Maxideon. I'm using now the solution in this thread:
    http://stackoverflow.com/questions/15451907/flush-pending-awt-events-programmatically
    Marcos

  • How to enqueue custom AWT event?

    hi,
    in my applet I need to use custom AWT events. I subclass them from java.awt.AWTEvent and set their id to higher as AWTEvent.RESERVED_ID_MAX - as recomended in documentation.
    But how to enqueue such event? A tried to use following approach:
    getToolkit().getSystemEventQueue().postEvent( myEvent );
    and it works fine - but only in browsers usings Sun's VM implementation. In browsers using Microsoft's VM I'm getting following exception:
    com.ms.security.SecurityExceptionEx[matlu/client/ClientConnection.enQueue]: Event queue access denied.
    So the question is: is there any other way to enqueue custom event, which will keep Microsoft's security manager happy?
    thak you very much
    Lubo Matecka

    I know it must be visible... (But it doesnt have to be bigger than 1 pixel...)
    The code I posted is just to illustrate the idea.
    If you need to post multiple events you just replace the AWTEvent member with a LinkedList (or some similar FIFO).
    Then in postEvent you do theLinkedList.addFirst(yourEvent)
    And in paint() you do AWTEvent ev = (AWTEvent)theLinkedList.removeLast();
    process ev.
    if(theLinkedList.size() > 0)
       repaint();Yes. I have run into the same problem, and I did not use the repaint- trick...
    My applet communicates with the server in a separate thread. When a response receives the communication thread should post an event to the AWT- thread to get the response processed.
    My solution here is to process the thread in the communicator- thread. This is a bad solution because it might create multithreading bugs.... but it has proven to work ok in practice.
    Another example is like this. The use presses the mouse at Component B so that:
    1 Component A gets a focusLost event.
    2 Component B gets a mousePressed.
    3 I want to do something in component A that should be done after component B has processed the mousePressed event. This can be solved without using events. You just have to write some more code (You are already in the right thread).

  • How to "kill" AWT Event Queue thread without using System.exit()?

    When I run my program and the first GUI window is displayed a new thread is created - "AWT-Event Queue". When my program finishes, this thread stays alive and I think it causes some problems I have experienced lately.
    Is there any possibility to "kill" this thread without using System.exit() (I can't use it for some specific reasons)

    All threads are kept alive by the JVM session. When you use System.exit(int) you kill the current session, thus killing all threads. I'm not sure, though...
    What you could do, to make sure all threads die, is to make ever thread you start member of a thread group. When you want to exit you app, you kill all the threads in the thread group before exit.
    A small example:
    //Should be declared somewhere
    static ThreadGroup threadGroup = new ThreadGroup("My ThreadGroup");
    class MyClass extends Thread {
    super(threadGroup, "MyThread");
    Thread thread = new Thread(threadGroup, "MySecondThread");
    void exit() {
    //Deprecated, seek alternative
    threadGroup.stop();
    System.exit(0);
    }

  • Synchronize AccessBridge thread with AWT event thread?

    Hi,
    I am a beginner in Java Access Bridge.
    I am writing a program that runs with Java Web Start and uses JFC Swing. For system monitoring purpose my company uses HP OpenView. Probe Builder is used for recording a probe for the application. The probe will be run at regular intervals to check if anything is broken. As I understand Probe Builder uses Java Access Bridge to record & control the application flow.
    Without Java Access Bridge my program runs fine. But when I run it with Probe Builder I occasionally catch some exceptions that indicate that there are two threads running over my gui classes at the same time, the AWT event thread and another thread that comes from com.sun.java.accessibility.AccessBridge.run.
    Since my classes are not thread safe (like all the Swing classes) there are race conditions that result in a NullPointerException.
    My question is that how can I make sure that only one thread at a time is running over my code? Can I somehow make Java Access Bridge run with the AWT event thread? Or do I have to synchronize all my methods - I want to avoid this since I am not sure that this can be done perfectly.
    I will appreciate any help.
    Thanks
    Message was edited by:
    karneim

    Maybe there is some other way to "kill" this thread because for some specific reasons I don't think I will be able to use System.exit(). This reason is - I'm using this Java program in Lotus Notes (don't know if you have had any experience with this) and if I call System.exit() then some important clean-up (garbage collection) won't be done.

  • AWT Event Listener not listening...

    Hi,
    I'm having problems with an AWT Event Listener on a JFrame.
    Basically, im making a tank game, so the first screen to appear is an inventory screen. The when you click start on this screen, you create a GameScreen which extends JFrame. i have an AWT Event Listener added to this frame using this code:
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener(){
    public void eventDispatched(AWTEvent e) {
    if(((KeyEvent)e).getKeyCode() == KeyEvent.VK_DOWN && e.getID() == KeyEvent.KEY_PRESSED)
    It's checking events on the arrow keys and the tab and enter keys.
    So when the this round of the game has finished, i setVisible to false, and make the inventory visible again.
    The problem is, when i set make the GameScreen visible again, the listeners aren't working.
    It seems to be working fine for 'enter', that is VK_ENTER, but not for the arrow keys...
    Any1 have any ideas??
    Any help would be great!
    Thanks,
    D.

    I am willing to bet that your problem lies in that once you return the main game screen from the inventory screen that you need to set the focus back to the main game screen. I believe, as events go, the component that has the focus is the one that will receive the events and process them according to their listener code. As I am not sure where your focus goes once you close the inventory screen and open the main screen, it could be that the wrong component has the focus.
    As far as getting the focus to the correct component is concerned, I remember myself and Malohkan having a discussion as to how to get this to work, and he came up with a work-around. That thread is somewhere in this forum. I'm not sure if it will solve your problem, but it might be something worth looking into.
    -N.

  • Running JUnit tests from AWT Event Quene

    Anyone know how to run JUnit tests from the AWT Event Queue? JFCUnit is overkill; I'm just looking for a TestRunner that runs on a different thread. I can delve into the JUnit documentation but, with luck, someone who's been through this before can spare me the trouble. Also, anyone else get a server error when searching for "JUnit event dispatch" on this forum?

    JUnit 3 version:
    import java.util.concurrent.atomic.AtomicReference;
    import javax.swing.SwingUtilities;
    import junit.framework.TestCase;
    public abstract class EDTTestCase extends TestCase {
         * Overriding this method guarantees that setUp(), tearDown(), and all
         * tests run on the EDT.
        @Override
        public void runBare() throws Throwable {
            final AtomicReference<Throwable> problem = new AtomicReference<Throwable>();
            if (!SwingUtilities.isEventDispatchThread()) {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        try {
                            runBare();
                        catch (Throwable throwable) {
                            problem.set(throwable);
                if (problem.get() != null) {
                    throw problem.get();
            else {
                super.runBare();
    }

  • Updating component within awt-event thread of another component

    Hi,
    I'm having trouble updating (repainting) a component inside the awt-event thread of another component. The component I want to update is a JFrame with a JLabel that lists the progress of the original component's action that triggered the event. I can get the frame to pop up but it's content is never fully painted and never refreshed.
    I've tried using invokeLater() (the frame ran after the original awt-event had finished) and invokeAndWait() (blocked the original awt-event) and running the computational intensive parts of the original component's action in SwingWorker threads (no difference) but all to no avail.
    What I want to do is similar to a progress bar so I think it should possible. Any suggestions? Thanks, Matt

    Are you calling yield() or sleep(...) on your Thread?

  • MACOS 10.4: Solve AWT Event queue hangup

    Hi,
    I'm having trouble with the AWT eventqueu. On MacOS 10.4, using Java 5 Runtime, my applet sometimes blocks. When looking at the threadstack, the deadlock always appears in the Event Loop, dispatching an AWT event, blocking in the CGlobalCursorManager._updateCursor call. In fact the CGlobalCursorManager.findHeavyweightUnderCursor Native call.
    I already tried some workarounds:
    - overwrite the validate method of my custom AWT components. Making sure that they do not block forever. This solves the problem for events coming through the overidden component, but it has to work for every event that might trigger the GlobalCursorManager.
    I had some possible solutions for which I would like some pro's and con's in this forum:
    1. I could try to kill the event loop. Is it possible to quit the event loop and restart it from within the applet ?
    2. Can I force each AWT container to use another implementation of the validate method ?
    3. Can I set another, customized, CGlogalCursorManager ?
    4. Other possibilities ?
    Thanks in advance for all those responding.

    I think you mean that I can override the validate method for each custom UI object separately.
    That's a possibility, but I was looking for a more general solution. If possible, I would to extends one
    class. E.g. can I set another event queue ? That way, I could make a custom event queue in case of a Mac OS browser.

  • Invoke an awt event from outside the swing application

    Is it possible to invoke an awt event triggered from outside the swing app? I am trying to implement a use case where i have to open a new tab in an already running swing app when a user clicks on a browser link.

    I have a desktop application that was invoked via webstart. The java webstart process started when the user clicked on a link that downloaded the swing application and now it runs in the clients JVM. Each browser click downloades and launches the application that performs a certain function. Now lets say, the user clicks on another link, then i don't want another java application to be launched. I want the same application that executes the function in lets say a new tab.
    Its kind of like you click on a link that somebody sent you in an outlook email. When you click on it and if firefox is already running, the link opens up in a new tab on an already running firefox browser. If firefox was not running, it starts a new firefox process.
    Hope this makes sense

  • Problem with java.awt.MouseInfo or java.awt.event.*;

    I have a problem with the MouseInfo class. I think.. because in my mousePressed(MouseEvent event) method, I have this:
         public void mousePressed(MouseEvent event) {
              pInfo = mInfo.getPointerInfo();
              point = pInfo.getLocation();
              pointX = point.getX();
              pointY = point.getY();
              System.out.println("pointer is at: (" + (int)pointX + ", " + (int)pointY + ")");
         }I think you all could figure out what this does. I declared the variables at the top and I implemented MouseListener... when I click it doesnt tell me the X and Y coords.
    Alright, thanks. Any help appreciated.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MouseExample extends MouseAdapter implements Runnable {
        @Override
        public void mousePressed(MouseEvent event) {
            int x = event.getX();
            int y = event.getY();
            System.out.println("x=" + x + ", y=" + y);
        @Override
        public void run() {
            JLabel label = new JLabel("Click anywhere", SwingConstants.CENTER);
            label.setPreferredSize(new Dimension(300, 200));
            label.addMouseListener(this);
            JFrame f = new JFrame();
            f.getContentPane().add(label);
            f.pack();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        public static void main(String[] args) {
            EventQueue.invokeLater(new MouseExample());
    }

  • JTable Awt -Event Queue problem

    Hi
    I've been looking everywhere for a solution to this, but can't seem to find one. I've got a JTable with an underlying model that is being continuously updated (every 100ms or so). Whenever I try to sort the JTable using TableRowSorter while the model is being added to I get
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.Vector.elementAt(Vector.java:430)
    at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
    I don't understand this as in my custom table model I've added the fireTableChanged etc. in a SwingUtilities.invokeLater( ...) thread.
    Has anyone else encountered this problem and found a solution? I'd be really grateful!
    Thanks

    Hi
    Thanks for responding, I'm still a little confused. I've posted the code below for both the JTable and the TableModel. The tablemodel simply gets values from a vector which is being dynamically updated from outside the table - but whenever the vector is added to
    The problem seems to only occur when I press the column header to sort the tables during the updates. My understanding is that the method refresh() should create a threadsafe update of the table - but somehow it refreshes the binding to the tablemodel and during this time the table returns a defaulttablemodel that doesn't correspond to the actual underlying data....I thought this kind of problem would be solved by invoking all updates on the swing event thread, but it seems to still produce the effect and I'm stumped!!
    (The data is in an array called turns, and the addElement() in another class calls the refresh() method)
    many thanks, in the hope that someone has the kindness and and benevolence to wade through the following code!
    public class JContiguousTurnsListTable extends JTable {
    private JContiguousTurnsListTableModel jctltm;
    public JContiguousTurnsListTable(Conversation c) {
    super();
    jctltm = new JContiguousTurnsListTableModel(this,c);
    this.setModel(jctltm);
    setSize();
    //this.setAutoResizeMode(AUTO_RESIZE_ALL_COLUMNS);
    //this.setAutoCreateRowSorter(true);
    TableRowSorter <TableModel> sorter = new TableRowSorter <TableModel>(jctltm);
    //sorter.setSortsOnUpdates(true);
    this.setRowSorter(sorter);
    System.err.println("Setting up ");
    private void setSize(){
    TableColumn column = null;
    for (int i = 0; i <11; i++) {
    column = this.getColumnModel().getColumn(i);
    if(i==1||i==2||i==3||i==4||i==8||i==9){
    column.setPreferredWidth(50);
    else if (i==0||i==5){
    column.setPreferredWidth(180);
    else if (i == 6) {
    column.setPreferredWidth(150);
    else if(i==10){
    column.setPreferredWidth(250);
    else
    column.setPreferredWidth(100);
    //column.setPreferredWidth(100);
    //column.setMinWidth(100);
    //column.setMaxWidth(100);
    public String getColumnName(int column){
    return jctltm.getColumnName(column);
    public void refresh(){
    this.jctltm.refresh();
    ----------------And the table model:
    public class JContiguousTurnsListTableModel extends AbstractTableModel {
    private Conversation c;
    public JContiguousTurnsListTableModel(JTable jt,Conversation c) {
    super();
    this.c=c;
    public void refresh(){
    //System.out.println("Refresh");
    SwingUtilities.invokeLater(new Runnable(){public void run(){fireTableDataChanged();fireTableStructureChanged();} });
    public boolean isCellEditable(int x, int y){
    return false;
    public String getColumnName(int column){
    if(column==0){
    return "Sender";
    else if(column==1){
    return "Onset";
    else if (column==2){
    return "Enter";
    else if(column ==3){
    return "E - O";
    else if(column ==4){
    return "Speed";
    else if(column ==5){
    return "Spoof Orig.";
    else if(column ==6){
    return "Text";
    else if(column ==7){
    return "Recipients";
    else if(column ==8){
    return "Blocked";
    else if(column ==9){
    return "Dels";
    else if(column ==10){
    return "TaggedText";
    else if(column ==11){
    return "ContgNo";
    else if(column ==12){
    return "Inconcistency";
    else{
    return " ";
    public Object getValueAt(int x, int y){
    try{ 
    //System.out.println("GET VALUE AT "+x+" "+y);
    Vector turns = c.getContiguousTurns();
    if(x>=turns.size())return " ";
    ContiguousTurn t = (ContiguousTurn)turns.elementAt(x);
    if(y==0){
    return t.getSender().getUsername();
    else if(y==1){
    return t.getTypingOnset();
    else if(y==2){
    return t.getTypingReturnPressed();
    else if(y==3){
    return t.getTypingReturnPressed()-t.getTypingOnset();
    else if(y==4){
    long typingtime = t.getTypingReturnPressed()-t.getTypingOnset();
    if(typingtime<=0)return 0;
    return ((long)t.getTextString().length())/typingtime;
    else if(y==5){
    return t.getApparentSender().getUsername();
    else if(y==6){
    return t.getTextString();
    else if(y==7){
    //System.out.println("GETTINGRECIP1");
    Vector v = t.getRecipients();
    String names ="";
    // System.out.println("GETTINGRECIP3");
    for(int i=0;i<v.size();i++){
    Conversant c = (Conversant)v.elementAt(i);
    // System.out.println("GETTINGRECIP4");
    names = names+", "+c.getUsername();
    // System.out.println("GETTINGRECIP5");
    return names;
    else if (y==8){
    if (t.getTypingWasBlockedDuringTyping())return "BLOCKED";
    return "OK";
    else if(y==9){
    return t.getNumberOfDeletes();
    else if(y==10){
    String returnText="";
    Vector v = t.getWordsAsLexicalEntries();
    for(int i=0;i<v.size();i++){
    LexiconEntry lxe= (LexiconEntry)v.elementAt(i);
    returnText = returnText+lxe.getWord()+" ("+lxe.getPartOfSpeech()+") ";
    return returnText;
    else if(y==11){
    return t.getNumberOfTurns();
    else if(y==12){
    // System.out.println("CONTIGUOUS1");
    String value ="";
    boolean hasSameRecipients = t.getTurnsHaveSameRecipients();
    boolean hasSameApparentOrigin = t.getTurnsHaveSameApparentOrigin();
    if (hasSameRecipients&hasSameApparentOrigin){
    value = "OK";
    else if (hasSameRecipients&!hasSameApparentOrigin){
    value = "Diff. O";
    else if(!hasSameRecipients&hasSameApparentOrigin){
    value = "Diff. Recip";
    else {
    value = "Diff O&R";
    //System.out.println("CONTIGUOUS2");
    return value;
    return " ";
    }catch (Exception e){
    return "UI ERROR";
    public Class getColumnClass(int column) {
    Class returnValue;
    if ((column >= 0) && (column < getColumnCount())) {
    returnValue = getValueAt(0, column).getClass();
    } else {
    returnValue = Object.class;
    return returnValue;
    public int getRowCount(){
    return this.c.getContiguousTurns().size();
    public int getColumnCount(){
    return 13;
    }

  • AWT-Event queue not responding

    Hi all! I have already posted a message with similar problem wich was solved but this now is a different one.
    I have following situation:
    I have a class that is called from somewhere (I don't know where from) and that displays a JFrame. After it calls setVisible(true) it calls function synchronized lock() which does wait(). After the JFrame is done it calls synchronized unlock() which does notifyAll().
    The purpose is that my JFrame should do some checking and then let the code that called it resume it's work normaly.
    Te problem is that this only works with JDK version 1.3. If I do it on 1.4 the frame doesn't respond to clicks and doesn't repaint. If I remove lock() and unlock() the frame works ok but the main program is not suspended.
    I suppose that the frame needs to make new threads for user clicks or repainting (I have noticed a Timer thread) but it can't do it for some reason.
    Any help?

    Yeah, as the doctor said to the patient who said "Doctor, it hurts when I do this" .. "So don't do that" ... don't do that. That is, it sounds as if your application is posting huge numbers of events? So if your application didn't post so many events, would the event queue not be filled up?
    - David

  • AWT Event Thread dying

    Hi All
    I am using a JTree and I will add some data to the JTree. Then I am removing that data from its original location.What is happening is that in the JTree paint method its calling DefaultMutableTreeNode.toString() which will call myObject.toString() .Since I have deleted these objects it will throw Exceptions .Since these Exceptions are thrown in EventThread some times the Application ghet crashed . Can anybody suggest me some solurtion for this?
    Thanks
    Pradeep

    Hi
    Thanks for the reply. How can I know when the file is deleted. Is there any listener for that?. Actually I tried Tree listener, but it didnot catch any events.
    Thanks
    Pradeep

  • Help for awt event handling consume fundamantal

    I have doubt about MouseEvent consume(). And, what it is used for?
    As, I tried an example and I could not figure out what it was doing
    Please give your suggestions on this
    Thanks
    nick

    Just another cross poster.
    [http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=2&t=018087]
    db

Maybe you are looking for

  • Intel iMac won't play DVD

    I have an Intel iMac purchased in late 2009 and the superdrive has quit playing DVDs. It will burn all types of media and will play CDs and will read and install software CDs but will not play a DVD. These are new commercial movies. After inserting t

  • IMovie refuses to load.

    It seems that whenever I try to open iMovie, the GUI refuses to load. I can see iMovie up in my tool bar and according to the computer, its running just fine. It might be just coincidence, but this happened right after I downloaded a software update.

  • Street Number getting Truncated in BAPI_PO_CREATE and CHANGE

    Dear All For an PO create interface, we are trying to use BAPI_PO_CREATE and BAPI_PO_CHANGE . The issue is in the structure POADDRDELIVERY. Here we give delivery address of the Purchase Order line item which later gets populated in Delivery address t

  • Objects as parameters?

    Hello I have a question. I have 2 classes: a simpleInterest and compoundInterest. Now they pretty much do the same thing except calculate differently. Now my problem is that depending on what type of interest a person wants, I should do this somehow

  • Build Skills Around MDM

    Hi, I am an SAP HR Consultant. And have been tracking developments around MDM. I find MDM very interesting and challenging and would like to develop skills in MDM and position myself as MDM Consultant over the next 6-12 months time. Could any one sug