KeyListener not reacting - java

Im trying to use a KeyListener to do something when the button m is pressed, it needs to add an image to a JPanel, however it doesn't do anything :/
I use :
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()==('m')){
panel.add(mario);
Thread marioS = new AePlayWave("sm64itsamemario.wav");
marioS.start();
}
}
});
Edit:
The answer is to set the focus to the panel before trying to invoke the listener :)
so I added a mouselistener that sets the focus to the panel on click :
panel.addMouseListener( new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
panel.requestFocusInWindow();
});

Related

MouseEvents are Captured but not KeyEvents Java JComponant

I'm working on an old game project called Lemmings, and the Principle Game Panel is working well and receiving the MouseEvents but not the KeyEvents, which is not very logic for me, so I copied down the Code of this file for you guys to see whats going on.
The GamePanel class extends JComponent SWING class
public class GameFrame {
private class GamePanel extends JComponent {
GamePanel(Dimension dim) {
setPreferredSize(dim);
//first version of the question was with the keyListner
/*addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.println(e.getKeyCode());
//nothing show up
}
});*/
//I tried using this, but it didn't work
//getInputMap().put(KeyStroke.getKeyStroke("A"), "action");
// this works cause we use the right inputMap not the one by default
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("A"), "action");
getActionMap().put("action",new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("A is pressed");
//now it works
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println(e.getPoint());
}
});
setVisible(true);
}
}
private JFrame window;
private GamePanel panel;
public GameFrame() {
window = new JFrame("Test");
window.setLocationRelativeTo(null);
panel = new GamePanel(new Dimension(400, 400));
window.setContentPane(panel);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public static void main(String[] args) {
new GameFrame();
}
}
UPDATE WITH SOLUTION
I learned that JComponants are not focusable and so it doesn't receive KeyEvents so we have to use the Key Bindings method
I found out that every JComponent has three inputMaps referred to by WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT and we have to make sure that we are using the right one for our work
for more informations look on How to use key Bindings and check the methods getInputMap() and getInputMap(int)
Key events are only dispatch to a focusable component.
By default a JPanel is not focusable so it does not receive key events.
If you are attempting to invoke some kind of Action based on a KeyEvent then you should be using Key Bindings, not a KeyListener. A key binding will allow you to listen for a KeyStroke even if the component doesn't have focus.
Read the section from the Swing tutorial on How to Use Key Bindings for more information and working examples.
the problem can be solved simply by adding a KeyListener to the JFrame in case we don't need to create Actions and stuff
this solution can only be possible if there are no other components focusable.
in the file GameFrame.java
in the function void init();
add
window.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed (KeyEvent e) {
super.keyPressed(e);
System.out.println("test "+e.getKeyChar());
}
});

How to use jbutton to make an jlabel to appear and disappear right away after releasing the click in JAVA

As the title says, I would like to know the syntax for that
I am making a first person boxing game when you click the button it punches the enemy but after releasing it, the image of the punch disappears right away.
the concept of the game is how many click the user can make in a certain period of time
I don't have a code to show because its blank inside the button
Start with this:
JButton btnPunch = new JButton("");
btnPunch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnPunch.setVisible(btnPunch.isVisible() ? false : true);
}
});
If you want an action to be done On Release use:
addMouseListener(new
MouseAdapter() {
public void mouseReleased(MouseEvent e)
{ // TODO: add your code here
} });

JRootpane - setting glasspane to visible doesnt intercept mouse events

I have a JFrame and a JPanel hierarchy inside it, i want to implement an inner panel that i can make it look "disabled"(while other panels dont change), that is, to cover it by a semi transparent gray layer and intercept all mouse and perhaps even keyboard events that are dispatched to this panel. ive been searching for a solution and didnt really find a good one yet.
The closest i got to a solution was when i used JRootPane, whenever i want it disabled i make its glasspane visible. the glasspane had been set to be opaque and with semi transparent background.
A simple example of my attempt :
public class Test extends JFrame {
private final JPanel jPanel;
public Test() {
jPanel = new JPanel();
final JButton jButton = new JButton("Hidden");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("hidden is clicked!");
}
});
final JRootPane jRootPane = new JRootPane();
jPanel.add(jRootPane);
final JPanel glassPane = new JPanel();
final JButton jButton2 = new JButton();
jButton2.addActionListener(new ActionListener() {
private boolean visible = true;
#Override
public void actionPerformed(ActionEvent e) {
glassPane.setVisible(visible = !visible);
}
});
jPanel.add(jButton2);
jRootPane.getContentPane().add(new JScrollPane(jButton));
glassPane.setBackground(new Color(0.5f, 0.5f, 0.5f, 0.2f));
glassPane.setOpaque(true);
jRootPane.setGlassPane(glassPane);
glassPane.setVisible(true);
getContentPane().add(jPanel);
}
public static void main(String[] strings) {
final Test test = new Test();
test.pack();
test.setVisible(true);
}
}
But the problem is that even when the glass is visible on top of the content, it doesnt intercepts events from getting to the content as it should, as documented here.
In your test class your glasspane doesn't intercept events, because you didn't tell it to intercept events (intercepting events is not a default behavior).
In the documentation link, it says
The glass pane
The glass pane is useful when you want to be able to catch events or paint over an area that already contains one or more components. For example, you can deactivate mouse events for a multi-component region by having the glass pane intercept the events. Or you can display an image over multiple components using the glass pane.
You can intercept Mouse Events this way:
glassPane.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
e.consume();
}
#Override
public void mousePressed(MouseEvent e)
{
e.consume();
}
});
You can intercept KeyBoard Events this way:
glassPane.setFocusable(true);
glassPane.addKeyListener(new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
e.consume();
}
#Override
public void keyReleased(KeyEvent e)
{
e.consume();
}
#Override
public void keyPressed(KeyEvent e)
{
e.consume();
}
});
Note: The JPanel has to be focasable to intercept the keyboard events.

ChangeListener JButton Issue

I am trying to create buttons that change the color of an object when they are pressed. However the object changes color whenever my mouse merely hovers over the button. Am I using the wrong listener? I'm not sure where I'm going wrong. Thanks in advance.
blue.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
object.setColor(color.blue);
objectIcon.repaint();
}
}
);
Try to use an ActionListener on the button.
E.g.
blue.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
object.setColor(color.blue);
objectIcon.repaint();
}
});

java swing events

I want when I enter a button, text to appear in the console. How can I combine the methods there is my comfusing, can someone explain and give example.
Try
JButton button = new JButton("Button1");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button1 was Clicked!");
}
});
// add button to a container
Use a MouseListener. For example:
JComponent button = new JButton();
component.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered the button");
}
});
MouseAdapter is a special MouseListener that has default empty implementations of all the other methods that the MouseListener provides, so you don't have to override them. You may want to look at the Javadoc for MouseAdapter, MouseListener, and MouseEvent.
Add an ActionListener to the button. In the actionPerformed() method print text on the console or whatever else you want.

Categories

Resources