How do I add,remove and search for items in an arraylist when using GUI? I would like to add user input into the programs arraylist.
Also how do I CHECK TO SEE IF A FILE CALLED INFO.TXT EXISTS -- IF IT DOES -- SET ALL INFO IN info.txt FILE INTO TEXTAREA -- See below:
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.*;
import java.io.File;
import java.io.*;
import static java.lang.System.out;
public class FinalMainFrame extends
JFrame {
BufferedReader br = null;
private Container pane;
private JTextField textField;
public FinalMainFrame() {
pane=getContentPane();
pane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu();
JMenuItem menuFileExit = new
JMenuItem();
menuFile.setText("File");
menuFileExit.setText("Exit");
menuFileExit.addActionListener
( (ActionEvent e) -> {
FinalMainFrame.this.windowClosed();
});
menuFile.add(menuFileExit);
menuBar.add(menuFile);
setTitle("Final Project...");
setJMenuBar(menuBar);
setSize(new Dimension(250, 200));
JLabel label = new JLabel("Enter Info:");
label.setFont(new Font("Serif",
Font.PLAIN, 18));
pane.add(label);
label.setLocation(0, 10);
label.setSize(100, 30);
textField = new JTextField(20);
pane.add(textField);
textField.setSize(100, 30);
textField.setLocation(120, 10);
JButton button1 = new JButton("Save");
pane.add(button1);
button1.setLocation(30, 70);
button1.setSize(150, 50);
button1.addActionListener
(
new ActionListener() {
public void
actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
null,"You pressed: " +
e.getActionCommand() );
try{
FileReader read = new
FileReader("info.txt");
BufferedReader br = new
BufferedReader(read);
String txt = "";
String line = br.readLine();
while (line != null){
txt += line;
line = br.readLine();
out.println(line);
}
String text = textField.getText();
FileWriter stream = new
FileWriter("info.txt");
try (BufferedWriter out = new
BufferedWriter(stream)) {
out.write(text);
}
JOptionPane.showMessageDialog(
null,"You entered: " + text );
}
catch (Exception ex) {}
}
}
);
this.addWindowListener
(
new WindowAdapter() {
public void
windowClosing(WindowEvent e) {
FinalMainFrame.this.windowClosed();
}
}
);
}
protected void windowClosed() {
System.exit(0);
}
}
When talking about GUI you should think of events. So add user input to your arraylist on a click event or etc.
Related
I am outputting some logs into the a JTextArea enclosed in JScrollPane but the auto scrolling functionality when the output reaches the bottom of the textArea is not working. I have attempted several methods that I saw online but none works. Below is my part of my code so far.
JTextArea ouputLogPane = new JTextArea();
JScrollPane outputPane = new JScrollPane(ouputLogPane);
outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(75, 501, 746, 108);
contentPane.add(outputPane);
Now I in another class am reading from a source file and appending log details to the textArea using the code below.
public void readFile(JTextArea outputLog, JScrollPane scrollPane){
count = 0;
while(moreLinesToRead){
if(count % 100 == 0){
outputLog.update(outputLog.getGraphics());
outputLog.append("Completed Reading"+ count + " Records "\n");
DefaultCaret caret = (DefaultCaret)outputLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
outputLog.update(outputLog.getGraphics());
//tried the one below but did not work either
//outputLog.setCaretPosition(outputLog.getDocument().getLength());
}
count++;
}
}
Finally I am calling this method in the when a button is clicked as below.
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
migrationUtil.readFile(ouputLogPane,outputPane);
}
});
So basically the complete output prints only after the execution finished. I read that I might have to use a separate thread to handle it but not very sure on how to proceed.
EDIT
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class ReadingExample extends JFrame {
private JPanel contentPane;
private Connection conn;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadingExample frame = new ReadingExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ReadingExample() {
//setResizable(false);
setFont(new Font("Dialog", Font.BOLD, 13));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 936, 720);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0), 2));
setContentPane(contentPane);
contentPane.setLayout(null);
final JTextArea ouputLogPane = new JTextArea();
final JScrollPane outputPane = new JScrollPane(ouputLogPane);
//outputPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
outputPane.setBounds(67, 189, 746, 108);
contentPane.add(outputPane);
JButton btnNewButton = new JButton("Start Reading");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File file = new File("file.txt");
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
try {
while((line = bufferedReader.readLine()) != null) {
ouputLogPane.append(line + "\n");
ouputLogPane.setCaretPosition(ouputLogPane.getDocument().getLength());
try {
Thread.sleep(200);
} catch (InterruptedException ee) {
ee.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(358, 620, 167, 29);
contentPane.add(btnNewButton);
//JPanel panel_3 = new JPanel();
//panel_3.setBorder(new TitledBorder(null, "Process Log", TitledBorder.LEADING, TitledBorder.TOP, null, null));
//panel_3.setBounds(57, 173, 769, 132);
//contentPane.add(panel_3);
}
}
What you want to do is read the file in a separate thread, so that your Swing thread is not blocked by it, allowing you to update the text area at the same time.
You still need to update the GUI on the Swing thread however, so you do this by calling SwingUtilities.invokeLater(runnable).
Here is a working example (Note I added a Thread.sleep(200) so you can see it being updated):
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class ReadingExample {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
JTextArea jTextArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(jTextArea);
scrollPane.setPreferredSize(new Dimension(300, 300));
mainPanel.add(scrollPane, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Start Reading");
mainPanel.add(btnNewButton, BorderLayout.SOUTH);
jFrame.setContentPane(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
btnNewButton.addActionListener(e -> {
new Thread(() -> {
File file = new File("file.txt");
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while((line = bufferedReader.readLine()) != null) {
final String fLine = line;
SwingUtilities.invokeLater(() -> {
jTextArea.append(fLine + "\n");
jTextArea.setCaretPosition(jTextArea.getDocument().getLength());
});
Thread.sleep(200);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}).start();
});
}
}
There are two ways to scroll to the bottom. You can manipulate the scroll bar:
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getMaximum());
Or, you can use the more reliable scrollRectToVisible method:
try {
textArea.scrollRectToVisible(
textArea.modelToView(
textArea.getDocument().getLength()));
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
I want to make the result of my buffered reader to appear in a text area, but It doesn't work for me.
I want the text area to get the result exactly as the system out print do, it is for more than one line, I tried to set the text area with string s but didn't work, just give me the result of one line.
Here is my Code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.ScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Window extends JFrame {
/**
* Launch the application.
* #throws FileNotFoundException
*/
public static void main(String[] args) {
Window frame = new Window();
frame.setTitle("SWMA Extractor");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setBounds(50, 50, 665, 550);
//frame.setLocation(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(null);
}
/**
* Create the frame.
*/
public Window() {
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel path = new JLabel("File Location");
path.setHorizontalAlignment(SwingConstants.CENTER);
path.setBounds(20, 11, 74, 23);
contentPane.add(path);
final JTextField location = new JTextField();
location.setBounds(104, 12, 306, 20);
contentPane.add(location);
location.setColumns(10);
final JTextArea textArea = new JTextArea();
ScrollPane scrollPane = new ScrollPane();
scrollPane.setBounds(20, 80, 605, 430);
contentPane.add(scrollPane);
scrollPane.add(textArea);
JButton btn = new JButton("Get Info.");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
File output = null;
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
int lineNumber = 1;
while((s = br.readLine()) != null) {
if (s.contains("System")) {
System.out.println(s);
String nextLine = br.readLine();
System.out.println(nextLine);
String nextLine1 = br.readLine();
System.out.println(nextLine1);
String nextLine2 = br.readLine();
System.out.println(nextLine2);
String nextLine3 = br.readLine();
System.out.println(nextLine3);
System.out.println();
}
}
lineNumber++;
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
btn.setBounds(433, 11, 192, 23);
contentPane.add(btn);
JButton clr = new JButton("Clear");
clr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getLocation = location.getText();
String s;
try {
textArea.setText("");
location.setText("");
} catch (Exception e1) {
}
}
});
clr.setBounds(20, 45, 605, 23);
contentPane.add(clr);
}
}
I see you say you tried setting the text, but the setText method actually replaces the whole current text with the new one:
JTextComponent #1669:
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
You should use insert or append methods:
Replace
System.out.println(s);
with
textArea.append(s);
Also, check the following question for a better way of doing this:
Opening, Editing and Saving text in JTextArea to .txt file
private void fileRead(){
try{
FileReader read = new FileReader("filepath");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp = scan.nextLine() + System.lineSeparator();
storeAllString = storeAllString + temp;
}
}
catch (Exception exception) {
exception.printStackTrace();
}
}
#Hovercraft's suggestion is very good. If you don't want to process the file in any way, you could directly read it into the JTextArea:
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
textArea.read(br, "Stream description");
} catch (IOException e2) {
e2.printStackTrace();
}
I'm still new to java, so dumb question is coming. I've been working on a simple software using JFrame, PrintWriter, File, and Scanner to create and read a text file, I save the file with the name you typed and then with the data you input into a JTextField, the problem is: As soon as you type one space it doesn't save the text after the space to the .txt file:
Input
waitFor it
WriteToFile(textarea.getText(), name.getText());
// my function input text name
Output:
waitFor
But if I input the text manually this way:
WriteToFile("waitFor it", name.getText());
// my function input text name
Output:
waitFor it
Which leads me to think that my function might not be causing this, but again I'm a noob.
Main.java
package creator;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import library.Database;
public class Main extends Database{
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton button = new JButton("Erase");
JButton button2 = new JButton("Add");
JButton button3 = new JButton("Save to Database");
Font font = new Font("Courier", Font.BOLD, 12);
Font font2 = new Font("Courier", Font.BOLD, 14);
final JTextField name = new JTextField();
final JTextField editorPane = new JTextField();
final JTextField textarea = new JTextField();
final JScrollPane scroll = new JScrollPane (textarea,
JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setTitle("Array Creator");
frame.setSize(401, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setLayout(null);
frame.add(button);
frame.add(name);
frame.add(button2);
frame.add(button3);
frame.add(editorPane);
frame.add(scroll);
button.setBounds(0, 200, 80, 22);
name.setBounds(82, 200, 80, 22);
button2.setBounds(164, 200, 80, 22);
button3.setBounds(246, 200, 148, 22);
editorPane.setBounds(100,175,200,18);
scroll.setBounds(50, 10, 300, 160);
textarea.setEditable(false);
button.setFont(font);
name.setFont(font);
button2.setFont(font);
button3.setFont(font);
editorPane.setFont(font);
textarea.setFont(font2);
textarea.setText("[");
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText("[");
editorPane.setText("");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea.setText(textarea.getText()+"["+editorPane.getText()+"],");
editorPane.setText("");
}
});
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String temp = textarea.getText();
temp = temp.substring(0, temp.length()-1);
textarea.setText(temp+"]");
editorPane.setText("");
WriteToFile(textarea.getText(), name.getText());
}
});
name.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
textarea.setText(readFile(name.getText()));
}
public void keyPressed(KeyEvent arg0) {
}
});
}
}
Database.java
package library;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class Database {
public static String WriteToFile(String data, String name){
String output = "ERROR";
PrintWriter writer = null;
try {
writer = new PrintWriter(name+".txt", "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.println(data);
writer.close();
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return output;
}
public static String readFile(String name){
String output = "[";
File file = new File(name+".txt");
try {
#SuppressWarnings("resource")
Scanner sc = new Scanner(file);
output = sc.next();
} catch (FileNotFoundException e) {
}
return output;
}
}
May someone provide me an explanation on why this is?
Instead
output = sc.next();
use
output = sc.nextLine();
Reference: Scanner#next() vs Scanner#nextLine()
I have created a program where I can input data in JTextField and on hitting save button I use a JFileChooser to save the data in a .txt file where each JTextField is in a new line. I also created a button that pops up a JFileChooser to browse for that file and populate its corresponding cells.
I am new to GUIs, the code I wrote is not working. I tried different variations and cannot seem to get it. Can someone point me in the right direction please.
The input is
john
Doe
st. Jude
100
Here is the code
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.util.Scanner
import java.util.Vector;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.io.*;
//import javax.swing.filechooser;
import javax.swing.filechooser.FileFilter;
public class Charity
{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new JFrame("Learning Team Charity Program");
Container cp = frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Charities
final String[] charityArray = {"St.Jude", "CHOC", "Cancer Research", "AIDs Foundation", "Crohns Foundation"};
final JComboBox selector = new JComboBox(charityArray);
JPanel first = new JPanel();
first.setLayout(new FlowLayout());
first.add(selector);
// User input JLabels and JTextFields
JLabel nameLabel = new JLabel("First Name: ");
final JTextField name = new JTextField();
JLabel lastLabel = new JLabel("Last Name: ");
final JTextField lastname = new JTextField();
JLabel donationAmount = new JLabel("Donation Amount: ");
final JTextField donation = new JTextField();
JPanel second = new JPanel();
second.setLayout(new GridLayout(4,2));
second.add(nameLabel); second.add(name);
second.add(lastLabel); second.add(lastname);
second.add(donationAmount); second.add(donation);
// Donate & Exit Buttons
JButton donateButton = new JButton("Donate");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
JButton openButton= new JButton("Open File");
JPanel third = new JPanel();
third.setLayout(new FlowLayout());
third.add(donateButton);
third.add(saveButton);
third.add(openButton);
third.add(exitButton);
// JTable display
final DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("First Name");
model.addColumn("Last Name");
model.addColumn("Charity");
model.addColumn("Donation");
table.setShowHorizontalLines(true);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(true);
JScrollPane scrollPane = JTable.createScrollPaneForTable(table);
JPanel fourth = new JPanel();
fourth.setLayout(new BorderLayout());
fourth.add(scrollPane, BorderLayout.CENTER);
// Button Events
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(1);
}
});
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line;
while((line = br.readLine())!= null){
model.addRow(line.split(","));
}//end while
br.close();
}//end try
catch(Exception e2){
JOptionPane.showMessageDialog(null, "Buffer Reader Error");
}//end catch
}
}
private void setValueAt(String line, int row, int col) {
// TODO Auto-generated method stub
}
});
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser fileChooser = new JFileChooser();
int status = fileChooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION)
{
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text", ".txt", "txt"));
//fileChooser.setFileFilter(new FileFilter("txt"));
PrintWriter output;
try {
File file = fileChooser.getSelectedFile();
output = new PrintWriter(file +".txt");
for(int row = 0; row<table.getRowCount(); row++){
for(int col = 0; col<table.getColumnCount();col++){
output.println(table.getValueAt(row, col).toString());
}
output.println();
}
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
donateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat df = new DecimalFormat("##,###.00");
try
{
Object[] rows = new Object[]{name.getText(), lastname.getText(), selector.getSelectedItem(),
donation.getText()};
model.addRow(rows);
name.setText("");
lastname.setText("");
donation.setText("");
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Enter a Dollar Amount", "Alert", JOptionPane.ERROR_MESSAGE);
return;
}
}
});
// Frame Settings
frame.setSize(470,300);
//frame.setLocation(300,200);
cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
cp.add(first);
cp.add(second);
cp.add(third);
cp.add(fourth);
frame.setVisible(true);
}
}
I understand I have to pass a value in the parenthesis after the addRow.
People don't know what that means because the code you posted here doesn't have an addRow(...) method.
I see you posted a second question 2 hours later: https://stackoverflow.com/questions/30951407/how-to-properly-read-a-txt-file-into-a-a-row-of-a-jtable.
Keep all the comments in one place so people understand what is going on.
Also, posting a few random lines of code doesn't help us because we don't know the context of how the code is used. For example, I have no idea what how you created the "model" variable. I don't know if you ever added the model to the table.
Post a proper SSCCE when posting a question so we have the necessary information. The file chooser is irrelevant to the problem because we don't have access to your real file. So instead you need to post hard coded data. An easy way to do this is to use a StringReader.
Here is a working example that shows how to read/parse/load a file into a JTable:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.io.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
try
{
DefaultTableModel model = new DefaultTableModel(0, 4);
String data = "1 2 3 4\na b c d\none two three four";
BufferedReader br = new BufferedReader( new StringReader( data ) );
String line;
while ((line = br.readLine()) != null)
{
String[] split = line.split(" ");
model.addRow( split );
}
JTable table = new JTable(model);
add( new JScrollPane(table) );
}
catch (IOException e) { System.out.println(e); }
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
All you need to do is change the code to use a FileReader instead of the StringReader.
I figured it out. Thanks for all those that tried to help.
openButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
JFileChooser openChooser = new JFileChooser();
int openStatus = openChooser.showOpenDialog(null);
if(openStatus == JFileChooser.APPROVE_OPTION){
try{
File myFile = openChooser.getSelectedFile();
//BufferedReader br = new BufferedReader(new FileReader(myFile));
Scanner br = new Scanner(new FileReader(myFile));
String line;
while((line = br.nextLine())!= null){
Object[] myRow = new Object[]{line,br.nextLine(), br.nextLine(), br.nextLine()};
model.addRow(myRow);
// line = br.readLine();
if(br.nextLine()== " "){
line=br.nextLine();
}
}//end while
br.close();
}//end try
catch(Exception e2){
return;
}//end catch
}
}
});
i am trying to implement GUI features to my java coding which i am trying out for the first time. But i tried a "Create Player Feature" in my code but it is not writing to file can someone help? thanks
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
password = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(password);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String username = nameP.getText();
String userpass = password.getText();
String hasheduserP = Utility.getHash(userpass);
String userchip = chipsP.getText();
String userContent = username + "|" + hasheduserP + "|" + userchip;
File file = new File("players.dat");
try{
//adding of user details
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("players.dat", true)));
out.println(userContent);
out.close();
JOptionPane.showMessageDialog(null,"User Created");
} catch (IOException ex){
System.out.println("Error Writing to File");
}
}
}
The file related part of your code works without any problem.
Hint: Improve it like this:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class SOPlayground {
public static void main(String[] args) throws Exception {
String userContent = "foo";
try {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/players.dat", true)))) {
out.println(userContent);
}
} catch (IOException ex) {
System.err.println("Error Writing to File: " + ex.getMessage());
}
}
}
The content of /tmp/players.dat now is
foo