I need help regarding my java GUI, I have a jform to add movie details into a textfile add movie into textfile
when I add the data and click the save button it will automatically print on the textfile file that has been declared inside the code.
now I am creating another jform to display a specific data that has inside the textfile into a jtextfield. However, I can't seem to have any idea on how to do it. can anyone guide me through this?
display textfile into jtextfield
This is my code to display the added movie into the jtable
float subPrice,totalPrice,tax;
int stockqty = Integer.parseInt(stock.getText());
float priceUnit = Float.parseFloat(unitP.getText());
subPrice = priceUnit*stockqty;
tax = (float) (subPrice*0.60);
totalPrice = subPrice+tax;
MovieInventory.AddRowToJTable(new Object[]{
movieID.getText(),
movieName.getText(),
yearR.getText(),
language.getText(),
genre.getSelectedItem(),
rated.getSelectedItem(),
duration.getText(),
type.getSelectedItem(),
stock.getText(),
unitP.getText(),
subPrice,
totalPrice,
});
JOptionPane.showMessageDialog(this, "Movie Add Succesfully!");
}
For the save button this is my code to save the data that has been put inside jtable into the textfile.
String filePath = "/Users/finatasha/Documents/inventoryMovie.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i <jTable1.getRowCount(); i++){
for(int j=0; j< jTable1.getColumnCount(); j++){
bw.write(jTable1.getValueAt(i, j).toString()+" ,");
//using comma to seperate data
}
bw.newLine();
}
bw.close();
fw.close();
JOptionPane.showMessageDialog(this, "Data save to textfile successfully!");
} catch (IOException ex) {
Logger.getLogger(MovieInventory.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "ERROR!");
}
Related
how can I write multiple lines so that I am able to record all achievements without overwriting the content? Thank you.
private void view_btnActionPerformed(java.awt.event.ActionEvent evt) {
try{
FileWriter FW = new FileWriter(""+StudRecord+"/"+LRN_Field.getText()+".txt");
System.out.print(achievement_Field.getText());
FW.write(""+achievement_Field.getText()+"");
JOptionPane.showMessageDialog(this, "Achievement Added");
achievement_Field.setText(" ");
FW.close();
}catch(Exception e){
System.out.print((e));
}
}
THE GUI IM WORKING ON
You are opening the file for writing, and your text will be the content of the file. Instead, open the file for appending.
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/FileWriter.html#%3Cinit%3E(java.io.File,boolean)
Im making a medical resource management system and i am using a text file to import the first set of Doctors. This is working fine and i have added the ability to remove a selected row, which is also working. However i want this change to become permanent and save on the text.
When i press my save button on the Java GUI i just clears the entire text file. I also have the ability the add separate doctors which is also working correctly. Any help would be appreciated. Below is my code for exporting the Jtable to the text file!
private void jButtonSaveActionPerformed(java.awt.event.ActionEventevt)
{
String filePath = "C:\\Users\\Stephen\\folder\\Programming
Assignment copy\\doctor.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < jTableDoc.getRowCount(); i++){//rows
for(int j = 0; j < jTableDoc.getColumnCount(); j++){//columns
bw.write(jTableDoc.getValueAt(i, j).toString()+",");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(doctorTable.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}
So I'm coding a program in Java that allows me to create teams (also remove them and edit them).
After creating a team the program enables the user to add 10 players, define their weight and tries scored and once again remove and edit them. Now as soon as they reach 10 players they lose the ability of adding more and a save button is enabled.
The problem I'm having is: if I save a team and then edit it or remove it and I try to save it again, the table creates another column and moves all the values one column to the right. The images will illustrate a bit better what I mean.
When saved for first time:
After saving 2nd time:
The code for the saving function is at follows:
private void btn_SaveTeamActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel pattern = (DefaultTableModel) table_PlayerBoard.getModel();
try {
saveTable((String) table_LeaderBoard.getValueAt(table_LeaderBoard.getRowCount() - 1, 0));
} catch (Exception ex) {
Logger.getLogger(Mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
enableTeamEdit();
btn_SaveTeam.setEnabled(false);
JOptionPane.showMessageDialog(null, "Team Saved");
pattern.setRowCount(0);
btn_RankTeams.setEnabled(true);
counter = 0;
}
ArrayList <Integer> triesList = new ArrayList();
ArrayList <String> teamList = new ArrayList();
boolean check = false;
I can't really understand where is the mistake. If there is any more information needed let me know. Thanks in advance.
saveTable method:
public void saveTable(String fileName)throws Exception {
DefaultTableModel chart = (DefaultTableModel) table_PlayerBoard.getModel();
BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt"));
System.out.println(fileName);
for (int i = 0 ; i < chart.getRowCount(); i++)
{
for(int j = 0 ; j < chart.getColumnCount();j++)
{
bfw.write((chart.getValueAt(i,j).toString()));
bfw.write("\t");;
}
bfw.newLine();
}
bfw.close();
}
In your saveTable(...) method, simply delete the contents of the given file, then open a new one for writing like this:
String path = "C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt";
File file = new File(path);
file.delete();
file = new File(path);
BufferedWriter bfw = new BufferedWriter(new FileWriter(file));
My code is when user type in the Name text filed, it will export as text file and record the Name.
For example,
I typed 1st time "James" in the Name text filed, it will appear
"James" in the text file. I type second time "Agnes" , it appears
"Agnes" in the text file. But It only appear one name in the text
file.
I want all the names appear whatever user type in the text filed.
How do i modify my codes?
try
{
new JTextField();
// create new file
String path="C:\\export.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
// bw.write(txtName.getText());
if (txtName.getText() ==null)
{
bw.write(txtName.getText());
bw.write('\n');
System.out.print("1st Name:" +txtName.getText());
}
else
if (txtName.getText()!=null)
{
// bw.write('\n');
bw.write(txtName.getText());
System.out.print("2nd Name:" +txtName.getText());
}
// close connection
bw.flush();
bw.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
Please advise.Thanks
You should use append mode when write file, like:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Edit again:
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
if (txtName.getText()!=null){
//this line edited
bw.write(txtName.getText()+"\n");
System.out.print("2nd Name:" +txtName.getText());
}
My app records sounds. Once the sound is recorded, user is asked to input a new file name. Now what I'm trying to do next is to add all file names in a text file so that I can read it later as an array to make a listview.
This is the code:
//this is in onCreate
File recordedFiles = new File(externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/recorded files.txt");
if(!recordedFiles.exists())
{
try {
recordedFiles.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//this executes everytime text is entered and the button is clicked
try {
String content = input.getText().toString();
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(">" + content + ".mp3");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Now the problem is that everytime I record a new file, the previous line is overwritten. So if I record two files 'text1' and 'text2', after I've recorded text1, the txt file will show text1, but after I recorded the text2, the text2 will overwrite the text1 instead of inserting a new line.
I tried adding:
bw.NewLine()
before
bw.write(">" + content + ".mp3");
but it doesn't work.
If I record three sounds and name them sound1, sound2 and sound3, I want this to be the result:
>sound1
>sound2
>sound3
Use FileWriter constructor with boolean append argument
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
// ^^^^
this will let file append text at the end instead overwriting previous content.
You can do it by adding line.separator Property
bw.write(">" + content + ".mp3");
bw.write(System.getProperty("line.separator").getBytes());
Replace
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
Instead of
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
FileWriter takes a boolean if it should overwrite. So use true if you would like to to append to the file instead of overwrite.