i want to do tokenize from textarea but i cannot call the textarea. the output cannot diplay.
Below is my program:
static JTextArea Report_tf;
public static void main(String[] args) throws IOException
{
new Form1(); //call form
//tokenization
String speech = Report_tf.getText();
Report_tf.setText(speech);
StringTokenizer st = new StringTokenizer(speech);
while (st.hasMoreTokens())
System.out.println(st.nextToken());
}
Is that what your code looks like, or is it facsimile of your code? I see a few problems in that small snippet:
There's no reason to have a static JtextArea field as this breaks OOP. Make it an instance variable of the class (I guess it's the Form1 class).
Where do you construct your JTextArea variable? As written it appears to be null and will throw a NullPointerException if you try to use it.
If you're trying to extract your text from the JTextArea from the main method as you indicate, you're doing this at program start up, before the user has had any time to enter data into the JTextArea which makes little sense. Much better is to get the text in response to an event such as inside of a JButton's ActionListener. This way, the user can enter text and then push the button when done, and your field will have text to extract.
Again, all of this should be not be done in the main or any static method but in a non-static method.
If this information doesn't help, you'll need to provide more information than you have, a lot more information and code.
Related
I'm trying to create a small program, where you have to guess words while you are shown a matching anagram. My code is like:
JFrame frame = generateJFrame(BACKGROUND, FOREGROUND);
JLabel display = generateDisplay(BACKGROUND, FOREGROUND);
Pair now = woerter.shuffle();
display.setText(now.getAnagram());
JTextField input = generateInputBox(BACKGROUND, FOREGROUND);
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nextWord(now, woerter, display, input);
}
};
input.addActionListener(action);
[...]
private static void nextWord(Pair now, Woerter woerter, JLabel display, JTextField input) {
if (now.getRealWord().equalsIgnoreCase(input.getText())) {
now = woerter.shuffle();
display.setText(now.getAnagram());
input.setText("");
}
}
Now when I execute it, it works the first time (when you type in the correct word and press enter a new anagram is displayed and the inputfield clears), but afterwards it breaks and enter doesn't do anything anymore.
What am I doing wrong? Any help would be appreciated.
Pair now = woerter.shuffle();
You are defining "now" as a local variable.
now = woerter.shuffle();
But you also reference it in your nextWord(…) method, which indicates you have also defined it as a static variable.
Don't define the variable twice. Get rid of the local variable:
//Pair now = woerter.shuffle();
now = woerter.shuffle();
Also, defining methods and variables as static indicates a poor design. Your nextWor() method should not be static and therefore the "now" variable will not need to be static.
Read the section from the Swing tutorial on How to Use Text Fields. The TextDemo code will show you how to better structure your code so that the ActionListener of the text field can access the text field and the rest of the data in your class.
So download the working demo code and modify it to meet your requirements.
I am trying to build a calendar app and use a memo section that I labeled notes. I have an add button to add a new note and I want it to add to the current file in the path. I am trying to use a BufferWriter to do this. I have attached the newNote() method that opens a new frame and allows for the new text. I think I am trying to append the new text to the current file but the examples I have seen shows to do it this way. The output of the txt file is not what I expected. I think it is due to calling the textArea object and it is pulling the data of the object and not the input inside the textArea. I am somewhat new to Java and am doing this project for personal use, not a class. Any help and insight would be appreciated. This is also my first time posting in a forum so please let me know if there is a better way of doing this.
The newNote() method.
public static void newNote() {//opens new frame to create a new note
//variables for the new window
JFrame noteFrame = new JFrame("New Note");
JPanel notePanel = new JPanel();
JButton cancelButton = new JButton("Cancel");
JButton addButton = new JButton("Add");
JTextArea textArea = new JTextArea("Add notes here");
//creates and positions buttons
addButton.setBounds(150,330,65,40);
addButton.addActionListener(new ActionListener() {//writes contents to a txt file when Add is clicked
#Override
public void actionPerformed(ActionEvent actionEvent) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter((new FileWriter("/home/skydawg/pCloudDrive/Documents/test/Log.txt", true)));
writer.write(String.valueOf(textArea));
writer.newLine();
writer.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (writer != null) try {
writer.close();
} catch (IOException ioe2) {
// just ignore it
}
noteFrame.dispose();//closes the frame
}}
});
The output to the txt file
newjavax.swing.JTextArea[,10,10,280x295,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder#13e59af,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.ColorUIResource[r=218,g=218,b=218],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=javax.swing.plaf.ColorUIResource[r=255,g=255,b=255],selectionColor=javax.swing.plaf.ColorUIResource[r=134,g=108,b=186],colums=0,columWidth=0,rows=0,rowHeight=0,word=true,wrap=true]
Here:
writer.write(String.valueOf(textArea));
the javadoc for that method:
Returns the string representation of the Object argument.
That doesn't do what you expect it to do. That is like calling textArea.toString() ... which again: doesn't give you the string content of your textArea.
Instead, you want to call textArea.getText(), and write that to your file.
Beyond that: you should not throw so many things together. Meaning: write a utility class that just writes some text to a file. Test that separately. And only when that part works, you put your GUI around that. Your approach is: throwing everything together, testing all at once. Which means that you run from one problem to the next. Don't do that. Slice your problem into many small parts, and think hard "how can i solve and test each part in isolation"!
Finally, as you have just seen: GUI programming and GUI components are complicated. Trying to learn these things by trial and error is a really inefficient strategy! It is really better to read a good book or tutorial (see for example). Start with working examples, instead of pulling together 5 different things that are all new to you! And most importantly: each time you use a new class you haven't studied before: take the time to read the corresponding javadoc. Top to bottom! You can invest that time upfront, or you can spend 1 hour not understanding what is going on, to then invest that time.
JTextArea extends JTextComponent. So you have a method called write(java.io.Writer writer).
That means, you can call textArea.write(writer) in your code.
New to asking questions here on stack overflow. I have a program that has me stumped. I have been able to get it to work but just not in the manner I would prefer and I was wondering if some of you could take a look at it and help me figure out what I am doing wrong. Please see below:
For the beginning, the program doesnt compile in class Output at
String ageStr = Input.getAge().toString();
int ageInt = Integer.parseInt(ageStr);
because getAge() returns the address, not the Text of JTextField. Integer can't parse that, as it inhabits not only integers.
And so does all your static getters only return not intended data.
Try to change those in class Input after this sample:
public static String getAge() {
return age.getText();
}
and don't forget to add the outputPanel in class Output
add(outputPanel, BorderLayout.CENTER);
Additionally,
make those methods non-static as stated by others
separate / encapsulate code into fitting methods and improve your API
keep an overall persistent code appearance.
One option is to define an object variable and change your Output-Constructor:
Input input; // keeps a ref to input
public Output(Input input) {
super("Output", 300, 300);
this.input = input;
String ageStr = input.getAge();
...
And the call to:
public void actionPerformed(ActionEvent e){
output = new Output(Input.this);
output.display();
...
Hope it helps you.
Ok here is what I changed, like I said I'm still getting an error. So far all I have tried to fix is the code associated with the age. I will work the rest when i figure out how to make this work. See new code below. I can get it to work if I leave everything static but I know that's not the appropriate method. Tried to fix the formatting as well.
I'm not looking for a complete answers just help on how to start it or maybe some references I could look at that may help me with this. Ok so I have to populate the JComboBox (accountnumber) from a text file. The txt files reads as:
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
It reads as acctNumber<>CustomerName<>openDate<>balance
How would I go about starting this? Which would be easiest to split the 4 variables. array/arraylist/hashmap etc.?
I'm not familiar with file I/O. and trouble with collections so this is the only part I'm stuck on.
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class AccountUtility {
List<String> accountsInfo = new ArrayList<>();
BufferedReader in;
File file = new File("accounts.txt");
public AccountUtility(){
ReadFile();
}
public void ReadFile(){
String nxtLine = " ";
try{
in = new BufferedReader(new FileReader(file));
while(nxtLine != null){
nxtLine = in.readLine();
accountsInfo.add(nxtLine);
}
for(String items : accountsInfo)
System.out.println(items);
in.close();
}catch(IOException ex){
}
}
public static void main(String[] args) {
AccountUtility ut = new AccountUtility();
}
}
so i decided to use a list , this is just my accountutility class I just added a mainmethod so i can test just this class and the result when i Run it comes to
1231<>Jack Williams<>2015/1/21<>463.02
1232<>Jane Brown<>2015/1/21<>13510.54
1233<>Paul Gonzales<>2015/1/22<>680.17
1234<>Jian Chen<>2015/1/22<>1117.54
1235<>Lily Makki<>2015/1/22<>1124.89
1236<>Michael Lopez<>2015/1/23<>800.0
1237<>Jose Alvarez<>2015/1/23<>607.21
1238<>Tina Lin<>2015/1/24<>11077.0
null
How do i split an list using a delimiter?
You're primary identifier is the account number, from this you need to be able to ascertain the account details.
This would lead me to use some kind of Map.
I would then create an Account class which held all the information in a simple, easy to use class, which provided appropriate setters and getters.
This would then lean me to the fact that I wouldn't actually need the Map, because all the information I need was in the Account class, so instead, I would simply create a ListCellRenderer for the combo box that would be capable of taking the account number from an instance of the Account class and display it appropriately...
This would mean I'd only need a List or a ComboBoxModel to hold the account details
Take a closer look at How to Use Combo Boxes for more details
To display an Object, Swing components will use the toString() method the Object placed in it.
One approach is to create a Data class that holds the name, ID, etc., implement toString() to display what you want (in your case, the Account Number), and then put a list of these objects in your JComboBox.
Then on change of selection in the combo, get the selected item, cast it to the data class, and then call getDate(), getName(), etc. to populate the textfields.
If you want to actually show the extra details of the Customer in the combo (after all, who really knows the person by account number?), then take a look at one approach here:
DetailedComboBox
Justin, I'm in the same boat and created a similar program that reads from text file. There was an excellent given for cells (e.g. Excel or Sql), but need to have it read from a text file. I'm thinking:
String tmp [] = line.split ("<>");
this will output data from each break.
I've been looking all over, and i cant find anyone who can solve this problem. I'm making a game, and in that game, i have editable controls. the controls window is a seperate JFrame, and when i click the confirm button, it is supposed to write the items in the JTextFields (holding the controls) to a file. but that wasnt working, so instead i have it print the arraylist that holds the values. here is the code:
public void writeControls() {
ArrayList<String> al = new ArrayList<String>();
al.add(up.getText());
al.add(down.getText());
al.add(left.getText());
al.add(right.getText());
al.add(jump.getText());
al.add(duck.getText());
al.add(attack.getText());
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
System.exit(0);
}
the problem is this: if i change the final JTextField attack or any other one for that matter, and click submit, the system prints out the default controls. for example, if the JTextFields have the values w,a,s,d,r,t,q and i change the value q to i, it prints out q. what am i doing wrong? thanks in advance!
EDIT 1:
code for the textfields, and the FILES.... is simply a string stored in a different class. the class setText() is below the textfields.
up = new JTextField(setText(FILES.controlsFileFinalDir, 1));
down = new JTextField(setText(FILES.controlsFileFinalDir, 2));
left = new JTextField(setText(FILES.controlsFileFinalDir, 3));
right = new JTextField(setText(FILES.controlsFileFinalDir, 4));
jump = new JTextField(setText(FILES.controlsFileFinalDir, 5));
duck = new JTextField(setText(FILES.controlsFileFinalDir, 6));
attack = new JTextField(setText(FILES.controlsFileFinalDir, 7));
public String setText(String fileDir, int lineNum) {
String txt = "";
txt = io.readSpecificLine(fileDir, lineNum);
txt = switchCase(txt);
return txt;
}
switchcase() is only taking what you have written in the text file that these are getting the values from, and translating them. so if the value is 0, it is turned into Space, etc. io.readSpecificLine(); is only to get the line of text from the file. does this help?
EDIT 2:
i just was dinking around and found out that if i set the JTextField text by using setText(""); then use getText(); it works. so the problem is that when i change it manually, and use getText(); it wont work. Why?
To update the text to a currently existing JTextField, I would establish the JTextField as a class variable, and create a setter/getter method to adjust it (which I'm assuming you're doing).
According to your methods, you would use something like:
up.setText(setText(FILES.controlsFileFinalDir, 7));
Edit: **The first setText is the JTextField.setText, the second setText is your public method you posted. I'm assuming your second getText() isn't working because you're probably not setting the text correctly.
Without seeing more code, I can't really give a better guess.
The main possibilities:
(1) The text fields have their editable property set to false.
(2) You are creating multiple copies of the JTextFields, then editing a new one on the screen, but referring to the old one when you get the value.
(3) You have a ValueChanged or LostFocus event handler that is resetting the text fields to their defaults
(4) It is actually JFormattedTextField not a JTextField
If I was you, I would try to debug the programm. You will probably do some Mistake in your code, you won't be able to see, by just checking the code.
For example in which order do you call the functions and so on, maybe you have a fault here, or maybe you have several threads, so you try to read the Textfields without even set them and so on ... It's hard to say without reviewing the whole Code.
So if you use eclipse you can follow this link for an explanation on how to debug: http://www.vogella.com/articles/EclipseDebugging/article.html
Netbeans or any other IDE should support debugging as well.
This may seem like a strange thing to suggest, but I think this is an issue with pointers. If you create a new string before passing it in, JTextField will be able to change it internally and return what you expect when asked for the modified value.
down = new JTextField("" + setText(FILES.controlsFileFinalDir, 2));
// or
down = new JTextField(new String(setText(FILES.controlsFileFinalDir, 2)));
You might want to try the following:
create a class Test.java
import java.util.ArrayList;
import javax.swing.JTextField;
public class Test implements Runnable {
private ArrayList<JTextField> textFields = null;
private ArrayList<String> stringList = null;
public Test(ArrayList<JTextField> textFields, ArrayList<String> stringList) {
this.textFields = textFields;
this.stringList = stringList;
}
#Override
public void run() {
for ( JTextField textField : this.textFields )
this.stringList.add( textField.getText() );
}
}
and then, at the place where you use the "getText() method .. "
do the following...
ArrayList<JTextField> textFields = new ArrayList<JTextField>();
// add all the JTextField to textFields
ArrayList<String> stringList = new ArrayList<String>();
Test test = new Test( textFields, stringList );
SwingUtilities.invokeLater( test );
// check if the stringList is populated.
If this work, then what I believe is that, for some reason, the JTextField hasn't finished
"setting" the text, and before it finishes your getText() was called. I've had similar problems before, and this solved my problem that time, but still, this might not be the perfect solution.
First, you should change your "setText()" method name to something like "getTextFromFile()" it would be more readable
Then, if you are setting and reading the new text in different threads, my bet is that the setText() is taking long to return, because it is accessing the file system, while the method that read the values run instantly
I would try to do run a little test:
public void test(){ // must be run after the JTextFields be initialized
up.setText("TEST")
System.out.println(up.getText());
up.setText(setText(FILES.controlsFileFinalDir, 1));
System.out.println(up.getText());
}
If the test() prints the correct values, then we can assume that if you set and read the new value in the same thread it works fine
The other test I would do is:
public void testThread(){
new Thread(){
public void run(){
while(true){
if(up!=null){
System.out.println(up.getText());
}
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
It will print the value of up each 1 second, so that you can see if after some time you get the new value. If it does, then the answer is: Your setText() is taking long to run and you are reading the value before the new value is set
SOLUTION
none of the above answers were working for me, so i finally decided to just start over with that class. the few things i changed were the way i made the JTextFields. I made them as an array instead of individual objects. Second is the way i put what they say. When i initialized them, i was unable to get them to create WITH the text in the parameters. so i had to do that seperately. i changed some of the method names so as to reduce future confusion, and it worked! so im not sure what was up with that, maybe it was the way i did it, maybe just a fluke. it happens sometimes, so im sorry for the delay and waste of your time! thanks for all the answers anyway!
Try this:
textbox.setText(setFile(args)); // your function for set file