Hi there!
I'm new to Java and just arrived at this forum.
I hope I can get some help here - getting a little desperate.
Well, I have to develop a small game in Java and in this game the user must be able to click on different spots on the screen and, well, make things happen.
I have everything ready in my head but don't know how to make objects clickable and get info from them...
So, I've tried and tried many different things, have read lots of tutorials but so far no good.. :(
I was wondering if someone would let me know what to do and even if I'm in the right direction...
Here go the codes...
All this thing does is plot two squares on a panel. What I'm trying to do is make them clickable and get them to return some info like "my name is blah and i've just been clicked".
Thank you thank you a lot for any hints...
This would be the main Class
import java.awt.Color;
import javax.swing.JFrame;
public class EventTest
{
public static void main( String args[] )
{
JFrame frame = new JFrame( "Mouse Event Test" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Panel painel = new Panel();
painel.setBackground(Color.WHITE);
frame.add( painel );
frame.setSize( 400, 210 );
frame.setVisible( true );
}
}
Other classes...
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class Panel extends JPanel
implements MouseListener {
public void mousePressed(MouseEvent e) {
saySomething("Mouse pressed", e);
}
public void mouseReleased(MouseEvent e) {
saySomething("Mouse released", e);
}
public void mouseEntered(MouseEvent e) {
saySomething("Mouse entered", e);
}
public void mouseExited(MouseEvent e) {
saySomething("Mouse exited", e);
}
public void mouseClicked(MouseEvent e) {
saySomething("Mouse clicked", e);
}
void saySomething(String eventDescription, MouseEvent e) {
System.out.println("Mouse event detected: "+e);
}
Square q1 = new Square();
Square q2 = new Square();
public void paintComponent( Graphics g )
{
super.paintComponent( g );
this.setBackground( Color.WHITE );
q1.show(50,50,g);
q2.show(100,50,g);
}
public void addMouseListener(MouseListener l) {
}
}
This one creates the small squares...
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class Square {
public Square() {
}
public void show(int x, int y,Graphics g) {
g.setColor(Color.getHSBColor(125, 125, 125));
g.fillRect(x,y,20,20);
g.setColor(Color.WHITE);
g.drawRect(x, y, 20, 20);
}
}