textArea.setText("") doesn't clear the text in a JTextArea - java

I am trying to clear the text in a JTextArea, and looking at other questions, it seems like calling textArea.setText(""/null) will clear the text area. This does not seem to be happening with my code, and it appends the new text to the text already in the area. Can anyone see something wrong in my code?
public class morseJFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public JTextPane textPane = new JTextPane();
public JTextArea textArea = new JTextArea();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
morseJFrame frame = new morseJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public morseJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 508);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textPane.setBounds(5, 5, 424, 194);
textPane.setText("Enter your alphanumberic text here to translate.");
contentPane.add(textPane);
JButton btnTranslate = new JButton("Translate");
btnTranslate.setBounds(5, 419, 213, 41);
btnTranslate.addActionListener(this);
add(btnTranslate);
contentPane.add(btnTranslate);
textArea.setBounds(5, 210, 424, 203);
contentPane.add(textArea);
JButton btnPlaySound = new JButton("Play Morse Sound");
btnPlaySound.setBounds(228, 419, 201, 41);
contentPane.add(btnPlaySound);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Translate")) {
String text = textPane.getText();
String translatedText = MorseTranslate.doMorse(text);
textArea.setText("");
textArea.setText(translatedText);
}
}
}

This does not seem to be happening with my code, and it appends the new text to the text already in the area
So based on this code...
String text = textPane.getText();
String translatedText = MorseTranslate.doMorse(text);
textArea.setText("");
textArea.setText(translatedText);
I would suggest that the problem is with your MorseTranslate.doMorse which is probably returning the text appended to itself
But, as you can see, this is a matter of "guess work" as we don't have the complete code to go by.
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses

Try to reverse the order like this:
textArea.setText(translatedText);
textArea.setText("");
Use either textArea.setText(null) or textArea.setText("") are the same thing.

I think setText() replaces the content (not append), so you don't need to do setText("") and then setText("the text you want"), the latest sentence should be enough.

setText("") doesn't clear the text
Yes it does.
textArea.setText("");
Here you are clearing the text area.
textArea.setText(translatedText);
Here, in the very next line, you are setting it to something else.

You could alternatively try:
textArea.setText(null);
See if that works. But I agree with Wyatt, you are setting other text right after clearing it.

Have you inserted a simple print statement to see what textPane.getText() is actually setting String text to before sending it to doMorse(String)?

Related

JTextPane not updating on JButton press

I am currently having trouble with a JTextPane not updating when a JButton ActionListener is telling it to update. In the code, I have a button that assigns a selected value from a JList to a global variable.
This process works because when I print out the variable when I press the button it prints the selected value in a list. However, when I push the button I also want that variable to populate the text pane so I know what value I am working with when using the UI. Does anyone know what might help with this?
I will try to get the relevant code from my large JavaSwing script as I'm using Eclipse WindowBuilder and it throws everything in the source in whatever order I created it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class MainMappingGui extends JFrame {
private JPanel contentPane;
String attSelected = "Hello";
String attButSelect = "";
JTextPane textPaneEdits;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMappingGui frame = new MainMappingGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainMappingGui() {
setTitle("Data Mapping");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1105, 892);
contentPane = new JPanel();
contentPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnConfigMap = new JButton("Configure Mapping");
btnConfigMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
attButSelect = attSelected;
System.out.println(attButSelect);
textPaneEdits.repaint();
textPaneEdits.revalidate();
}
});
btnConfigMap.setFont(new Font("Tahoma", Font.PLAIN, 9));
btnConfigMap.setBounds(206, 406, 122, 23);
contentPane.add(btnConfigMap);
textPaneEdits = new JTextPane();
textPaneEdits.setBounds(634, 38, 314, 357);
textPaneEdits.setEditable(false);
textPaneEdits.setText("Current Output Column: " + attButSelect);
contentPane.add(textPaneEdits);
}
}
For this example, please assume that attSelected is a value that changes dynamically with a ListSelectionListener and works properly for selected values in a list. I have set it to "Hello" for simplicity sake.
As the one of the comments says, you have to manually change the text in the text pane.
btnConfigMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
attButSelect = attSelected;
textPaneEdits.setText(attButSelect);
}
});
Repaint and revalidate are not necessary.

Printing JTextField gives out a blank on console

I am new to Java and have just tried out Java's swing, I tried making a log in form that would print the content of a JTextField to the console, but the console doesn't show anything when I tried it.
Here's my code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class JavaTextField {
private JFrame frame;
private JTextField text1;
private JTextField text2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTextField window = new JavaTextField();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JavaTextField() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
text1 = new JTextField();
text1.setBounds(114, 38, 122, 40);
frame.getContentPane().add(text1);
text1.setColumns(10);
String majorText = text1.getText();
text2 = new JTextField();
text2.setBounds(114, 117, 86, 20);
frame.getContentPane().add(text2);
text2.setColumns(10);
String minorText = text2.getText();
JButton btnButton = new JButton("Button");
btnButton.setBounds(132, 192, 159, 40);
frame.getContentPane().add(btnButton);
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(majorText);
System.out.println(minorText);
}
}
);
}
}
I'm glad if anyone could point me in the right direction, because I haven't seen the solution to this problem on the internet yet.
The issue here is, that you retrieve the content from the JTextFields at the wrong time. Currently you call getText() right when the components are being initialized. Of course, the content returned from getText() will be an empty String.
So to fix the issue in your logic, you should actually retrieve the majorText and minorText from the JTextFields only once your JButton has been pressed. Because at that point in time, when your button is pressed, the content of your text fields should be correct. To do that, move the retrieval of the text to the ActionListener.
The updated ActionListener should look as follows:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String majorText = text1.getText();
String minorText = text2.getText();
System.out.println(majorText);
System.out.println(minorText);
}
}
or simply:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(text1.getText());
System.out.println(text2.getText());
}
}
Sidenote (as also mentioned by the other answer):
Using null layout is highly discouraged, as it is a frequent source for unnecessary errors. Have a look at the different LayoutManagers available and how and when to use them.
There are some improvements to do in your code:
Avoid the use of null-layout and setBounds(...), see why should you avoid it and a graphic example along with a suggestion to fix it by using layout managers
Your majorText is getting the text BEFORE you click on the button, and by that time it's empty and never update it, you need to get the text on button click, so move this line:
String majorText = text1.getText();
Inside your actionListener, same thing for minorText
And if you tagged your question with Java 8, then you could rewrite your listener using Java 8 lambdas
btnButton.addActionListener(e -> {
String majorText = text1.getText();
String minorText = text1.getText();
System.out.println(majorText);
System.out.println(minorText);
}

Currency Exchange API Java GUI

I am fairly new to programming of this level and I was wondering if someone could help me with this.
So I am trying to create a currency exchange app using Java, and I have a problem updating the values on the GUI to reflect the new value on the API. Essentially ever so often the values change and it shows on the console, however, the GUI value never updates and stays the same.
I thought ActionListener would help solve this problem but either I have not implemented it properly or I haven't googled and come up with a solution properly.
Thank you in advance for any help :)
Here is my code:
GUI.java
public class GUI extends JFrame {
static Arb arb = new Arb();
private JPanel contentPane;
public static void main(String[] args) throws IOException, InterruptedException {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
arb.runUpdate_fx("anAPI");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(5000);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1121, 765);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTextPane FXRate = new JTextPane();
FXRate.setForeground(new Color(255, 255, 255));
FXRate.setBackground(new Color(0, 0, 0));
FXRate.setEditable(false);
FXRate.setFont(new Font("Tahoma", Font.BOLD, 11));
panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
FXRate.setText("FX Rates\r\n\r\nEUR-AUD FX Rate: " + arb.fxEURAUD + "\r\nEUR-USD FX Rate: " + arb.fxEURUSD);
panel_1.add(FXRate);
}
}
Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.646659
Expected Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.80102
References are passed by value in Java.
JTextField textField = new JTextField();
String text = "Initial text";
textField.setText(text); // no displays "Initial text";
text = "Updated text"; // doesn't change what the panel displays
// the panel still holds a reference to the old text
textField.setText(text); // updates the reference the panel holds to your new text
In your event listener, you need to call setText with the updated string to actually make the textfield display that.
Your timer and event handler look good, but the update method only fetches new values into the Arb object; nothing takes those values and puts them into the GUI. You can do that explicitly in your event handler.after the update method returns. To enable that, you may want to make FXRate a member variable, so you can access it from the action listener.

How to store and display user input in JList?

I don't know what I am doing wrong. I am trying to take a JTextField user input to be stored and displayed in a JList, but every time the button is pressed to store the user input the JList remains blank. Any help would be greatly appreciated.
DefaultListModel<String> model = new DefaultListModel<String>();
menuList = new JList<String>(model);
menuList.setBounds(500, 65, 300, 400);
menuList.setSelectionBackground(Color.LIGHT_GRAY);
menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
btnCreateMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
childFrame = new JFrame("New Menu");
childFrame.setBounds(340, 300, 400, 200);
childFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
childFrame.getContentPane().setLayout(null);
childFrame.setVisible(true);
lblNewMenu = new JLabel("Menu Name:");
lblNewMenu.setBounds(30, 60, 200, 20);
childFrame.getContentPane().add(lblNewMenu);
input = new JTextField();
String userInput = input.getText();
input.setBounds(lblNewMenu.getX() + 80, lblNewMenu.getY(), 250, 30);
childFrame.getContentPane().add(input);
btnMenuInput = new JButton("Create New Menu");
btnMenuInput.setBounds(120, 100, 200, 30);
btnMenuInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.addElement(userInput);
menuList.setModel(model);
childFrame.setVisible(false);
Entree selectedEntree = (Entree)cboEntrees.getSelectedItem();
Side selectedSide = (Side)cboSides.getSelectedItem();
Salad selectedSalad = (Salad)cboSalads.getSelectedItem();
Dessert selectedDessert = (Dessert)cboDesserts.getSelectedItem();
Menu menu = new Menu(userInput, selectedEntree, selectedSide, selectedSalad, selectedDessert);
menuArray.add(menu);
}
});
childFrame.getContentPane().add(btnMenuInput);
}
});
mainframe.setVisible(true);
This line
userInput = input.getText();
needs to be called first in the ActionListener. Otherwise you never get the latest String from the text field.
e.g.,
public void actionPerformed(ActionEvent e){
userInput = input.getText();
model.addElement(userInput);
//menuList.setModel(model); // not needed
Also, as mentioned by camickr in comment, avoid using null layouts and setBounds as this fights against the Swing GUI library rather than working with it, making it much harder to create flexible easy to update and edit GUI's.
Also, the childFrame top-level window should be a JDialog and not a second JFrame. Please see The Use of Multiple JFrames: Good or Bad Practice? for more on this.
Also note that you should create the entire dialog or Frame before you make it visible, or else some of the items may not be visible at first.
Another problem is the use of JFrame.HIDE_ON_CLOSE. You should probably be using DISPOSE_ON_CLOSE instead. Otherwise the frame will just be hidden, but will still exist, possibly for the life of the program.

Java Swing JTextField.getText is not returning anything [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For some reason getText is not working for a text field.
Perhaps I am doing something wrong with this.
private JTextField txtTemp;
txtTemp = new JTextField();
txtTemp.setBounds(350, 57, 86, 20);
mainPanel.add(txtTemp);
txtTemp.setColumns(10);
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
Nothing is being printed when something is typed in the text box.
I also did it with using an action listener. Load the program, and have the user add some text.
btnTest = new JButton("TEST");
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
}
});
Still returns blank.
Any ideas?
"Nothing is being printed when something is typed in the text box."... "Still returns blank."
Sounds like you want something to happen whenever the text field is being type into. For that we would use a DocumentListener, which listener for changes in the underlying Document of the text field.
final JTextField field = new JTextField(20);
field.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) { printText(); }
#Override
public void removeUpdate(DocumentEvent e) { printText(); }
#Override
public void changedUpdate(DocumentEvent e) { printText(); }
private void printText() {
System.out.println(field.getText());
}
});
See more explanation at How to Write a Document Listener
Aside, if you want something to happen when the use type enter, then add an ActionListener to the text field.
Your JTextField seems empty, as long as you dont give any input, however common mistakes may be:
is it editable?
txtTemp.setEditable(true);
any text added?
public void changeTxtField(String text)
{
txtTemp.setText(text);
System.out.println(text);
}
your code looks fine so
Don't also do it 'also in the Action Listener' , DO it only in the ActionListener ?
I have no idea where you are going wrong , are you expecting the output on the GUI screen ?if so you are mistaken , look into the terminal...
Here I just tried and it perfectly works , it prints the user input text after clicking the button onto the terminal ,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TestText{
public static void main(String[] args)
{
JFrame frame=new JFrame("TextFieldTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel=new JPanel();
JTextField txtTemp;
txtTemp = new JTextField();
txtTemp.setBounds(350, 57, 86, 20);
mainPanel.add(txtTemp);
txtTemp.setColumns(10);
JButton btnTest = new JButton("TEST");
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
}
});
frame.add(BorderLayout.SOUTH,btnTest);
frame.add(mainPanel);
frame.setSize(600,600);
frame.pack();
frame.setVisible(true);
}//main ends
}//class ends
I ended up figuring out this issue.
At the top if i declare and Instantiate the object it works.
private JTextField txtTemp = new JTextField();

Categories