How to add key listener - java

So when I run the program it doesn't print out the variable kod. I should addKeyListener(); But I don't know where and how ?
Can someone please tell me how am I supposed to add the keyListener to my main class or where ever I am supposed to add it ???
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class YuGiOh {
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel l1 = new JLabel("LABEL");
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addKeyListener(new tipkovnica());
panel.setLayout(null);
frame.add(panel);
l1.setBounds(80,100,100,20);
panel.add(l1);
}
}
class tipkovnica extends KeyAdapter{
public void keyBinder(KeyEvent e){
int kod = e.getKeyCode();
System.out.println(kod);
}
public void keyReleased(KeyEvent e){
}
}

KeyListener() requires the component to have focus. Try adding:
frame.requestFocus();

Related

Java Swing with ActionListener [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have a problem with ActionListener. If I use an anonymous class everything works good, if the MainFrame class implements ActionListener everything works good. But if I create an extern class and implement ActionListener I get NullPointerException.
How can I fix this problem using an extern class that implement ActionListener interface?
Thanks in advance!
This is the code:
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class App {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new MainFrame("Hello world Swing");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
MainFrame code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
JTextArea textArea;
public MainFrame(String title) {
super(title);
Container c = getContentPane();
c.setLayout(new BorderLayout());
textArea = new JTextArea();
JButton button = new JButton("Click me!");
c.add(textArea, BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);
button.addActionListener(new ListenApp());
}
}
ListenApp code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class ListenApp implements ActionListener {
MainFrame frame;
#Override
public void actionPerformed(ActionEvent e) {
frame.textArea.append("Hello\n");
}
}
It's because in ListenApp the frame (field) you have isn't declared as the frame you created in your main method.
They way to make it work is to pass the frame into the listener as an argument in the listener's constructor. Take a look:
MainFrame class:
package test;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame {
private JTextArea textArea; // private fields are always recommended.
public MainFrame(String title) {
super(title);
Container c = getContentPane();
c.setLayout(new BorderLayout());
textArea = new JTextArea();
JButton button = new JButton("Click me!");
c.add(textArea, BorderLayout.CENTER);
c.add(button, BorderLayout.SOUTH);
button.addActionListener(new ListenApp(this)); //pass the frame to the listener
}
public JTextArea getTextArea() // Must have access to the textArea aswell
{
return textArea;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new MainFrame("Hello world Swing");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
ListenApp class:
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ListenApp implements ActionListener {
private MainFrame frame;
public ListenApp(MainFrame frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent arg0) {
frame.getTextArea().append("i append something");
}
}

Java KeyListener not responding

Forgive me if I'm asking too big of a question, I trying to learn to code and I think I'm missing a big detail about KeyListiner. I am trying to make a simple program that "rolls a dice" and displays a picture of a number 1 to 6 when the users presses a key. My program doesn't seem to respond to any user input.
What am I doing wrong?
Thank you for any help, I'm just trying to learn so any advice is appreciated.
public class Dice {
public static void main (String arg[]) {
new DD();
}
}
class DD extends JPanel {
DD(){
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("dice.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
addKeyListener(new Roll());
}
}
class Roll extends JFrame implements KeyListener {
public void keyPressed(KeyEvent event){}
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){
int d = event.getKeyCode();
if(d == KeyEvent.VK_UP){
int roll = (int) (Math.random()*6) + 1;
System.out.println(roll);
}
}
}
Let's take a closer look at your DD class...
class DD extends JPanel {
DD() {
JFrame frame = new JFrame();
ImageIcon icon = new ImageIcon("dice.jpg");
JLabel label = new JLabel(icon);
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
addKeyListener(new Roll());
}
}
You create an instance of JFrame, from within the constructor of the JPanel, which is a questionable act...
You create a JLabel and add it to the JFrame
You show the JFrame
You add a KeyListener to the DD JPanel
But wait a minute, DD is never attached to any visible component, how could it ever possible be capable of receiving key events?!
KeyListener will only work when the component that it's registered to is focusable AND has focus, but if it's never displayed on the screen, it could never have focus!
To start with, I'd avoid using KeyListener, it has focus related issues, and instead use the Key Bindings API
For example...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Dice {
public static void main(String[] args) {
new Dice();
}
public Dice() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DD());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
class DD extends JPanel {
DD() {
setLayout(new GridBagLayout());
JLabel label = new JLabel(" - ");
add(label);
addKeyBindingFor(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Action.roll", new DiceRollAction(label));
}
protected void addKeyBindingFor(KeyStroke keyStroke, String name, Action action) {
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(keyStroke, name);
actionMap.put(name, action);
}
public class DiceRollAction extends AbstractAction {
private JLabel label;
public DiceRollAction(JLabel label) {
this.label = label;
}
#Override
public void actionPerformed(ActionEvent e) {
int roll = (int) (Math.random() * 6) + 1;
label.setText(Integer.toString(roll));
}
}
}
}

GUI application that changes background with button

I am trying to create a Java GUI application that contains a label and button. When the button is clicked the background color of the first panel is changed. I've got the label and button but getting errors whenever I click the button. Also, I wanted the first panel to originally have a yellow background then switch to whatever color. Here's my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel;
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new BorderLayout());
biggerPanel.setBackground(Color.YELLOW);
JLabel namePanel = new JLabel("Click the button to change the background color");
biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
biggerPanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
I made a few changes to your code.
First, you must start a Swing application with a call to SwingUtilities.invokeLater.
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
Second, you use Swing components. You only extend a Swing component when you want to override a method of the Swing component.
Third, I made a action listener specifically for your JButton. That way, you don't have to check for a particular JButton string. You can create as many action listeners as you need for your GUI.
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
Finally, I changed the background color of the JButton panel.
Here's the entire ChangeDemo class.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Here is working demo based on amendments to your code, haven't had time to tidy it up but hopefully you'll get the gist of it. Problem was you hand't added Panels to the borders (north, south etc.) in order to color them. Hopefully this helps.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel = new JPanel();
private JPanel namePanel = new JPanel();
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
//JPanel biggerPanel = new JPanel();
this.biggerPanel.setLayout(new BorderLayout());
this.biggerPanel.setBackground(Color.YELLOW);
JLabel nameLabel = new JLabel("Click the button to change the background color");
namePanel.add(nameLabel);
namePanel.setBackground(Color.YELLOW);
//this.biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
changeButton.setActionCommand("Change Color");
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
this.namePanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}

Modal JFrame on top of full screened JFrame

package javaapplication1;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final JFrame frame = new JFrame();
final NewJPanel p = new NewJPanel();
frame.setTitle("Frame");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60));
JButton btn = new JButton();
btn.setText("Button");
JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFrame f = new JFrame();
JPanel p = new JPanel();
f.setSize(300, 300);
p.setBackground(Color.red);
f.add(p);
f.setLocationRelativeTo(null);
f.setAlwaysOnTop(true);
f.setVisible(true);
}
});
}
}
I wanted the f.setVisible(true); pops out inside the full screened JFrame which is set to be modal when I clicked the button. How can I do that? Because in that code, when I click the button, the f.setVisible(true); shows outside the full screen JFrame. Looking forward for your answers.
So you want something like JInternalFrame inside of your main JFrame:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JavaApplication1 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame();
final JDesktopPane desktopPane = new JDesktopPane();
frame.setTitle("Frame");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final GraphicsDevice device = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(800, 600, 32, 60));
JButton btn = new JButton();
btn.setText("Button");
JPanel panel = new JPanel();
panel.add(btn);
frame.add(panel, BorderLayout.NORTH);
frame.add(desktopPane, BorderLayout.CENTER);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame();
JPanel p = new JPanel();
p.setBackground(Color.red);
f.setSize(300, 300);
f.setResizable(true);
f.add(p);
f.setVisible(true);
desktopPane.add(f);
}
});
}
});
}
}
More about JInternalFrame you can find here

Why Java ActionListener is not working?

Folks, I intend to implement a simple button ActionListener but it appears to not work.
The java codes are attached as following.....
The program intends to respond the click action from user and change the context of the JLabel
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame implements ActionListener {
public JButton btn = new JButton("Click");
public JLabel display = new JLabel("null");
public JPanel mainPanel = new JPanel();
public Frame() {
mainPanel.add(btn);
mainPanel.add(display);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
display.setText("it works");
System.out.println("it works");
}
}
public static void main(String[] args) {
Frame testFrame = new Frame();
testFrame.pack();
testFrame.setVisible(true);
}
}
Your actionlistener (the JFrame itself) is not added with addActionListener.
You should add ActionListner to the button
public Frame(){
mainPanel.add(btn);
mainPanel.add(display);
btn.addActionListener(this);
add(mainPanel);
}

Categories

Resources