JApplet does not receive mouse-events

62 views Asked by At

I'm trying to listen to MouseEvents in Java on a JApplet in a JFrame. My program is actually doing more stuff, but I've simplified it for you to this:

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;

public class mouse extends JApplet implements MouseListener, MouseMotionListener {

static final private int SCREENW = 800;
static final private int SCREENH = 300;

private static JFrame window = null;

public mouse() {
    if(window!=null)
        return;

    window = new JFrame("Window");
    window.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    window.addMouseListener( this );
    window.addMouseMotionListener( this );
    window.getContentPane().add("Center", this);

    window.pack();
    window.setSize(new Dimension(SCREENW, SCREENH));
    window.setVisible(true);    
    window.setFocusable(true);  
    window.requestFocusInWindow();      

}   

public void mouseEntered( MouseEvent e ) {
    System.out.println("Test0");
}
public void mouseExited( MouseEvent e ) {
    System.out.println("Test1");
}
public void mouseClicked( MouseEvent e ) {
    System.out.println("Test2");
}
public void mousePressed( MouseEvent e ) {   
    System.out.println("Test3");
}
public void mouseReleased( MouseEvent e ) {  
    System.out.println("Test4");
}
public void mouseMoved( MouseEvent e ) {  
    System.out.println("Test5");
}
public void mouseDragged( MouseEvent e ) {  
    System.out.println("Test6");
}



public static void main(String s[]) {
    mouse Mouse = new mouse();  

}
}

Note: I'm testing all this on a Ubuntu 14.04 maschine. When running 'java mouse', the window opens but no event is triggered. What is wrong?

2

There are 2 answers

0
user1511417 On BEST ANSWER
window.setBounds(100, 100, SCREENW, SCREENH);

was missing!

2
Curmudgeon On

Are you aware that JApplets can draw on their own? If run in a web page, creating a frame from a class extending JApplet would result in the JApplet running in the page, while the JFrame would pop out.

You can see an example here, basically you shouldn't need a JFrame to display your primitives. A paint() function should be enough to do that.