KeyListener class - java

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.

Related

Java KeyListener does not fire?

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?

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 ;)

Single MouseListener Event to get text from JTextArea

I am creating a football draw app. I currently have 9 text areas which hold 6 different teams. I have attached a MouseListener to each text area. When you click on the text area, you see a new window with each team seperated into a group format.
I have an issue trying to get the text from the text areas. I could achieve this by adding a MouseListener to each individual text area but this violates the Don't Repeat Yourself (DRY) principle as far as I am aware.
I have included my code below:
gui.getTable1().addMouseListener(new tableListener());
gui.getTable2().addMouseListener(new tableListener());
gui.getTable3().addMouseListener(new tableListener());
gui.getTable4().addMouseListener(new tableListener());
gui.getTable5().addMouseListener(new tableListener());
gui.getTable6().addMouseListener(new tableListener());
gui.getTable7().addMouseListener(new tableListener());
gui.getTable8().addMouseListener(new tableListener());
gui.getTable9().addMouseListener(new tableListener());
public static class TableListener implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
//get text from text area and pass to new GUI
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I would like to use the TableListener private class for all my text areas instead of 9 different MouseListeners. I think this can be done in a single line but I can't think how. Can someone please help?
Attach just one instace of listener to all the textareas and use e.getSource() to get event source textarea.

JFrame close question

Say If i have two classes, in each class is a different JFrame, e.g JFrame A and JFrame B ( in seperate classes).
Now from the constructor of JFrame A I may push a button with an actionlistener attached, which will instantiate the other class, thus creating JFrame B. The problem is when JFrame B is created, both the JFrames are visible. If i close JFrame B, then JFrame A closes as well. How can i make it so only JFrame B closes?
Thanks
edit DISPOSE_ON_CLOSE does not work for me, it closes all the jframes.
some sample code:
public class classone {
public classone() {
JFrame a = new JFrame("this is A");
classtwo newFrame = new classtwo();
}
}
public class classtwo {
public classtwo() {
Jframe b = new JFrame("this is B");
b.setDefaultCloseOperation(b.DISPOSE_ON_EXIT);
}
}
please ignore any syntax errors, just for demonstration.
For the JFrame B, set the default close operation to "dispose" as shown below :
frameB.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Then closing the child windows won't shut down your entire application.
HTH ! ;-)
Do you have DISPOSE_ON_CLOSE on one frame and EXIT_ON_CLOSE on the other? If so then that would explain why your program is exiting prematurely. Ensure that all frames are set to DISPOSE_ON_CLOSE.
I got question now. Just when you create an instance of a Window tell how this object live, Review this code
...
new JFrame(){
#Override
public synchronized void addWindowListener(WindowListener l) {
// You may ask here also add windowClosing method and look at my previous post
super.addWindowListener(l);
}
}.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
....
Just DO_NOTHING_ON_CLOSE and addWindowListener in WindowClosing method show a JOptionPane.showConfirmDia and if result return no(1) then return; else system.exit(0);
its all
I see my first StackOverFlow post ,What a shame! I'm editting my post.here you are;
Until now , I realize Depending developing software approachs Swing getting older. I'm missing a technology like Microsofts XAML.
soyatec inc. has some deals using XAML with java you may have a look but "In my opinion" not successfull work.Anyway...
JFrame frame=new JFrame();
frame.addWindowListener(new WindowListener() {
#Override
public void windowClosing(WindowEvent e) {
int result= JOptionPane.showConfirmDialog(JOptionPane.getRootFrame() //or your parent swing element
, "Sure ?");
switch (result) {
case 1:
break;
default:
System.exit(0);
break;
}
}
#Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
}
);

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