I also wanted to make the input dynamic so that it changes the value as i press any key. Thanks i dont know how to use a keylistener or something that would process my code.
public static void DecimalToAll(String varInput){
//DeciToHexa
int varDeciToHexa = Integer.parseInt(varInput);
String DeciToHexaAnswer = Integer.toHexString(varDeciToHexa);
System.out.println(DeciToHexaAnswer.toUpperCase());
//DeciToOctal
int varDeciToOctal = Integer.parseInt(varInput);
String DeciToOctalAnswer = Integer.toOctalString(varDeciToOctal);
System.out.println(DeciToOctalAnswer);
//DeciToBinary
int varDeciToBinary = Integer.parseInt(varInput);
String DeciToBinaryAnswer = Integer.toBinaryString(varDeciToBinary);
System.out.println(DeciToBinaryAnswer);
An example making use of DocumentListener:
JTextField can't add a "ChangeListener" like other components. To "monitor' changes in a JTextField, you can add a DocumentListener to the textfield:
private class MyDocumentListener implements DocumentListener
{
public void changedUpdate(DocumentEvent e){
//Do nothing
}
public void insertUpdate(DocumentEvent e){
//Do things when text are inserted
}
public void removeUpdate(DocumentEvent e){
//Do things when text are deleted
}
}
To add the DocumentListener, get the Document object from JTextField and add it:
JTextField txt = new JTextFeld();
txt.getDocument().addDocumentListener(new MyDocumentListener());
Related
Hey guyz i'm working on a GPA calculator for my java assignment, and the gui i have created is 100% based on Events i.e. no buttons for the user to submit his data. my question is how do i know if a textfield value has changed and if it did how do i get the original value befor the change.
another question how can i store each component in an arrayList do the user can create as many rows as they like Thanks
this is the snapshot of mu GUIenter image description here
BTW feel free any other suggestion
You can use keylistener
JTextField usernameTextField= newJTextField();
usernameTextField.addKeyListener(new () { public void keyReleased(Key KeyAdapter Event e) { JTextField textField = (JTextField) e.getSource(); String text = textField.getText(); textField.setText(text.toUpperCase()); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } });
I currently have a JTextField and inside that, I have default text.
The problem I currently have is getting that JTextField to have a working ActionListener. I have added an action listener to the component, but when I use FocusListener to check for focus, it will not give any output/reply.
Any help will be much appreciated. And please supply me with some example code of what I should change, thanks.
PS. I am using this class as a component from another class, so in another class I wrote:
window.add(smartTextField);
SmartText.java
package com.finn.multiweb;
import java.awt.Color;
import javax.swing.JTextField;
public class SmartText extends JTextField {
private static final long serialVersionUID = 1L;
JTextField textField = new JTextField();
String defaultText;
boolean hasDefaultText;
public SmartText() {
super();
hasDefaultText = false;
notFocused();
}
public SmartText(String defaultText) {
super(defaultText);
this.defaultText = defaultText;
hasDefaultText = true;
notFocused();
}
private void notFocused() {
super.setForeground(Color.GRAY);
if (hasDefaultText == true) {
super.setText(defaultText);
} else if (hasDefaultText == false) {
super.setText("");
}
}
private void isFocused() {
super.setForeground(Color.BLACK);
super.setText("");
}
private void focusGained(java.awt.event.FocusEvent evt) {
System.out.println("test");
}
}
You've not added a FocusListener to the field
// You need to implement the FocusListener interface
public class SmartText extends JTextField implements FocusListener {
private static final long serialVersionUID = 1L;
JTextField textField = new JTextField();
String defaultText;
boolean hasDefaultText;
public SmartText() {
super();
hasDefaultText = false;
notFocused();
// Then register yourself as interested in focus events
addFocusListener(this);
}
public SmartText(String defaultText) {
super(defaultText);
this.defaultText = defaultText;
hasDefaultText = true;
notFocused();
// Then register yourself as interested in focus events
addFocusListener(this);
}
// Then implement the contract of the FocusListener interface
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
Take a read through How to Write a Focus Listener for more details
From the looks of your code, you trying to add "prompt support" to the field, you may consider using the PromptSupport from the SwingLabs, SwingX libraries, for example
You can use the Text Prompt which is a single class.
To work with FocusListener Interface and in order to listen’s the keyboards gaining or losing focus, the listener object created from class is need to registered with a component using the component’s addFocusListener() method. The two important method focusGained(FocusEvent e) and void focusLost(FocusEvent e) which helps to find which component is focused.
Take a read through What is FocusListener Interface and How it Work and Validate Text Field Using FocusListener Interface in Java for more details with proper examples.
I have some text field on my form. And I like focusGained and focusLost event. Doing this with 2 or 3 text field is easy. But, after 18 text field, well, it's kinda confusing.
Is there any way to shorten the focusGained and focusLost event?
Example:
txtSomeTextFocusGained(java.awt.event FocusEvent evt){
if(txtSomeText.getText().equals("Text here!"){
txtSomeText.setText("");
}
}
txtSomeTextFocusLost(java.awt.event FocusEvent evt){
if(txtSomeText.getText().equals(""){
txtSomeText.setText("Text here!");
}
}
That's one text field, I've problem handling with about 18 text field. Any way to simplify that?
Thanks.
The methods are simple enough, so I can't think of a way to simplify them any further. What you can do, though, is prevent code repetition by declaring one FocusListener instance and then add it using addFocusListener(...) to all text-fields.
It would look something like this:
// Instantiate a FocusListener ONCE
java.awt.event.FocusListener myFocusListener = new java.awt.event.FocusListener() {
public void focusGained(java.awt.event.FocusEvent focusEvent) {
try {
JTextField src = (JTextField)focusEvent.getSource();
if (src.getText().equals("Text here!") {
src.setText("");
}
} catch (ClassCastException ignored) {
/* I only listen to JTextFields */
}
}
public void focusLost(java.awt.event.FocusEvent focusEvent) {
try {
JTextField src = (JTextField)focusEvent.getSource();
if (src.getText().equals("") {
src.setText("Text here!");
}
} catch (ClassCastException ignored) {
/* I only listen to JTextFields */
}
}
};
(You could omit the try-catch blocks if you were absolutely sure that the source of the event would always be a JTextField, but it is always a bad practice to rely on such assumptions.)
Then, for every JTextField you only need to add the same FocusListener:
...
someTextField.addFocusListener(myFocusListener);
...
(It's only half a line - difficult to get any shorter than that.)
Another alternative would be to subclass JTextField, adding a FocusListener in the constructor, but I don't see any advantage over the first solution (unless you want a more flexible/powerful solution, e.g. different text for each JTextField etc).
If you want just to set some text in field which gets focused you could write separated event handler class which implements FocusListener and then override focusGained and focusLost methods. Something like this:
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class CustomFocusListener implements FocusListener {
JTextField txt;
String textWhenFocusGained;
String textWhenFocusLost;
public CustomFocusListener(JTextField txt, String textWhenFocusGained,
String textWhenFocusLost) {
this.txt = txt;
this.textWhenFocusGained = textWhenFocusGained;
this.textWhenFocusLost = textWhenFocusLost;
}
#Override
public void focusGained(FocusEvent arg0) {
txt.setText(textWhenFocusGained);
}
#Override
public void focusLost(FocusEvent arg0) {
txt.setText(textWhenFocusLost);
}
}
Use this.
if(txtSomeText.getText().equals("Text here!")){
txtSomeText.setText("");
/////////////// It's problem of lower and supper case you should make ur text in lower case in code. and for desing of jtextfield it's ok
txtIdDeVoyageur = new JTextField();
txtIdDeVoyageur.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
if(txtIdDeVoyageur.getText().trim().toLowerCase().equals("id de voyageur")){
txtIdDeVoyageur.setText("");
txtIdDeVoyageur.setForeground(Color.black);
}
}
#Override
public void focusLost(FocusEvent e) {
if (txtIdDeVoyageur.getText().trim().equals("") ||
txtIdDeVoyageur.getText().trim().toLowerCase().equals("id de voyageur"))
{
txtIdDeVoyageur.setText("id de voyageur");
txtIdDeVoyageur.setForeground(new Color (153,153,153));
}
}
});
There's a text field and when lost focus it will validate the inputs, if not passed, print out the error message (to be simple here just has an empty check). And there's a button next to the text field, it will print out the text once click on it.
As I tried, when input some text and then click the button it will trigger both the focus lost event of text field and the event of button. In a other word, it will do the validation first and then print out the input text.
Here comes my question, what is the good approach to prevent printing out the text if the validation not passed? Or is there a way to "ignore" the click event on button if validation not passed?
I tried to use a boolean flag which indicate the validation result and check the flag when perform the action for button, but I do not think it is a good approach. As I know there's an event dispatcher thread in Swing which deal with the events, is it possible I can cancel the events from here?
Below is a piece of code which explain the question:
public class SimpleDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel(new FlowLayout());
frame.setContentPane(content);
final JTextField textField = new JTextField(10);
textField.addFocusListener(new FocusAdapter()
{
#Override
public void focusLost(FocusEvent e)
{
String text = textField.getText();
// do some validation here, if not validated
// do not trigger the event on button.
if ("".equals(text))
{
System.out.print("please input a text!");
}
}
});
content.add(textField);
JButton button = new JButton("Print Text");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// action performed for button
String text = textField.getText();
System.out.println(text);
}
});
content.add(button);
frame.setVisible(true);
frame.pack();
}
}
I faces similar issue while working on an application. I solved it like below
I created a abstract class ApplicationFrame which every frame in the application extends
public abstract class ApplicationFrame extends JFrame implements ActionListener {
#Override
final public void actionPerformed(ActionEvent event) {
if(validateInput()){
performAction(event);
}
}
/*
* Sub class should override this method to receive any action
*/
protected void performAction(ActionEvent event) {};
/*
* Sub class should override this method to perform validation
*/
abstract protected boolean validateInput();
}
All Frames will now extend this base frame, as below:
public class Frame1 extends ApplicationFrame{
#Override
protected void performAction(ActionEvent event) {
// perform action
}
#Override
protected boolean validateInput() {
// return true or false depending upon the validation results
}
// if you want to add Action Listener, you need to add like this:
btnSomeButton.addActionListener(this);
}
If you need to handle Focus events, you can make ApplicationFrame or the base frame implement FocusListener.
This is my custom implementation to solve the problem, hope this helps.
Make the button disabled on start-up
Upon lost focus, validate the text & enable button only when the input passes validation.
Upon start of text change, disable the button
It's always makes sense to make ui to communicate with user. So you can show "please input a text" as the default text of the textField when nothing is entered by user.
Here is the code for such custom textField:
public class TextFieldWithDefaultText extends JTextField implements FocusListener{
private final String hint;
public TextFieldWithDefaultText (String $text)
{
super($text);
this.hint = $text;
addFocusListener(this);
}
#Override
public void focusGained (FocusEvent $e)
{
if (this.getText().isEmpty())
{
super.setText("");
}
}
#Override
public void focusLost (FocusEvent $e)
{
if (this.getText().isEmpty())
{
super.setText(hint);
}
}
#Override
public String getText ()
{
String typed = super.getText();
return typed.equals(hint) ? "" : typed;
}
}
Write the acttionListerner for your button like this:
JButton button = new JButton("Print Text");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(!textField.getText().isEmpty())
System.out.println(textField.getText());
}
});
And ur textField implementation should be :
final TextFieldWithDefaultText textField = new TextFieldWithDefaultText ("please input a text");
Hope this helps :)
How I can retrive the event on a JLabel when change the text inside??
I have a JLabel and when change the text inside I have to update other field.
techically, the answer is to use a PropertyChangeListener and listen to changes of the "text" property, something like
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChanged(PropertyChangeEvent e) {
// do stuff here
}
};
label.addPropertyChangeListener("text", l);
not so technically: could be worth to re-visit the overall design and bind to original source which triggered the change in the label
IMHO you can not get an event on JLabels textchange. But you can use a JTextField instead of a JLabel:
private JTextField textFieldLabel = new JTextField();
textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);
textFieldLabel.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
System.out.println("removeUpdate");
}
public void insertUpdate(DocumentEvent e) {
System.out.println("insertUpdate");
}
public void changedUpdate(DocumentEvent e) {
System.out.println("changedUpdate");
}
});
Note: this event is fired no matter how the text gets changed; programatically via "setText()" on the TextField or (if you do not "setEditable(false)") via clipboard cut/paste, or by the user typing directly into the field on the UI.
The lines:
textFieldLabel.setEditable(false);
textFieldLabel.setOpaque(true);
textFieldLabel.setBorder(null);
are used to make the JTextField look like an JLabel.