JButton breaks my Keylistener - java

JAVA USING NETBEANS
Hello stackoverflow, i have a problem i would like help with. In a nutshell, I have a mouselistener and a keylistener on a jpanel, everything works fine except when i press one of my jbuttons, then the keylistener goes AWOL. Can any1 explain the problem, is the panels focus now on the buttons instead of the keyboard, im at a lost.
Here is the code, if somethings are not reference, assume its are there the entire panel code was 500+ long so i cut quite a bit.
Thanks in advance for any help.
package tankgame;
public class TankPanel extends JPanel implements KeyListener,
MouseListener,MouseMotionListener
{
JButton back,shop, menu, health, speed, rapidfire, shootradius;
TankPanel()
{
setLayout( null );
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setFocusable(true);
shop= new JButton("SHOP");
shop.addMouseListener(this);
shop.setBounds(400,0, 80,15);
add(shop);
}
public void keyPressed(KeyEvent k)
{
char c = k.getKeyChar();
if(c=='u')
{
u++;
System.out.println(u+" = u");
}
if(c=='i')
{
i++;
System.out.println(i+" = i");
}
if( c == 'd' )
{
if(Ptank.pic==PlayerTankE)
{
if(Ptank.move==true)
{
Pbarrel.x+=Ptank.speed;
Ptank.x+=Ptank.speed;
}
}
else
{
if(Ptank.pic==PlayerTankN || Ptank.pic==PlayerTankS)
{
Ptank.x = Ptank.x - 5;
Ptank.y=Ptank.y+5;
}
Ptank.setPic(PlayerTankE);
Ptank.width=35;
Ptank.height = 23;
}
}
setFocusable(true);
repaint();
}
public void keyReleased(KeyEvent k)
{
}
public void keyTyped(KeyEvent k)
{
}
public void mouseClicked(MouseEvent e)
{
//Invoked when the mouse button has been clicked (pressed and released)
}
public void mouseEntered(MouseEvent e)
{//Invoked when the mouse enters a component.
}
public void mouseExited(MouseEvent e)
{ //Invoked when the mouse exits a component.
}
public void mousePressed(MouseEvent e)
{//Invoked when a mouse button has been pressed on a component.
if(e.getSource()==back)
{
System.out.println(456);
System.out.println(back.getLocation().x + " "+back.getLocation().y);
}
else if(e.getSource() == menu)
{
changebuttons("menu");
System.out.println(456);
System.out.println(menu.getLocation().x + " "+menu.getLocation().y);
}
else if(e.getSource() == shop)
{
changebuttons("shop");
System.out.println(456);
System.out.println(shop.getLocation().x + " "+shop.getLocation().y);
}
else if(e.getButton() == MouseEvent.BUTTON1)
{
destpoint= new Point();
destpoint.setLocation(mousex, mousey);
origin = new Point();
}
for(int i = 0; i< Ptank.rapidfire; i++)
{
if (origin.distance(destpoint) <= 100 && origin.distance(destpoint) >= 50)
{
Bullet add = new Bullet(this,destpoint);
add.getOrigin(origin);
add.setPic(PlayerBullet);
add.width=4;
add.height=4;
bulletList.add(add);
}
}
}
}
public void mouseReleased(MouseEvent e)
{//Invoked when a mouse button has been released on a component.
}
public void mouseDragged(MouseEvent e)
{//Invoked when a mouse button is pressed on a component and then dragged.
}
public void mouseMoved(MouseEvent e)
{
//Invoked when the mouse cursor has been moved onto a component but no buttons
Cursor cursor = Cursor.getDefaultCursor();
//you have a List<Polygon>, so you can use this enhanced for loop
cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
setCursor(cursor);
mousex=e.getX();
mousey=e.getY();
}
public void changebuttons(String x)
{
if(x.equals("shop"))
{
menu.setBounds(720, 0, 80, 15);
health.setBounds(0, 0, 125, 15);
speed.setBounds(150, 0, 125, 15);
shootradius.setBounds(300, 0, 200, 15);
rapidfire.setBounds(500, 0, 150, 15);
shop.setBounds(1000, 0, 150, 15);
}
}

KeyEvents are only generated on a component that has focus. When you click on the button is now has focus to key events won't be generated on the panel. You need to add:
panel.requestFocusInWindow()
in your ActionListener to give focus back to the panel.
However the better solution is to use Key Bindings as you can add bindings to a KeyStroke even when the component doesn't have focus.

Don't use a KeyListener which requires the component be focused to work. Instead consider using Key Bindings. You can find out how to use these guys at the Swing tutorial: How To Use Key Bindings. If you need more specific help, you will want to post a much smaller bit of code than you show above, code that is self-contained and will actually compile and run for us, an SSCCE.

Related

java - get a button to change color when the mouse hovers over it

So i want to make a menu for a simple java game where the buttons changes colors when the mouse hovers over them. I am not using JButton but a picture of a button that uses mouselistener to detect the click. How do i make it so MouseEntered is called when you hover over a specific area where the button is?
public void mouseEntered(MouseEvent e) {
if(e.getX() < 950 && e.getX() > 350 && e.getY() < 300 && e.getY() > 200){
menuImage2 = true;
menuImage1 = false;
}
}
This is what i have so far
This is how I did it. It also plays a sound too. You just use flags. Notice, I used mouseMoved rather than mouseEntered.
Class MouseInput
#Override
public void mouseMoved(MouseEvent e) {
int x=e.getX();
int y=e.getY();
if (x>100&&x<200&&y>150&&y<200) {
if (mouseInStart==false) { <---- if this line is true, means mouse entered for first time.
Sound.playSound(soundEnum.BUTTONHOVER);
}
mouseInStart=true;
} else {
mouseInStart=false;
}
}
public boolean mouseInStart() { <--use this in your update method
return mouseInStart;
}
And in my other class (Class Menu)
public void render(Graphics2D g) {
....
....
gradient = new GradientPaint(100, 150, setStartColor(), 200, 200, Color.gray);
g.setPaint(gradient);
g.fill(startButton);
}
public Color setStartColor() {
if (mouseInStart) {
return Color.red;
} else {
return Color.white;
}
}
public void update() { <--- and this is to keep checking if your mouse is in start. This is part of the giant game loop.
mouseInStart=mouseInput.mouseInStart();
mouseInLoad=mouseInput.mouseInLoad();
mouseInQuit=mouseInput.mouseInQuit();
}

OpenImaj - Using a MouseListener with JFrame

I'm attempting to add mouse listening capabilities to a JFrame that displays an MBFImage and the mouse events do absolutely nothing. I'm not sure if the events are not firing or if they are and not being caught because I am doing something wrong...
The image shows up in the JFrame just fine, however moving the mouse around over the image, clicking, moving, dragging, etc. does not result in any activity.
NOTE 1 I've discovered that if I add the mouselistener to a JPanel and then (in this specific order) draw the image and then add the the JPanel to the JFrame, that the mouse listener catches the events, but ONLY listens outside of the image. It draws a minimum size window which I need to resize. Any mouse movement over the image does not seem to fire / catch any events.
NOTE 2 If I add the panel to the JFrame and then draw the image, the window size is just fine, however the mouse listener no longer work.
Can anyone shed any light?
Here is the relevant portion of my code:
private JFrame displayImage(final MyAppImage image, final MyAppImage.DetectLevel level, String title) {
MBFImage mbfImg = image.drawDetections(level); //draws face detection boxes
JFrame imgFrame = new JFrame(title);
DisplayUtilities.display(mbfImg, imgFrame);
imgFrame.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
#Override
public void mouseExited(MouseEvent e) {
}
});
imgFrame.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("hello");
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("here");
if (level == MyAppImage.DetectLevel.filtered) {
if (image.checkPoints(e.getX(), e.getY(), level) != null) {
System.out.println("YES");
}
else {
System.out.println("NO!");
}
}
else {
System.out.println("Huh?");
}
}
});
return imgFrame;
}
Exactly what #MadProgrammer commented - when you call DisplayUtilities.display(mbfImg, imgFrame); it creates an ImageComponent inside your JFrame that is itself a MouseListener.
You should be able to add a MouseListener to the ImageComponent directly however.

JLabel can't keep up with mouse

I have a small program, that creates a something, that could be considered a joystick. Everything works, but there is a glitch, I can't work out how to fix. If mouse moves too fast, the JLabel that I'm dragging around, sticks, as mouse has moved outside of the drawn box. I could increase the size of Jlabel, but then the "O" is offset too much from mouse. (I'd rather even decrease the size, but with this implementation, maximum mouse speed is too low).
Any ideas how to fix this?
This is the whole code, btw, anyone can go ahead and compile, to see what is the problem exactly, when mouse moves too fast.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainClass implements ActionListener, MouseListener, MouseMotionListener
{
int labelSize = 20;
int screenOffsetX = 58;
int screenOffsetY = 130;
JFrame frame;
JLabel xAxis;
JLabel move;
JLabel drag;
JLabel yAxis;
JLabel xAxisDrag;
JLabel yAxisDrag;
JLabel radio;
JLayeredPane panel;
Robot rob;
public static void main(String[] args)
{
new MainClass();
}
public MainClass()
{
frame = new JFrame("app");
frame.setLayout(null);
frame.setBounds(20, 20, 400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
move = new JLabel("Movement");
move.setBounds(150, 0, 100, 15);
frame.add(move);
xAxis = new JLabel("X");
xAxis.setBounds(100, 20, 50, 15);
frame.add(xAxis);
yAxis = new JLabel("Y");
yAxis.setBounds(200, 20, 50, 15);
frame.add(yAxis);
drag = new JLabel("Dragging");
drag.setBounds(150, 40, 100, 15);
frame.add(drag);
xAxisDrag = new JLabel("X");
xAxisDrag.setBounds(100, 60, 50, 15);
frame.add(xAxisDrag);
yAxisDrag = new JLabel("Y");
yAxisDrag.setBounds(200, 60, 50, 15);
frame.add(yAxisDrag);
radio = new JLabel("O");
radio.setBounds(0, 0, labelSize, labelSize);
radio.setOpaque(false);
radio.setEnabled(false);
panel = new JLayeredPane();
panel.setBounds(50, 100, 257, 257);
panel.setLayout(null);
panel.setBackground(new Color((float)1.0,(float)1.0,(float)1.0));
panel.setOpaque(true);
panel.add(radio);
radio.setLocation(128, 128);
frame.add(panel);
panel.addMouseMotionListener(this);
panel.addMouseListener(this);
frame.revalidate();
frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {}
#Override
public void mouseDragged(MouseEvent e)
{
if(!(e.getPoint().x<0 || e.getPoint().y<0 || e.getPoint().x>257 || e.getPoint().y>257))
{
xAxis.setText("X: "+((e.getPoint().x/4)-32));
yAxis.setText("Y: "+((e.getPoint().y/4)-32));
}
if(e.getPoint().x<0 || e.getPoint().y<0 || e.getPoint().x>257 || e.getPoint().y>257)
{ //Neļauj iziet ārpus paneļa;
try
{
rob = new Robot();
if(e.getPoint().x<0)
rob.mouseMove((screenOffsetX+frame.getX()), (e.getPoint().y+screenOffsetY+frame.getY()));
if(e.getPoint().y<0)
rob.mouseMove((e.getPoint().x+screenOffsetX+frame.getX()), (screenOffsetY+frame.getY()));
if(e.getPoint().x>257)
rob.mouseMove((257+screenOffsetX+frame.getX()), (e.getPoint().y+screenOffsetY+frame.getY()));
if(e.getPoint().y>257)
rob.mouseMove((e.getPoint().x+screenOffsetX+frame.getX()), (257+screenOffsetY+frame.getY()));
}
catch (AWTException e1)
{
e1.printStackTrace();
}
}
if( (e.getPoint().x>=radio.getX() && e.getPoint().x<=radio.getX()+labelSize) &&
(e.getPoint().y>=radio.getY() && e.getPoint().y<=radio.getY()+labelSize)
)
{ //Ja kursors ir uz JLabel, tad pārvieto;
xAxisDrag.setText("X: "+((e.getPoint().x/4)-32));
yAxisDrag.setText("Y: "+((e.getPoint().y/4)-32));
radio.setBounds(e.getPoint().x-(labelSize/2), e.getPoint().y-(labelSize/2), labelSize, labelSize);
}
}
#Override
public void mouseMoved(MouseEvent e)
{
xAxis.setText("X: "+((e.getPoint().x/4)-32));
yAxis.setText("Y: "+((e.getPoint().y/4)-32));
}
#Override
public void mouseClicked(MouseEvent arg0) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e)
{
radio.setLocation(124, 124);
xAxisDrag.setText("X: "+0);
yAxisDrag.setText("Y: "+0);
}
}
Replace
if( (e.getPoint().x>=radio.getX() && e.getPoint().x<=radio.getX()+labelSize) &&
(e.getPoint().y>=radio.getY() && e.getPoint().y<=radio.getY()+labelSize)
)
{ //Ja kursors ir uz JLabel, tad pārvieto;
xAxisDrag.setText("X: "+((e.getPoint().x/4)-32));
yAxisDrag.setText("Y: "+((e.getPoint().y/4)-32));
radio.setBounds(e.getPoint().x-(labelSize/2), e.getPoint().y-(labelSize/2), labelSize, labelSize);
}
by:
if( (e.getPoint().x>=radio.getX() && e.getPoint().x<=radio.getX()+labelSize) &&
(e.getPoint().y>=radio.getY() && e.getPoint().y<=radio.getY()+labelSize)
)
{
//Has the mouse been clicked inside the radio before grabbing started ?
if(grab==0) //if it is the first iteration of the function mousedragged
grab=2; //proceed to "grab"
}
if(grab==2 && (e.getPoint().x>=0 && e.getPoint().x<panel.getWidth()) &&
(e.getPoint().y>=0 && e.getPoint().y<panel.getHeight())
)
{ //Ja kursors ir uz JLabel, tad pārvieto;
System.out.println(radio.getX()+" "+radio.getY());
xAxisDrag.setText("X: "+((e.getPoint().x/4)-32));
yAxisDrag.setText("Y: "+((e.getPoint().y/4)-32));
radio.setBounds(e.getPoint().x-(labelSize/2), e.getPoint().y-(labelSize/2), labelSize, labelSize);
}
if(grab!=2) // if grabbing is not started
grab=1; // first iteration is over
Update MouseReleased function to:
#Override
public void mouseReleased(MouseEvent e)
{
//this a new line
//grabbing is over
grab=0; // go back to idle state
radio.setLocation(124, 124);
xAxisDrag.setText("X: "+0);
yAxisDrag.setText("Y: "+0);
}
Finally , add a new field called grab to your class MainClass:
private int grab=0; //idle state
The meaning of grab:
1. grab=0 => It is the first time that the function MouseDragged is executed and "grabbing" is not started yet. In fact when you drag the mouse this function is iterated like an infinite loop until you release the mouse. So it is important to know when it has started.
2. grab=1 => Iteration has started but there is no "grabbing"
3. grab=2 => "grabbing" has started. You can notice the condition grab==0 before the affectation. In fact I tried to avoid the case when the mouse is dragged from somewhere else and goes through "radio" and then the radio is "grabbed". That's why I checked that it is the first iteration. In this case we have grab=1 => the radio is not grabbed

How do I click a JLabel using MouseListener?

I am trying to make this program for minecraft, and now im just getting started. I want that if you click a label, it will check what label is it and will do something.
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
System.out.println(me.getX()+", "+me.getY()+".");
Object source = me.getSource();
int intx = me.getX();
int inty = me.getY();
if(me.getX()>=1 && me.getY()>=1 && me.getX()<=70 && me.getY()<=45){
permissionsframe.setLocation(810,250);
System.out.println(p1p.length);
permissionsframe.pack();
permissionsframe.setSize(200, 200);
permissionsframe.setVisible(true);
JLabel playerperms = new JLabel("Player "+p1s+" has "+p1p.length+" permissions.");
playerperms.setBounds(1, 1, 150, 150);
permissionsframe.add(playerperms);
System.out.println("You chose "+player1.getText()+".");
}
else{
System.out.println("You did not click any label.");
}
}
});
This selection area is adapted to the name I have now - NonameSL. But if the name will be longer or shorter, the selection area will obviuosly be different...
Is there a way to get the excact label? I tried if(source.equals(player1))(Player 1 is the label) but I placed the label in 1, 1 and I have to click the excact point that I defined the label in, X=1, Y=1. How can I make a mouse listener listen to a label?
There is no need to check if the mouse coordinates are inside your JLabel.
You can bind a Listener to every JLabel an process the click/press event in your MyMouseListener.class
To do so:
You have to add the MouseListener to every JLabel:
MyMouseListener myMouseListener = new MyMouseListener();
label01.setName("name01");
label01.addMouseListener(myMouseListener);
label02.setName("name02");
label02.addMouseListener(myMouseListener);
To identify the JLabel you could do something like this:
class MyMouseListener extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
JLabel l = (JLabel) e.getSource();
if(l.getName().equals("name01"))
doSomething01();
else if(l.getName().equals("name02"))
doSomething02();
}
}
The correct way to do this is to use the .getComponent() method instead of the .getSource() since this is MouseEvent which is something different than ActionEvent.
Implement the Listener to your class:
public class Main implements MouseListener {
public static void main(String[] args) {
//setup JFrame and some label and then
label.addMouseListener(this);
}
#Override
public void mousePressed(MouseEvent e) {
if (e.getComponent().equals(label)) {
System.out.println("clicked");
}
}
//the other orderride methods..

Java: Problem using setText() method with Button

I'm new to java and I'm trying to swap out the text on a Button I've created. The code for my main class is as follows:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class TeamProject extends Applet implements ActionListener, MouseListener
{
char[][] charValues = new char[10][10];
Table aTable;
boolean allowUserInput = false;
Button BtnStart;
Button randomChangeBtn;
boolean guessMode;
private AudioClip[] sounds = new AudioClip[5];
private int counter = 0;
//JSObject jso;
public void init()
{
//setup buttons
BtnStart = new Button("add row/column");
BtnStart.addActionListener((ActionListener)this); //cast
randomChangeBtn = new Button("change one value");
randomChangeBtn.addActionListener((ActionListener)this);
//add button
this.add(BtnStart);
//add image to Image objects
Image imgO = getImage(getCodeBase(), "images/not.gif");
Image imgX= getImage(getCodeBase(), "images/cross.gif");
//setup table
aTable = new Table(100, 100, 75, 55, 5, 5, imgX, imgO);
//setBackground(Color.LIGHT_GRAY);
super.resize(700, 700);
//add mouse listener
addMouseListener(this);
//initially guessMode will be false
guessMode = false;
//to talk to javascript
//jso = JSObject.getWindow(this);
sounds[0] = getAudioClip (getCodeBase(), "images/buzzthruloud.wav");
sounds[1] = getAudioClip (getCodeBase(), "images/inconceivable4.wav");
sounds[2] = getAudioClip (getCodeBase(), "images/foghorn.wav");
sounds[3] = getAudioClip (getCodeBase(), "images/waiting.wav");
sounds[4] = getAudioClip (getCodeBase(), "images/whistldn.wav");
}
public void paint(Graphics g)
{
g.setColor(Color.black);
aTable.draw(g);
}
//Mouse listener methods
public void mousePressed (MouseEvent e)
{
if(!guessMode){
if ((allowUserInput)){
aTable.swapSquareValue(e.getX(), e.getY());
repaint();
}
}
else{
System.out.println("guessed row = " + e.getY() + " guessed col = " + e.getX());
if(aTable.checkGuess(e.getX(), e.getY())){
int n = JOptionPane.showConfirmDialog(null, "Excellent!! Would you like to progress to next level",
"Correct!!!", JOptionPane.YES_NO_OPTION);
if (n == JOpionPane.YES_OPTION) {
}
else{
JOptionPane.showMessageDialog(null, "Nope", "alert", JOptionPane.INFORMATION_MESSAGE);
sounds[counter].play();
}
//repaint();
}
}
public void mouseClicked (MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
//Button action listener
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == BtnStart) {
aTable.addRow();
aTable.addColumn();
BtnStart.setText("Roseindia.net");
//this.remove(BtnStart);
//this.add(randomChangeBtn);
super.resize(700, 700);
repaint();
}
else if (e.getSource() == randomChangeBtn) {
aTable.randomChangeFunc();
repaint();
guessMode = true;
}
allowUserInput = true;
System.out.println(aTable.toString());
}
}
I'm trying to change to text in my actionPerformed(ActionEvent e) method. Like I said, I'm new, so please be gentle. Thanks :)
You are using java.awt.Button. There is no setText() method in the java.awt.Button. You may use setLabel(String) instead.
And you do not have to import java.lang.* either since the java.lang package is available to all your Java programs by default.
If you change the line:
Button BtnStart;
to
JButton BtnStart;
and
BtnStart = new Button("add row/column");
to
BtnStart = new JButton("add row/column");
then you will be using the Swing Button and you will be able to call setText();
The first thing you need to know is are you trying to create an Applet using AWT or Swing components. You import the Swing classes but are using AWT components. Most people these days use Swing.
In Swing your would never override the paint() method of the Applet. You would start by extending JApplet, then you would simply add components to the content pane of the applet. If you need to do custom painting then you do that by overriding the paintComponent() method of a JComponent or JPanel.
Start by reading the Swing tutorial for working examples of using applets.
As you said that you want to swap the text then you should use the setLabel() method instead of setText, but for changing the text of a Label then you can use the setText() method.

Categories

Resources