keyListener on jbutton not working - java

I would like to perform some action when 'Enter' key is press as soon as jbutton is clicked but it is not working, someone help
here is my code
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton.keyTyped(e);
}
key listener function
public void keyTyped(KeyEvent e) {
//action
}

You need to bind it - sample code below.
public class Test {
static JButton btnA = new JButton("A");
static JPanel jp = new JPanel();
static JFrame jf = new JFrame("test frame");
static ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent e) {
jl.setText(((JButton)e.getSource()).getText());
}
};
public static void main(String[] args) {
jf.setVisible(true);
jf.setSize(400, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp.add(btnA);
jf.add(jp);
btnA.addActionListener(action);
}
}

Related

How do i make my java program wait until there is entered a value into the textfield

Basically im trying to make a program that needs a barcode which you should enter through the GUI, it works with nextLine() since it pauses and waits for an input ,and i was wondering if there is anything like that but waiting for a input in a gui?
You can add a button to press after entering the input and listen to the button event. Check below example
public static void main(String[] args) {
JFrame frame = new JFrame("Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JTextField textField = new JTextField("enter input");
JButton button = new JButton();
button.setText("Ok");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame,
textField.getText());
}
});
panel.add(textField);
panel.add(button);
frame.add(panel);
frame.setSize(150, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
The other option is adding a document listener to your text field.
public static void main(String args[]) {
final JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
DocumentListener documentListener = new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
public void insertUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
public void removeUpdate(DocumentEvent documentEvent) {
JOptionPane.showMessageDialog(frame,
textField.getText());
}
};
textField.getDocument().addDocumentListener(documentListener);
frame.setSize(250, 150);
frame.setVisible(true);
}

set location on event doesn't work

i have the following code, where i try to make some jLabels/jComboBox visible/invisible and move the location of those that are visible on jRadioButton click.
the issue is that the location is updated only on second click.
private void SingleButtonActionPerformed(java.awt.event.ActionEvent evt) {
this.serverLabel.setVisible(true);
this.serverList.setVisible(true);
this.serverLabel.setLocation(this.hostGroupLabel.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.serverList.setLocation(this.cpuCountSpinner.getLocation().x, this.cpuCountSpinner.getLocation().y);
this.jXDatePickerStartDate.setLocation(153, jXDatePickerStartDate.getLocation().y);
this.requestedRamLabel.setVisible(false);
this.ramText.setVisible(false);
this.cpuLabel.setVisible(false);
this.cpuCountSpinner.setVisible(false);
}
I dont know why it is not working for you, mayby you are modifying somewhere else your GUI, or event is not fired at all. Here is working example. You should pase the code where you actually append the listener to the button. You did that right? It should be something like:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
singleButtonActionPerformed(e)
}
});
or Java8 variant using Lambdas
button.addActionListener(this::singleButtonActionPerformed)
but using this depends on context. It should be the object hta holds given method.
Here is working example with button and radio button (as suggested)
public class SettingLocation {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
f.setContentPane(p);
p.setLayout(new FlowLayout());
JButton b = new JButton("Click me");
b.setBounds(150, 150,100,100);
p.add(b);
JRadioButton rb=new JRadioButton("Exmaple radio");
p.add(rb);
rb.addActionListener(new ActionListener() {
Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
rb.setLocation(r.nextInt(300), r.nextInt(300));
}
});
b.addActionListener(new ActionListener() {
Random r = new Random();
#Override
public void actionPerformed(ActionEvent e) {
b.setLocation(r.nextInt(300), r.nextInt(300));
}
});
f.setVisible(true);
}
}

Setting Action Listener and changing background

I've created 3 buttons. They are each displayed twice in a JFrame. I'm having trouble changing the background of the frame. I've set ActionListeners but upon clicking, nothing is changing. May I ask for some help.
public class MyButtons extends JPanel {
public static JFrame frame;
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton()
{
Blue.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
public static void main(String[] args) {
frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
row1.setPreferredSize(new Dimension(250, 100));
row2.setPreferredSize(new Dimension(250, 100));
frame.setLayout(new GridLayout(3,2));
frame.add(row1);
frame.add(row2);
frame.pack();
frame.setVisible(true);
}
}
This code works, but probably not as you expected:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyButtons extends JPanel {
//public static JFrame frame;
// static is rarely a solution of problems in a GUI. ToDo! Change!
static JPanel ui = new JPanel(new GridLayout(2, 0, 20, 20));
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton() {
Blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
//row1.setPreferredSize(new Dimension(250, 100));
//row2.setPreferredSize(new Dimension(250, 100));
//frame.setLayout(new GridLayout(3, 2,10,10));
ui.add(row1);
ui.add(row2);
frame.add(ui);
frame.pack();
frame.setVisible(true);
}
}
N.B. Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently.

Java Smileys Replacing String with Smiley

I'm writing a Chat program. I designed a mock-up gui with smileys where when the user clicks on a smiley(jbutton) it prints it onto a textpane. I managed to add an advanced feature where when a user types in ":)" and sends it, it inserts the smiley instead of the string - using the insertIcon() method. The problem I have is that it only prints the smiley once rather than multiple times. So if I type "Hi :) My name is Jack :)" it only inserts the icon ONCE. Any suggestions?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SmileyTesterGUI extends JFrame {
JPanel main = new JPanel();
JPanel south = new JPanel();
JPanel messageCenter = new JPanel();
JPanel smileysNorth = new JPanel();
JTextField text;
JTextPane tPane;
Icon happy;
Icon smile;
Icon tongue;
Icon veryHappy;
Icon wink;
Icon laugh;
Icon sad;
Icon verySad;
Icon cry;
public SmileyTesterGUI() {
super("Smileys");
add(main);
main.setLayout(new BorderLayout());
main.add(south, BorderLayout.SOUTH);
south.setLayout(new BorderLayout());
south.add(messageCenter, BorderLayout.CENTER);
south.add(smileysNorth, BorderLayout.NORTH);
// textpane panel
tPane = new JTextPane();
JScrollPane sPane = new JScrollPane(tPane);
main.add(sPane);
tPane.setEditable(false);
// smileysPanel
smileysNorth.setLayout(new GridLayout(1, 0));
JButton smiley1 = new JButton();
JButton smiley2 = new JButton();
JButton smiley3 = new JButton();
JButton smiley4 = new JButton();
JButton smiley5 = new JButton();
JButton smiley6 = new JButton();
JButton smiley7 = new JButton();
JButton smiley8 = new JButton();
JButton smiley9 = new JButton();
smileysNorth.add(smiley1);
smileysNorth.add(smiley2);
smileysNorth.add(smiley3);
smileysNorth.add(smiley4);
smileysNorth.add(smiley5);
smileysNorth.add(smiley6);
smileysNorth.add(smiley7);
smileysNorth.add(smiley8);
smileysNorth.add(smiley9);
// set smileys(icon) to each button - pathed from personal directory
happy = new ImageIcon(getClass().getResource("smileys/Smile1.png"));
smiley1.setIcon(happy);
smile = new ImageIcon(getClass().getResource("smileys/Smile2.png"));
smiley2.setIcon(smile);
tongue = new ImageIcon(getClass().getResource("smileys/Smile3.png"));
smiley3.setIcon(tongue);
veryHappy = new ImageIcon(getClass().getResource("smileys/Smile4.png"));
smiley4.setIcon(veryHappy);
wink = new ImageIcon(getClass().getResource("smileys/Smile5.png"));
smiley5.setIcon(wink);
laugh = new ImageIcon(getClass().getResource("smileys/Smile6.png"));
smiley6.setIcon(laugh);
sad = new ImageIcon(getClass().getResource("smileys/Smile7.png"));
smiley7.setIcon(sad);
verySad = new ImageIcon(getClass().getResource("smileys/Smile8.png"));
smiley8.setIcon(verySad);
cry = new ImageIcon(getClass().getResource("smileys/Smile9.png"));
smiley9.setIcon(cry);
// smileys print on the textpane
smiley1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile1.png")));
}
});
smiley2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile2.png")));
}
});
smiley3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile3.png")));
}
});
smiley4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile4.png")));
}
});
smiley5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile5.png")));
}
});
smiley6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile6.png")));
}
});
smiley7.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile7.png")));
}
});
smiley8.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile8.png")));
}
});
smiley9.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
tPane.insertIcon(new ImageIcon(getClass().getResource(
"smileys/Smile9.png")));
}
});
// messagePanel
messageCenter.setLayout(new BorderLayout());
text = new JTextField();
JButton send = new JButton("Send");
messageCenter.add(text);
messageCenter.add(send, BorderLayout.EAST);
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
setLocation(500, 0);
setSize(600, 250);
}
public void sendMessage() {
String a = text.getText();
// tPane.setText(a);
// tPane.getText();
if (a.equals(":D")) {
tPane.insertIcon(veryHappy);
} else if (a.equals(":)")) {
tPane.insertIcon(smile);
} else if (a.equals(":(")) {
tPane.insertIcon(sad);
} else if (a.equalsIgnoreCase(":P")) {
tPane.insertIcon(tongue);
} else if (a.equals(";)")) {
tPane.insertIcon(wink);
}
text.setText(null);
text.requestFocus();
}
public static void main(String[] args) {
new SmileyTesterGUI().setVisible(true);
}
}
insertIcon() method of JTextPane uses selection (caret position in simplest case). So in your case you always replace the icon just once.
Your sendMessage() doesn't check multiple occurences of ":)" in the message. Use while loop obtaining indexes of the ":)" and for each index make it selected and then use insertIcon()

Create a shortcut in JFrame

public final class UserPage extends JFrame{
public UserPage() {
this.addKeyListener(new myclass());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000, 600);
this.setLocation(300, 60);
this.setResizable(false);
this.setVisible(true);
}
.
.
.
public class myclass extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
System.out.println("Key \"Delete\" Pressed");
}
}
}
}
But, when i press delete button, not see the "Key \"Delete\" Pressed" message!
JFrame (all Top-Level Containers) by default never to react to KeyEvents, have to use this Listener for JComponent they are to consume Focus, or is possible to flag it with setFocusable()
don't to use low_level KeyListener for Swing JComponents, if is possible then to use hight level abstraction, to use KeyBindings instead
JRootPane + KeyBindings(As #mKorbel has already said)
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
Also check out: JMenuItem#setAccelerator(...)
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UserPageTest {
public static JMenuBar makeMenuBar() {
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Test");
JMenuItem item = new JMenuItem(action);
item.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK));
menu.add(item);
bar.add(menu);
return bar;
}
public static Action action = new AbstractAction("UserPage?") {
#Override public void actionPerformed(ActionEvent e) {
System.out.println("UserPage Action");
}
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
String KEY = "UserPageAction";
f.getRootPane().getActionMap().put(KEY, action);
InputMap im = f.getRootPane().getInputMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), KEY);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setJMenuBar(makeMenuBar());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Categories

Resources