Creating a mouselistener over a single Jpane
it's my first post so I hope it'll not be too cringeworthy. So I am trying
to create a hex-based strategy game, not quite there yet but anyways.
To achieve a hex-based game I would like to create a field made of hexes
which the user should be able to click, and receive the coordinates of
that pixel. At the moment I can produce either a field of hexes or a
mouselistener/mouseadapter but not both. The last one executed replaces
the other on the screen.
I've looked around for quite some time but the posts that I've encountered
had either dealt with changing the background color which the
mouselistener can do, because background is independent of the
mousesensorhttp://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html?
The other examples I've come by have been too advanced for me, because
they're using multiple panes, and I have not been able to comprehend
themhttp://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html.
So what I'm looking for is a way to add a mouselistener over a single
pane, displaying the hexes. Would this be possible? E.G adding the hexMap
after the mouselistener would not overwrite the mouselistener but rather
act as an addition
A single line has been created acting as a placeholder for the hexes.
The code:
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class GraphicsSetup extends JPanel{
public static final int FRAME_WIDTH = 600;
public static final int FRAME_HEIGHT= 400;
private static JFrame frame;
public static void main(String[] args){
GraphicsSetup draw = new GraphicsSetup();
}
public GraphicsSetup(){
HexMap hexMap = new HexMap();
JPanel panel = new JPanel();
frame = new JFrame("HexExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
Container pane = frame.getContentPane();
pane.setBackground(new Color(20, 100, 30));
pane.add(new MouseListener());
pane.add(new HexMap());
frame.setVisible(true);
}
public class HexMap extends JComponent{
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.blue);
g2d.drawLine(0,0, FRAME_WIDTH, FRAME_HEIGHT);
}
}
class MouseListener extends JComponent{
public MouseListener(){
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
System.out.println("Mouse Event" + me);
}
});
}
}
}
Yours Sincerely
No comments:
Post a Comment