I am attempting a very simple form designed to take user input into a JTextField and show that same input via a pop up dialog.
I can hardcode the JTextField to have a preset number using setText(). If I do this, my program works flawlessly.
However, when I leave the field blank and try getText() to show the text in the pop up dialog, I either get an empty pop up frame, or I get an 'empty string' exception (I am attempting to parse String to Double.)
package buttontest;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import javax.swing.*;
import java.awt.event.ActionEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame
{
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame()
{
setTitle("SunStream Loan Calculator v2.0");
setSize(900,900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel,BorderLayout.CENTER);
}
public JTextField loanAmt;
class ButtonPanel extends JPanel implements ActionListener
{
private Component frame;
public ButtonPanel()
{
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(frame, bf.loanAmt.getText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
Any help would be greatly appreciated. I am researching using a KeyListener or KeyEvent but I don't quite understand it well enough.
You're creating a "shadow" ButtonFrame variable inside of the b2's ActionListener. Yes the bf variable refers to a ButtonFrame object which is of the same class as the displayed ButtonFrame object, but it refers to a completely distinct and non-visualized object. The key to a solution is to get the text from the ButtonFrame object that is actually displayed, and this can be obtained from within an inner class via the ButtonFrame.this construct:
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! note use of ButtonFrame.this:
JOptionPane.showMessageDialog(frame, ButtonFrame.this.loanAmt.getText());
}
}
});
Next consider using public getters rather than accessing fields such as the JTextField directly. This reduces the chances of the code causing side effects, such as changing the properties of the JTextField object inadvertently.
For instance (changes denoted by //!! comment):
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class ButtonFrame extends JFrame {
private JTextField loanAmt; // !! Make field private
#SuppressWarnings("LeakingThisInConstructor")
public ButtonFrame() {
setTitle("SunStream Loan Calculator v2.0");
setSize(900, 900);
ButtonPanel panel = new ButtonPanel();
panel.add(new JLabel("Enter your loan amount:"));
loanAmt = new JTextField(40);
panel.add(loanAmt);
add(panel, BorderLayout.CENTER);
}
// !! create a public method to get JTextField's text
// !! without exposing the JTextField itself.
public String getLoanAmtText() {
return loanAmt.getText();
}
class ButtonPanel extends JPanel implements ActionListener {
private Component frame;
public ButtonPanel() {
final JButton b2 = new JButton("Calculate");
add(b2, BorderLayout.SOUTH);
b2.setActionCommand("calculate");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// !! ButtonFrame bf = new ButtonFrame();
if ("calculate".equals(e.getActionCommand())) {
//!! call public method on ButtonFrame object
JOptionPane.showMessageDialog(frame,
ButtonFrame.this.getLoanAmtText());
}
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
The only way you can access your loanAmt is through ButtonPanel itself. Because you add loanAmt to this button right ?
So, if you want access loanAmt. You must get all component on this button panel. This is my psudeo code howto accessing your loanAmt from ButtonPanel class.
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonFrame bf = new ButtonFrame();
if("calculate".equals(e.getActionCommand())) {
// Get all component
java.awt.Component[] componentList = this.getComponents();
JTextField txtField;
String value;
for (int i = 0; i < componentList.length; i++) {
if (componentList[i].getClass().getName().equals("javax.swing.JTextField")) {
txtField = (JTextField) componentList[i];
value = textField.getText();
}
}
if (value != null) JOptionPane.showMessageDialog(frame, value);
}
}
});
Related
My question is
If I have a Jpanel having some JtextField and ComboBox. Another JPanel containing Buttons like Save, Update, Clear, Exit.
both the JPanel are added into JFrame and by the BoarderLayout.
If I write something in text field and press save button it will save the data into database. I know the connection code to database.
Problem is the connection between the Text Panel and Button Panel. If I made the JTextField public and JButtons Public I can access them in JFrame and Implements Listners to save data into Database, but I guess its not right practice.
Kindly guide me to the how to do it correctly.
Here is the Test Code.
Buttons Panel:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Buttons extends JPanel{
JButton btnSave, btnUpdate, btnClear, btnExit;
public Buttons(){
btnSave = new JButton("Save");
btnUpdate = new JButton("Update");
btnClear = new JButton("Clear");
btnExit = new JButton("Exit");
setLayout(new FlowLayout());
add(btnSave);
add(btnUpdate);
add(btnClear);
add(btnExit);
setSize(100,100);
}
}
TextPanel
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* #author Aqeel
*/
public class textPanel extends JPanel{
JLabel ID , Name;
JTextField txtID, txtName;
GridBagConstraints gridBagConstraints;
public textPanel(){
ID = new JLabel("ID:");
Name = new JLabel("Name:");
txtID = new JTextField(10);
txtName = new JTextField(10);
setLayout(new GridBagLayout());
add(ID, new GridBagConstraints());
add(txtID, new GridBagConstraints());
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
add(Name, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
add(txtName, gridBagConstraints);
setSize(300,200);
}
}
Jframe
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.UnsupportedLookAndFeelException;
import org.openide.util.Exceptions;
/**
*
* #author Aqeel
*/
public class Jframe extends JFrame
{
textPanel textpanel;
Buttons buttons;
public Jframe() {
textpanel = new textPanel();
buttons = new Buttons();
setLayout(new BorderLayout());
add(textpanel, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
setSize(400, 200);
buttons.btnSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
String ID = textpanel.txtID.getText();
String Name = textpanel.txtName.getText();
System.out.println(ID);
System.out.println(Name);
}
});
buttons.btnExit.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String args[])
throws ClassNotFoundException, InstantiationException, UnsupportedLookAndFeelException
{
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()
) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (IllegalAccessException ex) {
Exceptions.printStackTrace(ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Jframe().setVisible(true);
}
});
}
}
It's a good practice to isolate the components used in a specific implementation. You can focus on the role of each JPanel instead.
The TextPanel has to role of receiving the text input for Id and Name and the Buttons JPanel has the role of triggering specific actions.
A simple way to accomplish this would be to, instead of accessing directly the JButton and JTextField components (either making them public or by getters), create a getter in TextPanel class that returns a String for id and another String for name.
public class textPanel extends JPanel{
JLabel ID , Name;
JTextField txtID, txtName;
...
public String getId()
{
return txtID.getText();
}
public String getName()
{
return txtName.getText();
}
}
For the Buttons class, create an interface with methodos for each action.
public class Buttons extends JPanel{
private JButton btnSave, btnUpdate, btnClear, btnExit;
private ButtonsActions actionsListener;
public Buttons(ButtonsActions actionsListener){
this.actionsListener = actionsListener;
btnSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
actionsListener.onSave();
}
});
...
}
public interface ButtonsActions {
public void onSave();
public void onUpdate();
public void onClear();
public void onExit();
}
}
The Jframe class would then be able to implement this interface and react to the actions when a button is clicked.
One of the reasons for isolating the implementation from each panel is that, let's say you later change the Buttons panel to have a JRadioButton listing all the action options and one apply button to trigger the selected action. Or if you change the TextPanel to offer o JComboBox instead of a simple JTextField. In any of those cases you would have to change all the places in your code that uses the Buttons or TextPanel classes to work with the new screen design.
use a methods to access or to modify (setters and getters ) attributes
as an exemple puts this method in Buttons class :
public JButton getbtnSave()
{
return this.btnSave;
}
this code is used for getting the btnSave with private access modifier.
and also use a method to get txtID (place this in the textPanel class)
public JTextField getTxtID()
{
return this.txtID;
}
public JTextField getTxtName()
{
return this.txtName;
}
so the code in the the JFrame will be
buttons.btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String ID = textpanel.getTxtID().getText();
String Name = textpanel.getTxtName().getText();
System.out.println(ID);
System.out.println(Name);
}
});
To be short, I create a class Something witch have a function with a JFrame where I have a label and a button on it. On the button I have an addActionListener(new changeLabel()).
I did class changeLabel in the src package for the listener but when I start the application and I click the button throw an NullPointerException on the changeLabel at
nameLabel.setText("Name changed");
line. I want to mention that if I create this listener class in Something class, work perfectly.
I don't know why throw null exception because the label is initialized firstly and after that, the button just want to change the text.
I tryed to make a getFunction, to call that label, I tryed with object Something, with object changeLabel etc... but doesn't work.
Here is some code
package trying;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
public class Something {
JFrame frame;
JLabel changeName;
JButton button;
public void gui(){
frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//is just an example
changeName = new JLabel("Stefan");
//is just an example
button = new JButton("Change");
button.addActionListener(new changeLabel());
frame.getContentPane().add(changeName, BorderLayout.NORTH);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String args[]){
new Something().gui();
}
}
The listener class
package trying;
import java.awt.event.*;
public class changeLabel extends Something implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
changeName.setText("Andrei");
}
}
How can I solve this problem?
The problem is that because the changeLabel class extends Something, it will contain it's own changeName variable which is not initialized == null.
You can:
make the changeLabel implementation private class of Something (good practice) or
pass the JLabel to its constructor.
In both ways changeLabel should not extend Something.
Code Sample #1:
public class Something {
JFrame frame;
JLabel changeName;
JButton button;
public void gui(){
frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//is just an example
changeName = new JLabel("Stefan");
//is just an example
frame.getContentPane().add(changeName, BorderLayout.NORTH);
button = new JButton("Change");
button.addActionListener(new changeLabel());
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String args[]){
new Something().gui();
}
class changeLabel implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
changeName.setText("Andrei");
}
}
}
Code Sample #2:
public class Something {
...
public void gui() {
...
button.addActionListener(new changeLabel(changeName));
}
}
public class changeLabel implements ActionListener {
private final JLabel label;
public changeLabel(JLabel label) {
this.label = label;
}
#Override
public void actionPerformed(ActionEvent e) {
label.setText("Andrei");
}
}
For one reason getText() returns null.For example:
somebody:hi!
appears as
null:hi!
I have a button which you have to press in order to change the name,but it still returns null as if nothing is written in the JTextField.If I dont' put the button and just use:
username=getText();
it appears as :
:hi!
Here is my code(yes I agree the layout is awful,but currently I am trying just to make it work):
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TextClient extends JFrame{
public JPanel mypanel=new JPanel(new GridBagLayout());
public static JButton send=new JButton("Send");
public static JButton changename=new JButton("Change name");
public static JTextField textf=new JTextField(10);
public static JTextField textname=new JTextField(10);
public static JLabel username=new JLabel("Name:");
public static JTextArea texta=new JTextArea(20,20);
public static JScrollPane jsp=new JScrollPane(texta);
public String user;
public TextClient() throws IOException
{
add(mypanel);
GridBagConstraints c1=new GridBagConstraints();
c1.anchor=GridBagConstraints.SOUTH;
c1.gridx=3;
c1.gridy=1;
mypanel.add(textf,c1);
GridBagConstraints c2=new GridBagConstraints();
c2.gridx=2;
c2.gridy=2;
mypanel.add(jsp,c2);
GridBagConstraints c3=new GridBagConstraints();
c3.gridx=2;
c3.gridy=0;
mypanel.add(send,c3);
GridBagConstraints c4=new GridBagConstraints();
c4.gridx=0;
c4.gridy=0;
mypanel.add(username,c4);
GridBagConstraints c5=new GridBagConstraints();
c5.gridx=1;
c5.gridy=0;
mypanel.add(textname,c5);
GridBagConstraints c6=new GridBagConstraints();
c6.gridx=2;
c6.gridy=1;
mypanel.add(changename,c6);
setVisible(true);
setSize(500,500);
setLocationRelativeTo(null);
setResizable(false);
Socket socket=new Socket("localhost",9000);
changename.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev)
{
user=textname.getText();
}
});
ClientPeer cp=new ClientPeer(user,socket);
String message=textf.getText();
cp.start();
send.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev)
{
try {
String sendit=textf.getText();
cp.sendMessage(sendit);
textf.setText("");
} catch (IOException ex) {
Logger.getLogger(TextClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public static void main(String [] args)
{
try {
new TextClient();
} catch (IOException ex) {
Logger.getLogger(TextClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Your mixing up objects and variables, and making one call at the wrong time.
Here:
ClientPeer cp=new ClientPeer(user,socket);
String message=textf.getText();
You call getText() in a constructor and not in an ActionListener, meaning you're making this call before the textf JTextField has even been rendered in a GUI and long before the user has had a chance to fill it.
Here:
#Override
public void actionPerformed(ActionEvent ev)
{
user=textname.getText();
}
You change the state of the user field inside of an ActionListener, but unfortunately you use the user varable in the first code that I have shown, again before the field has been rendered and before the user has interacted with it.
I suggest that you put more of your code, including the code that uses the user variable inside your ActionListener code, so that the variable actually holds relevant information.
Other recommendations:
None of your fields should be declared static. If you feel that they must be static to fix an error, then you're fixing the error backwards. The correct fix is to create code that does not require static fields (with some exceptions of course, but none that apply in your current case).
Here's a simplified version of your code, to show you what I mean:
import javax.swing.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TextClient extends JFrame {
public JPanel mypanel = new JPanel();
public JButton send = new JButton("Send");
public JButton changename = new JButton("Change name");
public JTextField textf = new JTextField(10);
public JTextField textname = new JTextField(10);
public JLabel username = new JLabel("Name:");
public String user;
public TextClient() throws IOException {
add(mypanel);
mypanel.add(textf);
mypanel.add(send);
mypanel.add(username);
mypanel.add(textname);
mypanel.add(changename);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setVisible(true);
setLocationRelativeTo(null);
changename.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
user = textname.getText();
System.out.println("user in action listener: " + user);
}
});
// you're trying to use user here!
System.out.println("user outside of action "
+ "listener where you try to use it: " + user); // !!
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
String sendit = textf.getText();
System.out.println("sendit: " + sendit);
}
});
}
public static void main(String[] args) {
try {
new TextClient();
} catch (IOException ex) {
Logger.getLogger(TextClient.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
By now, I already know my code is flawed. I just want to know why it's flawed. I want to activate the "webButton" so that when it gets clicked, it prints a message on the console that reads "This opens Mozilla Firefox."
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone implements ActionListener {
public static void main(String[] args) {
{
{
JFrame container = new JFrame();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
JButton webButton = new JButton(new ImageIcon("Firefox.png"));
JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
JButton texButton = new JButton(new ImageIcon("Phone.png"));
JButton setButton = new JButton(new ImageIcon("Settings.png"));
JButton smsButton = new JButton(new ImageIcon("sms.png"));
container.setTitle("Smartphone Interface!");
container.setSize(240,340);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
webButton.addActionListener(instanceofSmartphone);
}
}
}
}
Do this.
webButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
}
});
If you want to use the ActionListener interface then, implement it in your Frame class and then replace that instanceOfSmartphone with
webButton.addActionListener(this);
And put this outside the method
public void actionPerformed(ActionEvent e) {
if(e.getSource() == webButton) {
}
}
You need to implement the actionPerformed method. An example follows.
public void actionPerformed(ActionEvent e) {
System.out.println("This method opens Mozilla Firefox.");
}
Additionally, you need to change how you add the action listener to the following.
webButton.addActionListener(this);
There are also a number of other issues. Here is a modified version of your code to get it working but far from perfect or what you will want in the end. I strongly recommend you walk through all of the tutorials in order at the below website. It doesn't get any easier than what they have. Also, if your not already using it, you should try Netbeans or some other IDE. It give you feedback that may help while you are starting out.
https://docs.oracle.com/javase/tutorial/
package smartphone;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.util.Scanner;
public class Smartphone extends Frame implements ActionListener {
static JButton webButton = new JButton(new ImageIcon("Firefox.png"));
static JButton phoButton = new JButton(new ImageIcon("Facebook.png"));
static JButton texButton = new JButton(new ImageIcon("Phone.png"));
static JButton setButton = new JButton(new ImageIcon("Settings.png"));
static JButton smsButton = new JButton(new ImageIcon("sms.png"));
Smartphone(){
webButton.addActionListener(this);
}
public static void main(String[] args) {
Smartphone container = new Smartphone();
container.setLayout(new BorderLayout());
Scanner daniel = new Scanner(System.in);
container.setTitle("Smartphone Interface!");
container.setSize(240, 340);
container.add(setButton, BorderLayout.CENTER);
container.add(webButton, BorderLayout.SOUTH);
container.add(texButton, BorderLayout.NORTH);
container.add(phoButton, BorderLayout.EAST);
container.add(smsButton, BorderLayout.WEST);
container.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("This opens a Firefox Webbrowser.");
}
}
You need to add an ActionListener to the buttons INSIDE of the constructor: buttonName.addActionListener(this);.
Then you need to create the following method:
public void actionPerformed(ActionEvent event) {
Object control = event.getSource();
if (control == buttonName) {
//Run code...
}
}
I'm learning Swing class now and everything about it. I've got this toy program I've been putting together that prompts for a name and then presents a JOptionPane with the message "You've entered (Your Name)".
The submit button I use can only be clicked on, but I'd like to get it to work with the Enter button too. I've tried adding a KeyListener, as is recommended in the Java book I'm using (Eventful Java, Bruce Danyluk and Murtagh).
This is my code:
import java.awt.BorderLayout;
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;
import javax.swing.JTextField;
public class NamePrompt extends JFrame{
private static final long serialVersionUID = 1L;
String name;
public NamePrompt(){
setLayout(new BorderLayout());
JLabel enterYourName = new JLabel("Enter Your Name Here:");
JTextField textBoxToEnterName = new JTextField(21);
JPanel panelTop = new JPanel();
panelTop.add(enterYourName);
panelTop.add(textBoxToEnterName);
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitButton(textBoxToEnterName));
submit.addKeyListener(new SubmitButton(textBoxToEnterName));
JPanel panelBottom = new JPanel();
panelBottom.add(submit);
//Add panelTop to JFrame
add(panelTop, BorderLayout.NORTH);
add(panelBottom, BorderLayout.SOUTH);
//JFrame set-up
setTitle("Name Prompt Program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
NamePrompt promptForName = new NamePrompt();
promptForName.setVisible(true);
}
}
And this is the actionListener, keyListener class:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SubmitButton implements ActionListener, KeyListener {
JTextField nameInput;
public SubmitButton(JTextField textfield){
nameInput = textfield;
}
#Override
public void actionPerformed(ActionEvent submitClicked) {
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
}
Component frame = new JFrame();
JOptionPane.showMessageDialog(frame , "You've Submitted the name " + nameInput.getText());
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
There is a simple trick for this. After you constructed the frame with all it buttons do this:
frame.getRootPane().setDefaultButton(submitButton);
For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.
And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
System.out.println("Hello");
JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
}
}
UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:
SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);
You can use the top level containers root pane to set a default button, which will allow it to respond to the enter.
SwingUtilities.getRootPane(submitButton).setDefaultButton(submitButton);
This, of course, assumes you've added the button to a valid container ;)
UPDATED
This is a basic example using the JRootPane#setDefaultButton and key bindings API
public class DefaultButton {
public static void main(String[] args) {
new DefaultButton();
}
public DefaultButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton button;
private JLabel label;
private int count;
public TestPane() {
label = new JLabel("Press the button");
button = new JButton("Press me");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
gbc.gridy++;
add(new JButton("No Action Here"), gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
InputMap im = button.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = button.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "spaced");
am.put("spaced", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
doButtonPressed(e);
}
});
}
#Override
public void addNotify() {
super.addNotify();
SwingUtilities.getRootPane(button).setDefaultButton(button);
}
protected void doButtonPressed(ActionEvent evt) {
count++;
label.setText("Pressed " + count + " times");
}
}
}
This of course, assumes that the component with focus does not consume the key event in question (like the second button consuming the space or enter keys
In the ActionListener Class you can simply add
public void actionPerformed(ActionEvent event) {
if (event.getSource()==textField){
textButton.doClick();
}
else if (event.getSource()==textButton) {
//do something
}
}
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Without a frame this works for me:
JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
null, tf, "Enter your message",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,0);
message = tf.getText();
I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key
textField_in = new JTextField();
textField_in.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getExtendedKeyCode());
if (arg0.getKeyCode()==10) {
String name = textField_in.getText();
textField_out.setText(name);
}
}
});
textField_in.setBounds(173, 40, 86, 20);
frame.getContentPane().add(textField_in);
textField_in.setColumns(10);