Java KeyListener does not fire? - java

Normally I don't program in JAVA but for this project I need to. I got everything working except of the key listener. I want the program to react whenever a Key is pressed (doesn't matter wich one).
public class fullscreen extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
public fullscreen() {
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
}
and then the KeyListener methods:
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Key Pressed!");
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
The MouseListener methods work without any problem. What did I do wrong with the KeyListener?

Related

KeyListener on a disabled button

I have a series of buttons in my code. I have added key listeners to individual buttons to listen to keys, so that when user presses RIGHT, LEFT,UP DOWN, I can transfer focus to the next button.
Note: I know that TAB can be used
now everything works really great! but when the focus is at a disabled button. I am not able to listen to it.
Any suggestions, as to how I can go around the problem?
Please pardon me before hand for amateur coding style!
addEntry.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{calPeriod.setFocusable(true);
calPeriod.grabFocus();
}if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
getTime.setFocusable(true);
getTime.grabFocus();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
genChart.setFocusable(true);
genChart.grabFocus();
}
}
});

Java mouse listener lacking responsiveness

I made a little color selector using JPanels and mouse listeners, but for some reason the result isn't as responsive as expected and I don't know why.
in order to do so I created a modified JPanel I called ColorPanel, to add it a few properties like color and color name, built in mouse listener, background color defined when instanciated etc:
public class ColorPanel extends JPanel{
private Color color;
private String sColor;
public ColorPanel(Color color, String sColor){
this.color = color;
this.sColor = sColor;
this.setBackground(color);
this.setBorder(BorderFactory.createLineBorder(Color.white));
this.addMouseListener(new appMouseListener());
ColorSelector.panSelector.add(this);
ColorSelector.vPanel.add(this);
}
public Color getColor(){
return this.color;
}
public String getScolor(){
return this.sColor;
}
class appMouseListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
ColorSelector.select((ColorPanel)e.getSource());
}
#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
}
}
}
this is linked to another object I made meant to instanciate all the panels I need and their countainer, as well as the method to change the selected colorpanels border color and store its coulour into a global variable.
While it works, every so often I got to click several times to select a colorpanel. The program had no responsiveness problem before and that selector is the only thing behaving this way.
public static void select(ColorPanel colorPanel) {
IhmMap.SelectedColor = colorPanel.getColor();
IhmMap.SelectedScolor = colorPanel.getScolor();
for(int i = 0 ; i<vPanel.size(); i++ ){
vPanel.elementAt(i).setBorder(BorderFactory.createLineBorder(Color.white));
}
colorPanel.setBorder(BorderFactory.createLineBorder(Color.red.darker().darker()));
}
This is the method, all the panels are added to a vector upon creation, so I can manipulate them easily.
MouseClicked event only fires if you didn't move the mouse at all between pressing and releasing the mouse. That way if you press the mouse button and move the mouse slightly just by 1 pixel, the mouseClicked won't get called.
I suggest using mouseReleased or a combination of mousePressed, mouseReleased and/or mouseExited. e.g.
private boolean pressed;
#Override
public void mouseExited(MouseEvent arg0) {
pressed = false;
}
#Override
public void mousePressed(MouseEvent arg0) {
pressed = true;
}
#Override
public void mouseReleased(MouseEvent arg0) {
if (pressed) {
//your code here
}
}
That way you can press on the ColorPanel and as long as you don't leave the ColorPanel it will register a click.

Easier way to implement MouseListener in Java

I have a more general question to ask.
When I have to implement a MouseListener in my class, the compiler automatically forces me to implement every method there is in a MouseListener interface.
Like so:
MouseListener mouseLtnr = new MouseListener()
{
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
counter++;
xs.add(MouseInfo.getPointerInfo().getLocation().x - getLocationOnScreen().x);
ys.add(MouseInfo.getPointerInfo().getLocation().y - getLocationOnScreen().y);
System.out.println(xs.get(counter-1) + " , " + ys.get(counter-1));
if(flag == false)
repaint();
}
#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
}
};
More often than not, I only need one or two of those. Is there a way to implement just the one I need, or do I have to deal with wasted lines of code?
Thank you for your time.
Best,
Dauta
Use a MouseAdapter, it is a basic class which implements the MouseListener (and MosueWheelListener and MouseMotionListener) interface, but provides blank implementations of all the methods, meaning you can just override the ones you want...
MouseListener mouseLtnr = new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
counter++;
xs.add(MouseInfo.getPointerInfo().getLocation().x - getLocationOnScreen().x);
ys.add(MouseInfo.getPointerInfo().getLocation().y - getLocationOnScreen().y);
System.out.println(xs.get(counter-1) + " , " + ys.get(counter-1));
if(flag == false)
repaint();
}
}
If you dig around the docs a bit, you will find a few more classes like this as well ;)
FYI: MouseInfo.getPointerInfo() will return the mouse cursor position relative to the screen, not the component that generated the event. You can also use MouseEvent#getXOnScreen and MosueEvent#getYOnScreen or SwingUtilities#convertPointToScreen(Point, Component) depending on your needs ;)

KeyListener class

So, I'd like to create a keylistener inside my program that is applyable to all the classes in it (as when creating class as an object).
I don't know how to do it with a key(or any other) listener.
Usually it would go: class blabla extends JPanel {blablabla;}, but it doesn't work that way.
What is the way to go?
Consider creating a EventHandler class that implements KeyListener interface. Instatiate this class and pass to addKeyListener() method:
class EventHandler implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
/**
* Usage
*/
EventHandler eh = new EventHandler();
nameOfComponent.addKeyListener(eh);
KeyListener is an interface, so you should use the keyword implements instead of extends.

Window events for JFrames that are hidden/shown via setVisible?

Which kind of listener do I have to add to a JFrame to detect when it is being hidden or shown via setVisible?
I tried using a WindowListener and the windowOpened and windowClosed methods, but they only work for the first time that a window is opened (windowOpened) or, respectively, when the window is closed using the dispose method (windowClosed). That is not enough for me. I want to be notified every time the window is made visible and invisible on the screen using setVisible.
Is there a standard Swing way to achieve this, or do I need to make my own (by, say, overriding the setVisible method)?
Try a java.awt.event.ComponentListener. You can add one using this code (where window is the name of the JFrame) :
window.addComponentListener(new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
/* code run when component hidden*/
}
public void componentShown(ComponentEvent e) {
/* code run when component shown */
}
});
1- Create a class that implements ComponentListener Interface, Like the following example:
//---------------------
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
public class winlistenner implements ComponentListener {
public void componentHidden(ComponentEvent arg0) {
// TODO Auto-generated method stub
System.out.print("Hided\r\n");
}
public void componentMoved(ComponentEvent arg0) {
// TODO Auto-generated method stub
System.out.print("Moved\r\n");
}
public void componentResized(ComponentEvent arg0) {
// TODO Auto-generated method stub
System.out.print("Resized\r\n");
}
public void componentShown(ComponentEvent arg0) {
// TODO Auto-generated method stub
System.out.print("Shown\r\n");
}
}
//------------------------------------------------------------------------
2- Now create a getter for your JFrame like this:
public class JMain {
private JFrame frmNetworkshareMoon;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
public JFrame getFrmNetworkshareMoon() {
return frmNetworkshareMoon;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JMain window = new JMain();
winlistenner listenner= new winlistenner();
window.getFrmNetworkshareMoon().addComponentListener(listenner);
window.frmNetworkshareMoon.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//......
// the rest of your class code:
//...
}
3- being your main like the above example, you will set JFrame listener the listener you created, and then run the program, you will see messages coming from the listener:
Moved
Resized
Resized
Moved
Shown
Moved
Moved

Categories

Resources