How to save multiple text input in different .txt file - java

I have made a program, which allows users to have as many text boxes as they want in which they can input a text string. I want to save each user input into different variables. I also want to print all of those variable or access the data stored in them when ever I want.
If you can help me that it would be really nice, thanks in advance. If you have any question please let me know in comment and I will answer them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public GUI()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add Another");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate();
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new GUI().displayGUI();
}
});
}
}

What you're looking for is an ArrayList<String>.
Declare a private ArrayList<String> userStrings; where you have your private fields.
In your constructor, add userStrings = new ArrayList<String>();
And then when you receive a string, just add it into your list with userStrings.add(myNewString). (Use your String instead of myNewString)
ArrayLists are indexed like an array, but using a method get, so you can get the first item in your list by using userStrings.get(0).

Related

When using JPanels in java how can you display user input data in one class to another

I've been having some difficulty with this. Basically I want a user to enter a name in one Java class and have that data displayed in another. I try using gets but I keep getting 'null'. Also how would you do this if I wanted to get an int from my class (exampl) to display in my second class. Would it basically be the same?
Here's an example to show what I mean
1st class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exampl extends JFrame implements ActionListener {
JLabel intro = new JLabel("Welcome What is your name?");
JTextField answer = new JTextField(10);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
String name = answer.getText();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Exampl() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(intro);
add(answer);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "Hello there" + name;
greeting.setText(greet);
add(next);
next.addActionListener(this);
if(source==next)
dispose();
new Hello();
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
2nd class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hello extends JFrame implements ActionListener {
String name;
JLabel hi = new JLabel("Nice to see you "+name);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
public Hello() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(hi);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "example " + name;
greeting.setText(greet);
add(next);
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
My recommendations for you:
Don't extend JFrame, instead extend JPanel. See: Extends Frame vs creating it inside the program and Why shouldn't you extend JFrame and other components
Don't use multiple JFrames. See The use of multiple JFrames, good / bad practice? (BAD) instead you might want to try using Card Layout or JDialogs
What do you mean by extend? do you mean "public class Hello extends Exampl"? I'm new to java so I don't know much.
From that comment on another answer, you might want to learn the basics first in console applications before going into a GUI application which adds more complexity to your programs and thus your learning.
I'm planning on doing a project where I add the inputted name and a random int into a file so I can store it. Or would it make more sense to add that code into the same class?
From that comment, you can create a public method which returns the value in a JTextField in the format you need, then call that method from the other class, for example:
public String getUserName() {
return userNameField.getText();
}
public int getDigit() {
try {
return Integer.parseInt(digitField.getText());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return -1; //In case it's not a number, or return 0, or whatever you need
}
//------In another class------//
int digit = object1.getDigit(); //Where object1 is an instance of the other class where those methods are defined
Make a getter in first class and extends second one class then use super.getter();

I'm trying to make a button to count characters in a text field

I'm trying to use the JButton count to count the number of characters entered into the JTextField t. I'm new to Java and GUIs but here's my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends Frame implements ActionListener{
TextField t;
Button count;
int a;
Choice choice;
public GUI1(){
this.t = new TextField("", 30);
this.count = new Button("count");
this.count.addActionListener(this);
JTextField x = new JTextField();
x.setEditable(false);
this.setTitle("Character count");
this.setLayout(new FlowLayout());
this.add(x);
this.add(t);
this.add(count);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()== this.count)
t.setText(choice.getSelectedItem()+ " " +a);
}
I'm also trying to enter the value in another uneditable JTextField x. Any help is appreciated.
Add this to your code
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = t.getText().length();
}
});
OR
You can use lambda expression like this
count.addActionListener(e -> a = t.getText().length());
For More
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You need to add a listener
TextField t = new TextField();
Button b = new Button("Count");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
}
});
You can read more about here
http://www.tutorialspoint.com/awt/awt_button.htm
First of all, I recommend you not to use AWT elements, since it brings tons of problems and it has little to no support, instead you can try using Swing components which are a replacement/fix for AWT. You can read more about here. You might also want to read AWT vs Swing (Pros and Cons).
Now going into your problem:
You should avoid extending from JFrame, I might recommend you to create a new JFrame object instead. Here's the reason to why. That being said, you can also remove all your this.t and other calls with this.
I'm glad you're using a Layout Manager!
And now to count the number of characters on your JTextField and set text to your other JTextField you should use this code:
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
Also I fixed your code, I changed AWT elements to Swing ones and added number of cols to your second JTextField so it would appear.
So, here's a running example that I made from your code (And removed Choice choice line since you didn't posted that code):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 {
JTextField t;
JButton count;
int a;
JFrame frame;
public GUI1(){
frame = new JFrame();
t = new JTextField("", 15);
count = new JButton("count");
JTextField x = new JTextField("", 15);
x.setEditable(false);
count.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int count = t.getText().length();
System.out.println(count);
x.setText(t.getText());
}
});
frame.setTitle("Character count");
frame.setLayout(new FlowLayout());
frame.add(x);
frame.add(t);
frame.add(count);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
new GUI1();
}
}
When you click on a button you should
String str = t.getText(); // get string from jtextfield
To save the text from the texfield. Then you can use something like:
a = str..length(); // get length of string
x.setText(str + " " + a); //set it to the field
To set it to the JTextField.

Add Integer to JList in java

Im making a jframe with two components. A list and a button. The list starts at 0 and everytime i press the button it increases by 1. So if i press the button, the value in the jlist changes from 0 to 1.
My question is, how can I add an integer to a jlist? (i tried the setText method just in case - only works for Strings)
Thanks
EDIT: PART OF MY CODE (ActionListener)
increase.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
counter++;
System.out.println(counter);
listModel.addElement(counter);
// listModel.clear();
}
});
I'm assuming that you want to add an int item to the JList, meaning a new int pops up in the list's display each time the button is pushed. You can create a JList<Integer> and add Integers (or boxed ints) to the JList's model, usually using listModel.addElement(myInteger).
If you need to clear previous elements, do so before adding the element, not after. For example,
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Foo2 extends JPanel {
private DefaultListModel<Integer> dataModel = new DefaultListModel<>();
private JList<Integer> intJList = new JList<>(dataModel);
public Foo2() {
add(new JScrollPane(intJList));
intJList.setFocusable(false);
add(new JButton(new AbstractAction("Add Int") {
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
dataModel.clear(); // if you need to clear previous entries
dataModel.addElement(count);
count++;
}
}));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Foo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Foo2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Gui where you can paste a text with a lot of lines

I would like to make a gui where after i click a button i can paste a text with a lot of lines and submit that text.
Example of the code i have for create the button:
public class SimpleGui implements ActionListener {
JButton button;
SimpleGui g;
public static void main (String[] args) {
SimpleGui g = new SimpleGui();
g.go();
}
public void go(){
JFrame frame = new JFrame();
button = new JButton("Insert Player");
frame.getContentPane().add(button);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
button.setText("Now paste the data! ");
}
}
Now where i have button.setText("Now paste the data! ");, what i want is to:
Create some kind of widget that allow me to insert 20 lines of text i've copied from a .txt document.
2) receive and manage the data that the user did put on the widget.
Can you help me?
Though your question is unclear but probably you're asking about a component where you can set your text. Use JTextArea as follows:
JTextArea textarea = new JTextArea("The initial text");
your_container.add(textarea);
Then whenever you want to get the text from your text area, use:
String data = textarea.getText();
If at runtime you want to set the textarea to some data you can:
textarea.setText("Your data here");
EDIT :
After the OP added the code, I think this is what he wants to achieve:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class SimpleGui implements ActionListener
{
JButton button;
SimpleGui g;
JTextArea textarea;
JFrame frame;
String data;
public static void main (String[] args)
{
SimpleGui g = new SimpleGui();
g.go();
}
public void go()
{
frame = new JFrame();
button = new JButton("Insert Player");
textarea = new JTextArea("Paste data here!");
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Insert Player"))
{
button.setText("Now paste the data!");
frame.getContentPane().add(textarea, BorderLayout.CENTER);
}
else if(e.getActionCommand().equals("Now paste the data!"))
{
data = textarea.getText();
System.out.println(data);
}
}
}
Your text data is in the data variable. You can use it as you like. I've simply demonstrated that by printing it.

how to remove lines one by one from a JTextArea

How can i remove lines from a JTextArea one by one instead of all together?
I have a JTextArea which gets appended with string results from a thread, now i would like to remove one line at a time while the thread is executing.
You first need to decide what should trigger the line removal.
Should it be the addition of a new line, so that total line number is constant. If so then you should write your code to call the line removal code in the same location that where a new line is added.
Or should it be at a constant rate -- and if so, then you will want to use a Swing Timer for this.
Then you need to decide which line to remove. If not the first line, then you'll need to figure out how to calculate which line. The javax.swing.text.Utilities class can help you find out the start and finish location of every line of text in your JTextArea.
Edit
You ask:
the main concern is about how to remove it from the JTextArea, i have already calculated the start and end positions of a line that has to be deleted.But what function can assist in removing just that one line?
You would first get the JTextArea's Document by calling, getDocument()
Then you could call remove(int offs, int length) on the Document as per the Document API.
Try This :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SwingControlDemo {
String [] m;
int i=0;
String append="";
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
Timer t;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo(){
headerLabel.setText("Control in action: JTextArea");
JLabel commentlabel= new JLabel("Comments: ", JLabel.RIGHT);
final JTextArea commentTextArea =
new JTextArea("This is a Swing tutorial "
+"\n to make GUI application in Java."+"\n to make GUI application in Java"+"\n to make GUI application in Java",5,20);
JScrollPane scrollPane = new JScrollPane(commentTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s=commentTextArea.getText();
m=s.split("\n");
t.start();
}
});
t=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
i++;
append="";
if(i<=m.length)
{
for(int j=i;j<m.length;j++)
{
append=append+m[j];
}
commentTextArea.setText(append);
}
else
{
t.stop();
}
}});
controlPanel.add(commentlabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}

Categories

Resources