How to restrict input types - java

I am learning java swing. There is an editable JComboBox for selecting different depths of water and a JTextField to accept mobile number. My question is how can I restrict the user to enter only digits in these two fields and also, how to limit the maximum number of character inputs like not more than 10 for the mobile number? Are methods available for these requirements or I need to define them of my own?
Thanks in advance for your help.

Use a JFormattedTextField something like:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("JFormattedTextField Example");
MaskFormatter fmt = null;
// A phone number 10 digits
try {
fmt = new MaskFormatter("(###)-###-####");//brackets () are optional just there for my pref
fmt.setPlaceholderCharacter('*');//set place holder for the empty digits of the number
} catch (java.text.ParseException e) {
}
JFormattedTextField tft1 = new JFormattedTextField(fmt);
frame.add(tft1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
This automatically has the properties you want it will only accept digits in a specified format
Have a look at the docs too for more info: JFormattedTextField

How about this to restrict the user from typing characters other than numbers in phone text field
TF1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
char k=arg0.getKeyChar();
if (!(k>='0' && k<='9'))
arg0.consume();
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});

Related

Wait for TextField input, before continuing with the code

I have a Graphical User Interface that has a TextField, my code looks as following:
int port = 0;
try{
port = Integer.parseInt(frame.textfieldInput.getText());
}
catch(NumberFormatException npe)
{
System.out.println("Error! parse exception");
}
System.out.println("The Port is " + port); //is 0
I have to assign the value '0' to port, because otherwise the code wont compile, because the variable wouldn't be initialized.
Because the TextField is empty at the beginning of the Program, getText() wont get a value, which is why port stays '0'.
Is there any way to wait for the input before the code continues?
Found a solution, this is how I solved it:
I created a global variable outside of my ActionListener:
public String value = "";
public void createInput() {
buttonInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
value = textfieldInput.getText();
}
});
}
named 'value'.
in my public static void main(String[] args) I declared the following:
while(frame.value.equalsIgnoreCase(""))
{
try
{
System.out.println("waiting...");
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println("interrupted");
}
}
I just have to clear the variable 'value' everytime I used it, so it is empty again for future uses.
I tis not the best way to solve it, but it worked for me.
Below code may give you some idea to more efficient way to get value on focus lost.
JFrame frame = new JFrame();
frame.setSize(50, 50);
TextField field = new TextField();
field.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// continue from here
System.out.println(field.getText());
}
#Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
});
frame.getContentPane().add(field);
frame.setVisible(true);

How can I add a place to type user input in a jframe?

I want to have user input in a program I am creating is there any way in a jframe in java to have a place a user can type things into.
You can use Text Fields like JTextField, JFormattedTextField etc. For more details you can refer to Oracle documentation on Swing.
Several java Swing GUI Components allow for user input of which you can use in the JFrame.For instance, text fields provide formatted text input or password field behavior. I suppose you should get familiar with the swing GUI Components for you to make friendly user interfaces.
Something like:
package test20may2014;
import java.awt.BorderLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.*;
public class Test20may2014 implements WindowListener{
static JTextArea foo;
static JTextField bar;
public static void main(String[] args) {
JFrame jframe = new JFrame("Test20May2014");
jframe.addWindowListener(new Test20may2014());
foo = new JTextArea(10,10);
bar = new JTextField(10);
jframe.getContentPane().add(foo, BorderLayout.NORTH);
jframe.getContentPane().add(bar, BorderLayout.CENTER);
jframe.pack();
jframe.setVisible(true);
}
#Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowClosing(WindowEvent arg0) {
System.out.println(foo.getText());
System.out.println(bar.getText());
System.exit(0);
// TODO Auto-generated method stub
}
#Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
}

Java - Is it possible to detect when Mouse Button Four or KeyPress anytime?

So I have been trying to figure out some things with Java. I have the click event trigger and print "SUPSUP" in the program when the JFrame window pops up. But I was wondering is there a way to set up the app where if I press button 4 outside the JFrame window the "SUPSUP" will still be printed? I mean I want to have a listener in java in general not tied to the JFrame Components, I wouldn't mind if I needed to use a key listener either. I'm trying to build a program that will do certain things on the screen every time I click on button 4, but I can't be able to click on the blue JFrame thanks.
So Far I have this code.
public class CriticalMassWizard implements MouseListener
{
private static CriticalMassWizard instance = null;
private static Robot robot;
private static boolean triggerSpam;
private static JFrame frame = new JFrame("Tester");
// Singleton
public static CriticalMassWizard getInstance()
{
if(instance == null) {
instance = new CriticalMassWizard();
instance.setUpFrame();
try {
robot = new Robot();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return instance;
}
private void setUpFrame()
{
frame.setResizable(true);
frame.setSize(300, 300);
frame.getContentPane().setBackground(Color.BLUE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton() == 4)
{
System.out.println("SUPSUP");
}
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
Now this is related to FocusListeners and the focus that is set at a point in time at whatever JFrame you are on. It might be possible if you have multiple JFrame's and you click on one of them to output something on another, but if you click on your desktop,for eg, then this cannot be accomplished through native Java Libraries.

How to trigger an event on enter key press in JTextField in java

I have a button and a JTextField and if the JTextField is empty a message window opens informing that the field is empty.
Now I want when I enter a number inside the JTextField, the text on the button to change.
But I don't know which code to use.
I used this code
tfInputTinter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btObserving.setText("Stop Observing");
}
});
but nothing happens with the text on the button.
Does anybody have an idea what should I do?
Thanks
I would say, this will do the trick.
https://stackoverflow.com/a/3953219/3178834
The person in this post had the same problem I think.
Greetz,
xwavex
You are wanting a KeyListener to listen for events on the keyboard.
textField.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
public void keyReleased(KeyEvent e)
{
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
}
});
Or rather than using the inner type way of working you can implement KeyListener in a class and implement the same set of methods in your class.

Allow characters storage on JTextField only if are numbers

I want to filter the key that are pressed on JTextField.
I want that only numbers are allowed, and if other character are pressed it remove it or don't allow the storage on the text field.
I'm thinking to use an addKeyListener, and use the methods: key pressed and key released.
Any Ideas?
Try this
final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
String oldText = "";
public void keyPressed(KeyEvent keyEvent) {
// Store old text in a temporary variable
oldText = myTextField.getText();
}
public void keyReleased(KeyEvent keyEvent) {
// Make sure that the user is typing a number else replace with old text.
int charCode = (int)keyEvent.getKeyChar();
if (charCode < 48 || charCode > 57){
myTextField.setText(oldText); // Replace with old text.
}
}
public void keyTyped(KeyEvent keyEvent) {
}
});
No offence, Mr. Ravindra's answer is correct but it fails when you type continuously ..
I hope this helps :
final JTextField myTextFiled=new JTextField();
JFrame frame=new JFrame("onlyNums");
KeyListener myKeyListner=new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()>='0' && e.getKeyChar()<='9')
myTextFiled.setText(myTextFiled.getText()+e.getKeyChar());
else if(e.getKeyChar()==KeyEvent.VK_BACK_SPACE && myTextFiled.getText().length()>0)
myTextFiled.setText(myTextFiled.getText().substring(0, myTextFiled.getText().length()-1));
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
};
//to null out handling other inputs
myTextFiled.setInputMap(JTextField.WHEN_FOCUSED, new InputMap());
//to add your own handling
myTextFiled.addKeyListener(myKeyListner);
Note: You have to add handling to insert/remove from the pointer's position.
Regards,
Use a custom Document:
public class NumericDocument extends PlainDocument {
#Override
public void insertString(int pos, String text, AttributeSet as)
throws BadLocationException {
try {
Integer.parseInt(text);
super.insertString(pos, text, as);
} catch(NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
}
Install to your TextField:
JtextField field = new JTextField();
field.setDocument(new NumericDocument());
This will work, even if text is pasted (where no KeyEvent is fired).

Categories