I have to implement a way for update a jbutton text based on the user keyboard inputs, let's say that i have this gui
When a user clicks on one of this buttons he must be able to change the number on it by typing on the keyboard, the interaction has to be direct, so without having a text field or typing in console.
I thought to use the Reader
class, but actually i'm not understanding how to do it...
Searching online i found only ways for do it by console/JTextField that is not what i need. I think that this will be a pseudoImplementation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame implements ActionListener {
JButton btn;
public static void main( String[] args ) {
new Gui();
}
public Gui() {
this.getContentPane().setLayout(new FlowLayout());;
this.setTitle("Title");
JButton btn = new JButton("3");
this.getContentPane().add(btn);
btn.addActionListener(this);
btn.setActionCommand("listenForInput");
btn.setSize(30, 30);s
this.pack();
this.setSize(100, 100);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if( cmd.equals("listenForInput")) {
/* ClassThatExtendsReader reader = new ClassThatExtendsReader();
String oldText = btn.getText();
boolean notPressedEnter = ture;
String newNum = "";
while( notPressedEnter ) {
String char = reader.nextLine();
if( char == Enter ) notPressedEnter = false;
newNum = newNum + char;
btn.setText(newNum);
}
if( newNum is not integer ) {
showMessage("wrong input");
btn.setText(oldText);
}
*/
}
}
}
So:
- Intialize the JFrame with a button inside
- add a listener to the button for detect when it is clicked
- when it is clicked read for the pressed chars
- each time that a char is entered update the button text
- when pressed ENTER stop the loop
-
- I think that the loop inside the listener should be in a
Runnable
class to put it in aThread
- I think that the loop inside the listener should be in a