Adding values in JTextFields in real time in Java GUI - java

I am writing a Java GUI program. I have two JTextFields:
'txtNet' and 'txtExcise'. I want values in these two textfields added as soon as I enter them and populate the result in another textfield 'txtTotal' without using a button.

I want values in these two textfields added as soon as I enter them
and populate the result in another textfield 'txtTotal' without using
a button.
This can be done using a DocumentListener on the JTextField's.
Here is a tutorial that covers the basics on how to use them: How to Write a Document Listener
Important extract from tutorial:
Document events occur when the content of a document changes in any
way
This will allow you to monitor changes on the textfield values and react accordingly. For your case this would involve checking the values of the 2 inputs and provided both are valid, displaying the result in the output textfield
Here is a quick SSCCE (Stack overflow glossary of acronyms):
public class AutoCalculationDemo {
public static void main(String[] args) {
JTextField firstInput = new JTextField();
JTextField secondInput = new JTextField();
JTextField output = new JTextField();
output.setEditable(false);
DocumentListener additionListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void removeUpdate(DocumentEvent e) {
attemptAddition();
}
#Override
public void changedUpdate(DocumentEvent e) {
attemptAddition();
}
public void attemptAddition(){
try{
double firstValue = Double.parseDouble(firstInput.getText());
double secondValue = Double.parseDouble(secondInput.getText());
output.setText(String.valueOf(firstValue + secondValue));
}catch (NumberFormatException nfe){
System.out.println("Invalid number(s) provided");
}
}
};
firstInput.getDocument().addDocumentListener(additionListener);
secondInput.getDocument().addDocumentListener(additionListener);
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3,2));
panel.add(new JLabel("First number: "));
panel.add(firstInput);
panel.add(new JLabel("Second number: "));
panel.add(secondInput);
panel.add(new JLabel("Output: "));
panel.add(output);
frame.add(panel);
frame.setSize(250,150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Related

Use KeyListener in a loop

I don't have a lot of experience with KeyListeners but I used one in my application and it works fine except I need to wait for input before my program can continue. For this I made a while loop that loops until the String temp is not null (which would mean there would be input).
The problem is there is no way to type in the JTextField (called input). Below is code from my two methods that are supposed to work together so that the text in my JTextField (input) can be returned (as temp). I'm not sure why this doesn't work or how to fix it.
The keyPressed method for my KeyListener:
public void keyPressed(KeyEvent e)
{
//only sends text if the enter key is pressed
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
//if there really is text
if (!input.getText().equals(""))
{
//String temp is changed from null to input
temp=input.getText();
//text sent to another JTextField
output.append(temp+"\n");
//input no longer has text
input.setText("");
}
}
}
The method thats trying to get text, also in my KeyListener class
public String getTemp()
{
booleans isNull=temp==null;
//loops until temp is not null
while (isNull)
{
//unnecessary line of code, only used so the loop not empty
isNull=checkTemp();
}
return temp;
}
public boolean checkTemp()
{
return temp==null;
}
Your while loop is a common console program construct, but understand that you're not creating a console program here but rather an event-driven GUI, and in this situation, the while loop fights against the Swing GUI library, and you need to get rid of it. Instead of a while loop with continual polling you now want to respond to events, and if you're listening for user input into a JTextField do not use a KeyListener as this low-level listener can cause unwanted side effects. Instead add a DocumentListener to the JTextField's Document.
Edit: You're listening for the enter key, and so the solution is even easier: add an ActionListener to the JTextField!
e.g.,
input.addActionListener(e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
});
More complete example:
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ChatBox extends JPanel {
private static final int COLS = 40;
private JTextField input = new JTextField(COLS);
private JTextArea output = new JTextArea(20, COLS);
private JButton submitButton = new JButton("Submit");
public ChatBox() {
output.setFocusable(false); // user can't get into output
JScrollPane scrollPane = new JScrollPane(output);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ActionListener inputListener = e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
input.requestFocusInWindow();
};
input.addActionListener(inputListener);
submitButton.addActionListener(inputListener);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(input);
bottomPanel.add(submitButton);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ChatBox mainPanel = new ChatBox();
JFrame frame = new JFrame("Chat Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

How to enter a specific word in a textfield

what do I have to add to the code below so that the user has to enter a specific word i.e. "London" to open the JOptionPane input dialog box.
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
At the moment I can type in anything in the text field and the dialog box will appear. I only want it to open if the user enters a specific word.
I'm using the action event with action listener and action performed to open the JOptionPane Dialog box.
public class Test9 {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField");
JTextField textfield = new JTextField(30);
frame.add(textfield);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,200);
JPanel panel = new JPanel();
frame.add(panel);
panel.add(textfield);
textfield.addActionListener(new Action4());
}
}
You can do something like this.
if(museum_name.equals("London")){
JOptionPane.showMessageDialog(null, " You are attending the " + museum_name);
} else{
// show the error message
}
Its encouraged to use equals() method for String comparison. Please note, equals() is used to compare two strings for equality, while operator == compares the reference of an object in java.
Update
To show an error message if the input is not "London", you can do something like this.
static class Action4 implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String museum_name = ((JTextField) e.getSource()).getText();
if (museum_name.equals("London")) {
JOptionPane.showMessageDialog(null, "You are attending the " + museum_name);
} else {
JOptionPane.showMessageDialog(null, "Wrong input!");
}
}
}

Pass a String to another class

I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)

Problems aligning text field input using GridLayout

I want to make a form using java frame. I have two fields Name and Age. After entering the details, when the button is clicked, the entered data must be displayed as shown below, but I am not sure how to align it.
The entered data are:
FirstName: abcd
LastName: efg
This is what I have so far:
import java.awt.*;
import java.awt.event.*;
public class DataEntry {
public static void main(String[] args) {
Frame frm=new Frame("DataEntry frame");
Label lbl = new Label("Please fill this blank:");
frm.add(lbl);
frm.setSize(350,200);
frm.setVisible(true);
frm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p = new Panel();
Panel p1 = new Panel();
Label jFirstName = new Label("First Name");
TextField lFirstName = new TextField(20);
Label jLastName =new Label("Last Name");
TextField lLastName=new TextField(20);
p.setLayout(new GridLayout(3,1));
p.add(jFirstName);
p.add(lFirstName);
p.add(jLastName);
p.add(lLastName);
Button Submit=new Button("Submit");
p.add(Submit);
p1.add(p);
frm.add(p1,BorderLayout.NORTH);
}
}
Firstly, you need to add an event to the button, when it is clicked.
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Add the code to output the relevant details.
}
}
Then it's up to you to add the relevant code to the method body.
You should read the Documentation
Add a listener to your "Submit" button:
Submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myLabelForShowingTheOutput.setText("<html><body>Name: " + lFirstName + "<br>Last name: " + lLastName + "</body></html>");
}
});
Note that "myLabelForShowingTheOutput" is the JLabel you want to print. The text to print is basic HTML, so the label can show multiple lines. Other way to do it without HTML would be create a JLabel for the name and another for the age. Note as well that I did put the last name in the output, because there isn't an obvious JTextField for the age.
Remember, as well, that variables should start their name in lower case, so Submit would be "submit".

Java JTabbedPane, update others tab JLabel value?

I have 2 JTabbedPane. I am unable to refresh the data. PLease help, here is my code:
pane1:
//.. some codes...
// This is the ButtonListener
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
userInput = tf.getText(); // tf is JTextField
//System.out.println("the input is "+ finalInput);
pane2.updateData(userInput);
}
}
pane2:
public void updateData(String s){
System.out.println("Update data function is called");
labelUser.setFont(new Font("Arial", Font.BOLD, 30));
labelUser.setText("Updated text here " + s);
}
Here is my main class:
import java.awt.*;
import javax.swing.*;
public class Main {
public static Pane2 p2 = new Pane2();
public static void main(String[] args) {
JFrame f= new JFrame ("My Frame");
f.setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
p2 = new Pane2();
tp.addTab("Pane1", new PaneFirst(p2));
tp.addTab("Pane2", new PaneSecond());
f.add(tp);
f.pack();
f.setVisible(true);
}
}
The labelUser never updates, but I trace the updateData function, its being called. Why is the text in labelUser not being updated?
EDIT:
"labelUser" come from pane2.java class.
Note: Apparently this didn't fix the problem.
One thing to try would be:
public void updateData(String s){
System.out.println("Update data function is called");
labelUser.setFont(new Font("Arial", Font.BOLD, 30));
labelUser.setText("Updated text here " + s);
repaint(); // add this line to tell your pane to repaint itself
}
There is a chance that your panel is just not getting repainted.
Might be a typo but - in actionPerformed() you store the content of the textfield in userInput but use finalInput to update pane2.

Categories