import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.event.*;
public class MouseAct extends JFrame{
public static void main(String args[]){
MouseAct M= new MouseAct();
M.paint1();
}
public void paint1(){
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(640,480); //
show();
}
public void paint( Graphics g ){
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g.setColor(Color.black);
g.fillRect(1,1,638,478);
g.setColor(Color.white);
g.drawRect(1,1,638,478);
g.drawRect(100,100,100,100);
MouseListener l = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
MouseAct b = (MouseAct)e.getSource();
System.out.println("source="+e.getSource());
// b.setSelected(true);
b.repaint();
}
public void mouseReleased(MouseEvent e) {
MouseAct b = (MouseAct)e.getSource();
// b.setSelected(false);
b.repaint();
}
};
}
// public void setSelected(){
}
views:
42answers:
2
+1
A:
(1) don't create the Mouselistener inside the paint method - now you create a new one on each repaint. Inside paint1()
would be a better place
(2) add the listener to your MouseAct object. Then it will be called whenever the mouse button is pressed while the pointer is 'over' your frame.
public void paint1(){
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize(640,480);
MouseListener l = new MouseAdapter() { ... } // add your code here
addMouseListener(l); // this 'activates' the listener
show();
}
Andreas_D
2010-08-09 11:36:17
+1
A:
You should NOT be overriding the paint() method of a JFrame or any Swing component.
Custom painting is done by overriding the paintComponent() method of a JComponent and then you add the component to the content pane of the frame. The MouseListener can then be added to this component.
Read the section from the Swing tutorial on Custom Painting for more information. The tutorial also has a section on "How to Write a Mouse Listener".
camickr
2010-08-09 14:06:49