Connect 4 GUI in Java (JApplet) - java

I am currently programming a Connect 4 Applet game, and i already have all the AI logic implemented. Now i need to design a simple gui so i can play with.
I have an image of the board that i want to use (a transparent png) and i want to be able to perform a move by clicking on the image (e.g on the specific column i want to play).
What is the best way of doing this? I thougt of using a class that extends JPanel,where i put all the buttons and stuff...including painting the board image. But can i put a mouse listener on an Image??

"But can i put a mouse listener on an Image??"
No, or at least, not in the context you are thinking.
You have a couple of choices depending on what you want to achieve.
The basic requirement though, is you are going to need to know exactly where on the image each click point is. This is best achieved by using an image editing program to map out the "hot spots" and then code these into your program
You could...
Use a JLabel to render the board image and attach a MouseListener to it.
The problem I would have with this is trying to figure out how to update the image with the player markers.
You could...
Use a JPanel and override it's paintComponent to render the image and player moves/markers.
You would then add a MouseListener to it and monitor the mouse clicks from there.
Regardless of which method you used, I would probably create a List of Rectangles which represented the hot spots the user can click. Each time mousePressed is called, I would walk this list and use Rectangle#contains(Point), passing the mouse click point, to determine which hot spot was clicked.
You would then to to compare this with the game model to determine if it's a valid move or not and take appropriate action as required.
Take a look at How to write a Mouse Listener and Performing custom painting for more details

Use 16(?) JToggleButton objects in a 4x4(?) GridLayout.
Knock the space & background out of the buttons as seen in the answer to Add a complex image in the panel, with buttons around it in one customized user interface.
Related: How to Use
Buttons, Check Boxes, and Radio Buttons
GridLayout
Advantages of Approach
There is no need to extend any component. We can use the 'vanilla' version of the layout, buttons and container. This is favoring composition over inheritance.
Logic of the game can be represented by changing the icons of the buttons. The GUI will update as needed.
It saves coding all the logic to detect which image was clicked. Add an ActionListener and the buttons will respond to either mouse focus/click or keyboard focus/action.

why do you wanna add mouse listener to image? if your class implements mouselistener you can tell what to do when the mouse clicked or what ever else. take a look :
public class Test extends JPanel implements MouseListener {
.
.
.
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}

Related

JMapViewer Issue [duplicate]

I am trying to add a mouse listener to a MapMarker, so that when a mouse will hover a MapMarker, I could react with an event.
I implemented the mouseListener, but I can't really add a listener.
The issue is that I did not find a way the MapMarker will addMouseListener, due to the fact that non of the hierarchy implements JPanel.
Any help appreciated
As noted here, the default JMapViewer constructor uses a DefaultMapController, "which implements map moving by pressing the right mouse button and zooming by double click or by mouse wheel." To see map coordinates, extend DefaultMapController, override mouseClicked() and use one of the viewer's getPosition() methods. You can use your controller as shown in comments at line 65 of Demo.java, r30377.
new DefaultMapController(map){
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(map.getPosition(e.getPoint()));
}
};

Using KeyListener for a Calculator in NetBeans

I have written a calculator in NetBeans and it functions perfectly. However, I have to actually click the buttons to insert numbers and am trying to remedy that with a KeyListener. I have all my numbers and function buttons set inside a JPanel named buttons. I have my display label in a JPanel named display.
I set my class to implement KeyListener and it inserted the KeyPressed, -Typed, and -Released methods; however I stuck from there. I'm not sure how to make my buttons actually listen for the KeyPressed event, and when it hears the event - activate the button. Also, my buttons are named by their number (e.g. the Zero Button is named zero, One button is one, etc.).
I've read that you actually have to implement a KeyListener somewhere by using: something.addKeyListener(something);
but I cannot seem to figure this out.
Can I get some help here? I'm new to Java and this is my first solo project. And let me know if I didn't provide enough information.
EDIT: Most of my code is NetBeans Generated and I cannot edit the initialization of the components which seems to be my problem I think?
My class declaration:
public class Calculator extends javax.swing.JFrame implements KeyListener {
//Creates new form Calculator
public Calculator() {
initComponents();
}
One of my buttonPressed actions (all identical with changes for actual number):
private void zeroActionPerformed(java.awt.event.ActionEvent evt) {
if (display.getText().length() >= 16)
{
JOptionPane.showMessageDialog(null, "Cannot Handle > 16 digits");
return;
}
else if (display.getText().equals("0"))
{
return;
}
display.setText(display.getText().concat("0"));
Main method supplied by NetBeans:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator().setVisible(true);
}
});
}
The initComponents() netbeans generated is absolutely massive (about 500 lines of code) and I cannot edit any of it. Let me know if I can supply any more helpful information.
Could there be an issue of Focus, and if so how can I resolve the issue?
Yes there is probably an issue with focus. That is why you should NOT be using a KeyListener.
Swing was designed to be used with Key Bindings. That is you create an Action that does what you want. Then this Action can be added to your JButton. It can also be bound to a KeyStroke. So you have nice reusable code.
Read the Swing tutorial on How to Use Key Bindings for more information. Key Bindings don't have the focus issue that you currently have.
I'm not sure I completely understand your question, and some code would help, but I'll take a crack, since it sounds like a problem I used to have a lot.
It sounds like the reason that your key presses aren't being recognized is that the focus is on one of the buttons. If you add keylisteners to the buttons, then you shouldn't have any problem.
In netbeans you can add keylisteners through the design screen really easily.
Here's a picture showing you how to add a keyPressed listener to a button in a jPanel.
private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {
//Check which key is pressed
//do whatever you need to do with the keypressed information
}
It is nice to be able to write out the listeners yourself, but if you are just learning, then it is also nice to get as much help as possible.
This might not be the best solution, since you would have to add the listener for each of your buttons.

Removing MouseListener() from a JLabel

I added a MouseListener to a JLabel. Now if I want to disable this MouseListener associated with the JLabel, when the label is clicked once, how can I do it.
I know there is a big way to set a boolean or int variable when the label is clicked and then call a method and remove MouseListener there, but I want to learn a compact and easy way. Is there a way to do this?
In your mouse listener:
public void mouseClicked(MouseEvent event) {
// Do stuff...
((Component) event.getSource()).removeMouseListener(this);
}
What's wrong with label.removeMouseListener(listener)? It works just fine. If you want to create listener that removes itself call label.removeMouseListener(this)

Setting the position of the cursor in java awt

I've been looking at how to programmatically set the position of the cursor. Doing some googling I found the use of the Robot class. But when I do this it calls the mouseMoved event implemented in MouseMotionListener which I don't want. Are there any other ways to set the position that wouldn't call that method?
The mouseMoved event will still fire no matter what you do, but you can overwrite it, so that it does nothing once fired.
You can overwrite the listener of the component that you are moving the mouse on, so that only that component will ignore the event but others components will trigger properly.
myComponent.addMouseMotionListener(new MouseMotionAdapter()
{
#Override
public void mouseMoved(MouseEvent e)
{
/*Do Nothing*/
}
});

Java JButton - MouseMotionListener ( MouseMoved ) MouseOver Effect

I'm trying to do the MouseOver effect like it is known in JavaScript in Java for a JButton. I added a MouseMotionListener and it worked. I did want to set 2 other Buttons visible, if my mouse touches the 1st Button. So that works perfectly.. but I don´t know how to handle if the mouse isn´t over the Button. I want to setVisible the Buttons false after the Mouse left the Button
Heres my code:
mouseover.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent arg0) {}
public void mouseMoved(MouseEvent arg0) {
del.setVisible(true);
addone.setVisible(true);
}
mouseover is the Button I want to listen to.
del is another Button wich I want to setVisible
addone also
Sry for my not really awesome english :P
Thank you !
You're looking for a MouseListener, specifically implementing mouseExited.
http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
You may want to use MouseAdapter to avoid being forced to implement all of the methods from MouseListener. MouseAdapter is simply a class that implements the mouse listening interfaces.
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
Perhaps you want to check setRolloverIcon(), setRolloverSelectedIcon() methods, instead of using MouseEvent.
Instead of using a MouseMotionListener. Use a MouseListener, this class has two methods called mouseEntered() and mouseExited() these should allow you to make the necessary changes as the mouse comes in and out of the button.
Here is a brief tutorial on MouseListeners

Categories

Resources