|
How to program a panel that handles its own mouse events |
|
This Java Swing tip illustrates a method of programming a panel that handles
its own mouse events. A self-contained JPanel class that handles its own mouse
events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SelfContainedPanel extends JPanel {
private int x1, y1, x2, y2;
public SelfContainedPanel()
{
addMouseListener(
new MouseAdapter() {
public void mousePressed( MouseEvent e )
{
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased( MouseEvent e )
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
}
);
addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e )
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
}
);
}
public Dimension getPreferredSize()
{
return new Dimension( 150, 100 );
}
public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ),
Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) );
}
}
// Creating a self-contained subclass of JPanel
// that processes its own mouse events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SelfContainedPanelTest extends JFrame {
private SelfContainedPanel myPanel;
public SelfContainedPanelTest()
{
myPanel = new SelfContainedPanel();
myPanel.setBackground( Color.yellow );
Container c = getContentPane();
c.setLayout( new FlowLayout() );
c.add( myPanel );
addMouseMotionListener(
new MouseMotionListener() {
public void mouseDragged( MouseEvent e )
{
setTitle( "Dragging: x=" + e.getX() +
"; y=" + e.getY() );
}
public void mouseMoved( MouseEvent e )
{
setTitle( "Moving: x=" + e.getX() +
"; y=" + e.getY() );
}
}
);
setSize( 300, 200 );
show();
}
public static void main( String args[] )
{
SelfContainedPanelTest app =
new SelfContainedPanelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.