get value of changed JTextField on Java Swing - java

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) { } });

Related

How do i get the value in the textfield in GUI? java

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());

Display output from a method on a JPanel in Java

I have a GUI the gets an input from a text area and on the click of button produces a report. The report is supposed to be displayed below the input area. On the click of the button, the input data are passed to a a void method called Calculate(), and right now the correct results are displayed on the console by System.out.printf(). How can I redirect this output to the report area?
public class Progress extends JFrame
{
JTextArea input;
JButton calculate;
JPanel report;
public void Notify()
{
calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculate();
}
});
}
}
...
public void Calculate()
{
GenerateReport m = new GenerateReport();
m.Parsecsv(input.getText());
}
So, as a newbie to Java, I wanted to know how I can redirect the output of my Calculate() method to the report panel?
Well you could modify your Calculate to return a string containing the information you want to print into the text area. I assume you know how to make simple methods that aren't void and return a data type:
public String Calculate() {
<something to get the text needed is done here>
return <text from report>;
}
Then you could make a "JOptionPane.showMessageDialog( Calculate() )" to show the report, or you could as mentioned create a JLabel to print the report within the frame your working with.
Something like:
JLabel lab1 = new JLabel(null, Calculate() );
If I understand you right?
I think what you're trying to ask is, "What is a JLabel?". You can use a JLabel to output your text from your calculate method.
Or you can return a String from your calculate method and somehow display it otherwise.

Java Swing default focus on frame

I am learning java and Swing right now and trying to develop simple programms for education purposes.
So here is the question.
I have gridlayout and fields on my frame with default text
accNumberField = new JTextField("0", 10);
accNumberField.addFocusListener(new FocusListener() {
int focusCounter = 0;
#Override
public void focusGained(FocusEvent arg0) {
// TODO Auto-generated method stub
if (focusCounter > 0)
accNumberField.setText("");
focusCounter++;
}
What I want is that when user click on field for the first time the default text is disappered. So I add focus listener and used accNumberField.setText(""); in focusGained method.
But the problem is that for default first field in my frame getting focus right in time of frame creation. And default text is disappearing from the begining. I used counter as you can see. But that's not what I wanted.
I want that no field would get focus in time of creation and every field would be able to get focus from the time when user would click on one of them.
Sorry if I spelled something wrong. English is not my native language.
Found a thread having a code example of your desired functionality, Java JTextField with input hint. Precisely, you need to provide your own implementation of JTextField which will be holding the "default-text" in a field, specially created for that.
For your second question, you can set the focus to some button or frame itself.
Is there any reason that you use focusListener()? why not use mouseListener() as follow?
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
accNumberField.setText("");
}
});
if you want to clear the text for the first click, you can simply use a boolean:
//outside constructor
private boolean isTextCleared = false;
//in constructor
accNumberField.addMouseListener(new MouseAdapter()
{
#Override
public void mouseReleased(MouseEvent e)
{
if (!isTextCleared)
{
accNumberField.setText("");
isTextCleared = true;
}
}
});

How can I Listen for Keyboard input without Text Field Java

I am working on a Java application and interfacing with an RFID reader that acts as a keyboard input device.
The application will be used for employee time tracking, so the employee should not see the code that his/her RFID tag contains.
Currently, the application opens a jFrame that asks the employee to scan their tag. This is where I would like to listen for the keyboard input.
All of the RFID tags are 10 digits, so I would like to use some kind of regex to detect when a card is scanned if possible.
If someone could point me in the right direction, or contribute some code I would be grateful.
Thanks in advance.
UPDATE:
I was able to read the input of the scanner by adding the following to the constructor of my JFrame.
addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){ System.out.print(e.getKeyChar());}
#Override
public void keyReleased(KeyEvent e) { }
#Override
public void keyTyped(KeyEvent e) { }
});
So it is now confirmed that the Reader is just standard Keyboard input.
Here is an example of what I get for a tag: 0006459027
Now, the big question is, how do I take the characters that I got, and detect that it is a 10 digit string, and from there trigger an event to open a new frame?
First, I'd see if the RFID reader is triggering an ActionEvent to be fired when the tag is scanned. This would be the simplest approach.
Failing that, you would need to attach a DocumentListener to the fields underlying document and monitor for changes.
You'll need to decide how best to interrupt the results (as you're likely to get each letter of the RFID at a time). You could monitor the length of the document or have a javax.swing.Timer which triggers after a short delay (you'd reset the timer on each update event triggered by the DocumentListener)
Check out
JTextField.addActionListener
JTextField.getDocument().addDocumentListener
I'd suggest taking a look at DocumentFilter as well, but your interested in the final result, not modifying it.
UPDATED with DocumentListener Example
// In the classes variable decleration section...
private JTextField rfidField;
// In the classes constructor or UI init method...
rfidField = new JTextField(12);
rfidField.getDocument().addDocumentListener(new DocumentListener() {
public void handleUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 10) {
System.out.println("Trigger me happy...");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
rfidField.setText(null);
}
});
}
}
#Override
public void insertUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
handleUpdate(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
handleUpdate(e);
}
});
// Now don't forget to add the field to your forms container ;)
//////
One of things I would be do when you "trigger" the code event is, once you've read it from the text field, is clear the text field (JTextField.setText(null)) - IMHO
If the RFID reader acts as a keyboard input device, try with key events:
JFrame frame = new JFrame();
// frame setup
frame.addKeyListener(new KeyAdapter(){
public void KeyPressed(KeyEvent ke)
{
System.out.println(ke);
}
});
Otherwise you have to check which kind of event it fires.
I was in a similar situation but with a bar-code scanner.
I really worked hard on a custom DocumentListener that would take care of all scenarios, and none of it worked.
Out of desperation, I added an ActionListener and it then worked very well.
Here is a code snap-shot :
try {
txtStockItemRef.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(txtStockItemRef.getText());
DatabaseManager.peformStockItemLookupByBarcodeRef(txtStockItemRef.getText());
}
});
} catch(Exception exc) {
LiveCityRetailTools.handleExceptionWithUserMessage(exc);
}

JLabel on change text event

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.

Categories