I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.
This is some of my code:
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = br1.readLine();
//Splits the string of set and subject by using the comma
String [] names = strSetSubjectLine.split(",");
strSetName = names[0];
strSubjectName = names[1];
//Finds the line number to see the number of cards in each set
lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
lnr2.skip(Long.MAX_VALUE);
strLineNumber2 = String.valueOf(lnr2.getLineNumber());
lineNumber2 = Integer.parseInt(strLineNumber2);
} catch (IOException | NumberFormatException e) {
strLineNumber2 = "0";
}
//Adds the set name to the set name array
lblDeckName[row] = new JLabel (strSetName);
//Adds all buttons that will be used in the layout into a button array
JButton aryOptions [][] = new JButton [3][lineNumber];
//Defines and formats the Add Words button
JButton btnAddWords = new JButton("Add Words");
btnAddWords.setOpaque(false);
btnAddWords.setContentAreaFilled(false);
btnAddWords.setBorder(null);
btnAddWords.setBorderPainted(false);
//Defines and formats the Play button
JButton btnPlay = new JButton("Play");
btnPlay.setOpaque(false);
btnPlay.setContentAreaFilled(false);
btnPlay.setBorder(null);
btnPlay.setBorderPainted(false);
//Defines and formats the Delete Set button
JButton btnDelete = new JButton("Delete Set");
btnDelete.setOpaque(false);
btnDelete.setContentAreaFilled(false);
btnDelete.setBorder(null);
btnDelete.setBorderPainted(false);
//Adds each button to the array based on the number of sets
aryOptions [0][row] = btnAddWords;
aryOptions [1][row] = btnPlay;
aryOptions [2][row] = btnDelete;
//Formats the GridBagLayout (Spaces are for formatting purposes)
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = row;
layoutBackground.add(lblDeckName[row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx =2;
gbc.gridy = row;
layoutBackground.add(new JLabel (strSubjectName),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = row;
layoutBackground.add(new JLabel(strLineNumber2),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 5;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 6;
gbc.gridy = row;
layoutBackground.add(aryOptions[0][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 7;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 8;
gbc.gridy = row;
layoutBackground.add(aryOptions[1][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 9;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 10;
gbc.gridy = row;
layoutBackground.add(aryOptions[2][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 11;
gbc.gridy = row;
layoutBackground.add(new JLabel(" |"),gbc);
//Creates an action event for the delete set button
btnDelete.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Defines new file reader and buffered reader
FileReader file_to_read2 = new FileReader(path);
BufferedReader br2 = new BufferedReader(file_to_read2);
//Finds the numerical index of the button that was clicked
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br2.readLine()) != null) {
counter ++;
if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
try {
//Finds the name of the set based on what button was clicked
String chosenDeck2 = br2.readLine();
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Creates the path to the file that needs to be deleted
Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p2);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
//Reads the deck name based on the button that was clicked
String chosenDeck2 = br2.readLine();
//Splits the deck name from the subject
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Closes the buffered reader and file reader
//Gets the file that needs to be deleted
Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p1);
}
}
br2.close();
file_to_read2.close();
}
catch (HeadlessException | IOException | NumberFormatException e) {
JOptionPane.showMessageDialog(null, e);
}
});
//Creates an action event for the add words button
btnAddWords.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Creates a new file reader and buffered reader
FileReader file_to_read3 = new FileReader(path);
BufferedReader br3 = new BufferedReader(file_to_read3);
//Finds the index value
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br3.readLine()) != null) {
//Increases counter value by 1
counter ++;
if(intIndex == 0)
{
try {
//Reads the set and subject for the
String chosenDeck2 = br3.readLine();
//Splits the subject from the set
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
String chosenDeck2 = br3.readLine();
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
}
}
br3.close();
file_to_read3.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
//Opens the new words frame
frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
s.setVisible(true);
});
}
} catch (Exception e ) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.
I am really stuck, and would really appreciate some help.
Thanks :)
You may rearrange your exception handling to use this properly.
try
{
//trying something
}
catch(SomeException e)
{
//we failed
e.printStackTrace();
}
finally
{
//called when we failed or when we succeeded, even after a return; statement
}
EDIT
This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
ArrayList<String> linesRead = new ArrayList<String>();
String line = br1.readLine();
while(line != null)
{
linesRead.add(line);
line = br1.readLine();
}
br1.close();
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = linesRead.get(row);
Related
On start up my program gives me the message java.io.IOException: stream closed. It then opens with limited components.
I understand what a stream closed exception is, I just can't figure out how to fix it, in my case. I would really appreciate some help. (I'm sorry about the big chunk of code, but I am not sure what you need to help me)
try {
//Defines new file reader and buffered reader
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
//action code
try {
//Finds the line number to see the number of cards in each set
lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
lnr2.skip(Long.MAX_VALUE);
strLineNumber2 = String.valueOf(lnr2.getLineNumber());
lineNumber2 = Integer.parseInt(strLineNumber2);
//Closes the file reader and buffered reader
br1.close();
file_to_read.close();
} catch (IOException | NumberFormatException e) {
strLineNumber2 = "0";
}
//Adds the set name to the set name array
lblDeckName[row] = new JLabel (strSetName);
//Adds all buttons that will be used in the layout into a button array
JButton aryOptions [][] = new JButton [3][lineNumber];
//Defines and formats the Add Words button
JButton btnAddWords = new JButton("Add Words");
btnAddWords.setOpaque(false);
btnAddWords.setContentAreaFilled(false);
btnAddWords.setBorder(null);
btnAddWords.setBorderPainted(false);
//Defines and formats the Play button
JButton btnPlay = new JButton("Play");
btnPlay.setOpaque(false);
btnPlay.setContentAreaFilled(false);
btnPlay.setBorder(null);
btnPlay.setBorderPainted(false);
//Defines and formats the Delete Set button
JButton btnDelete = new JButton("Delete Set");
btnDelete.setOpaque(false);
btnDelete.setContentAreaFilled(false);
btnDelete.setBorder(null);
btnDelete.setBorderPainted(false);
//Adds each button to the array based on the number of sets
aryOptions [0][row] = btnAddWords;
aryOptions [1][row] = btnPlay;
aryOptions [2][row] = btnDelete;
//Formats the GridBagLayout (Spaces are for formatting purposes)
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = row;
layoutBackground.add(lblDeckName[row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx =2;
gbc.gridy = row;
layoutBackground.add(new JLabel (strSubjectName),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = row;
layoutBackground.add(new JLabel(strLineNumber2),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 5;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 6;
gbc.gridy = row;
layoutBackground.add(aryOptions[0][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 7;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 8;
gbc.gridy = row;
layoutBackground.add(aryOptions[1][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 9;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 10;
gbc.gridy = row;
layoutBackground.add(aryOptions[2][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 11;
gbc.gridy = row;
layoutBackground.add(new JLabel(" |"),gbc);
//Creates an action event for the delete set button
btnDelete.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Defines new file reader and buffered reader
FileReader file_to_read2 = new FileReader(path);
BufferedReader br2 = new BufferedReader(file_to_read2);
//Finds the numerical index of the button that was clicked
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br2.readLine()) != null) {
counter ++;
if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
try {
//Finds the name of the set based on what button was clicked
String chosenDeck2 = br2.readLine();
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Closes the buffered reader and file reader
br2.close();
file_to_read2.close();
//Creates the path to the file that needs to be deleted
Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p2);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
//Reads the deck name based on the button that was clicked
String chosenDeck2 = br2.readLine();
//Splits the deck name from the subject
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Closes the buffered reader and file reader
br2.close();
file_to_read2.close();
//Gets the file that needs to be deleted
Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p1);
}
}
}
catch (HeadlessException | IOException | NumberFormatException e) {
JOptionPane.showMessageDialog(null, e);
}
});
//Creates an action event for the add words button
btnAddWords.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Creates a new file reader and buffered reader
FileReader file_to_read3 = new FileReader(path);
BufferedReader br3 = new BufferedReader(file_to_read3);
//Finds the index value
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br3.readLine()) != null) {
//Increases counter value by 1
counter ++;
if(intIndex == 0)
{
try {
//Reads the set and subject for the
String chosenDeck2 = br3.readLine();
//Splits the subject from the set
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
//Closes the buffered reader and file reader
br3.close();
file_to_read3.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
String chosenDeck2 = br3.readLine();
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
br3.close();
file_to_read3.close();
}
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
//Opens the new words frame
frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
s.setVisible(true);
});
}
} catch (Exception e ) {
JOptionPane.showMessageDialog(null, e);
}
What I am finding is that when I am deleting the br1.close() the stream closed error stops, but I can find any reason why? Nothing is using that reader, that I can see. And when I do delete it I get and error saying that the test files are being used by other processes, which I can only presume is br1.
I know this may seem confusing to look at, probably because it is sloppy code, but I would really appreciate some help. I am a high school student.
Thanks :)
You could use the closable feature from Java 7:
try ( FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read)){
//Finds the line number to see the number of cards in each set
lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
lnr2.skip(Long.MAX_VALUE);
strLineNumber2 = String.valueOf(lnr2.getLineNumber());
lineNumber2 = Integer.parseInt(strLineNumber2);
} catch (IOException | NumberFormatException e) {
strLineNumber2 = "0";
}
Then you don't have to care about closing your stream or file in the right order.
Furthermore you could just use libs for doing the "readFile" job like apache commons or guava.
When you construct nested Readers as you do, for example,
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
, closing the outer one automatically closes the inner one, too. You do not need to close the inner one yourself, and if you try to do so after closing the outer one, as you do, you will find that it is already closed.
The best solution is to close only the outer one (as opposed to your workaround of closing only the inner one). You probably don't even need to retain a reference to the inner one -- a more typical idiom would go something like this:
BufferedReader br1 = new BufferedReader(new FileReader(path));
try {
// ... manipulate br1 ...
} finally {
br1.close();
// no need to explicitly close the inner FileReader
}
You could write that in try-with-resources form if that suits your fancy.
Similar applies to nested Writers, InputStreams, and OutputStreams, too.
I'm having stuck at reading back from csv wheres i'm success at creating the csv.
the problem I'm facing is I cant get a clue on how to obtain the values getting from csv back to the jTable.
I'm not having any other problems aside from public void fromCsv
class FCMS extends JFrame{
String header[] = {"Firstname","Lastname","FCMS ID","Email"};
String data[][];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
JPanel pane = new JPanel();
JPanel pane_input = new JPanel();
JLabel lbl_firstname = new JLabel(" Firstname");
JLabel lbl_lastname = new JLabel(" Lastname");
JLabel lbl_id = new JLabel(" FCMS ID");
JLabel lbl_email = new JLabel(" Email");
JTextField txt_firstname = new JTextField(10);
JTextField txt_lastname = new JTextField(10);
JTextField txt_id = new JTextField(10);
JTextField txt_email = new JTextField(10);
JButton btn_add = new JButton("Add Entry");
JButton btn_Csv = new JButton("Export to Csv");
JButton btn_load = new JButton("Load From Csv");
public FCMS(){
setSize(200,200);
setPreferredSize(new Dimension(350,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
setTitle("Flight Crew Management System");
btn_add.setMnemonic(KeyEvent.VK_A);
btn_Csv.setMnemonic(KeyEvent.VK_E);
btn_load.setMnemonic(KeyEvent.VK_L);
pane_input.setLayout(new GridLayout(0,2));
pane_input.add(lbl_firstname);
pane_input.add(txt_firstname);
pane_input.add(lbl_lastname);
pane_input.add(txt_lastname);
pane_input.add(lbl_id);
pane_input.add(txt_id);
pane_input.add(lbl_email);
pane_input.add(txt_email);
pane_input.add(btn_add);
pane_input.add(btn_Csv);
pane_input.add(btn_load);
pane.setLayout(new BorderLayout());
pane.add(pane_input, BorderLayout.NORTH);
pane.add(new JScrollPane(table), BorderLayout.CENTER);
add(pane);
pack();
setVisible(true);
btn_add.addActionListener(new AksyonListener());
btn_Csv.addActionListener(new AksyonListener());
btn_load.addActionListener(new AksyonListener());
txt_email.addActionListener(new AksyonListener());
}
public void toCsv(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter Csv = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
Csv.write(model.getColumnName(i) + ",");
}
Csv.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
Csv.write(model.getValueAt(i,j).toString()+",");
}
Csv.write("\n");
}
Csv.close();
}catch(IOException e){ System.out.println(e); }
}
public void fromCsv(File file){
BufferedReader fileReader = null;
model.setRowCount(0);
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}
}
public static void main(String[] args){
new FCMS();
}
class AksyonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == btn_add || e.getSource() == txt_email){
String fn = txt_firstname.getText();
String ln = txt_lastname.getText();
String id = txt_id.getText();
String mail = txt_email.getText();
txt_firstname.setText("");
txt_lastname.setText("");
txt_id.setText("");
txt_email.setText("");
txt_firstname.requestFocus();
model.insertRow(model.getRowCount(), new Object[]{fn, ln, id, mail});
}
else if(e.getSource() == btn_Csv){
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
toCsv(table, new File(file));
}
}
else if(e.getSource() == btn_load){
JFileChooser fc = new JFileChooser();
int option = fc.showOpenDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
fromCsv(new File(file));
}
}
}
}
}
Problem is solved:
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}
String[] tokens = line.split(",");
Above is where you split one line of data into an array, so above is where you then need to take the data from the array and add it to the TableModel.
So your code should be:
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
Then there is no need for the second loop.
However, the above code will just append data to the existing "model", so you may also need to clear all the data in the model. You can do this by adding:
model.setRowCount(0);
before the loop.
I am making a gui with netbeans. I right clicked a JTable to add event listener for mouse clicked. I added my code to the new method. For the life of me when I click the JTable I get no errors.
Any ideas on what I am doing wrong or how to fix it? if you need to see more of my code let me know. everything besides the connection to the DB is ran out of the driver class.
I moved my program to eclipse to make this easier for me to trouble shoot.
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Here is the onclick method
Here is my even listener
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
Here is the whole Driver Class:
import java.awt.BorderLayout;
public class Driver {
private JFrame f;
private JPanel p;
private JTextField fieldBN;
private JTextField fieldFN;
private JTextField fieldLN;
private JTextField fieldP;
private JTextField fieldE;
private JTextField fieldA;
private JTextField aLine2;
private JTextField fieldW;
private JLabel labelBN;
private JLabel labelFN;
private JLabel labelLN;
private JLabel labelP;
private JLabel labelE;
private JLabel labelA;
private JLabel labelW;
private JComboBox relationship;
private JButton buttonS;
private JTable tableDisplay;
String[] relationshipValues = { "Business", "Friend", "Family", "Professional" };
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
// Constructor:
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
public void gui() {
f = new JFrame("Contact Book");
GridBagConstraints c = new GridBagConstraints();
p = new JPanel(new GridBagLayout());
f.getContentPane().add(p, BorderLayout.NORTH);
c.gridx = 0;
c.gridy = 0;
labelBN = new JLabel ("Business Name:");
p.add(labelBN, c);
c.gridx = 1;
c.gridy = 0;
fieldBN = new JTextField(10);
p.add(fieldBN, c);
c.gridx = 0;
c.gridy = 1;
labelFN= new JLabel ("First Name:");
p.add(labelFN, c);
c.gridx = 1;
c.gridy = 1;
fieldFN = new JTextField (10);
p.add(fieldFN, c);
c.gridx = 0;
c.gridy = 2;
labelLN= new JLabel ("Last Name:");
p.add(labelLN, c);
c.gridx = 1;
c.gridy = 2;
fieldLN = new JTextField (10);
p.add(fieldLN, c);
c.gridx = 0;
c.gridy = 3;
labelP = new JLabel ("Phone Number:");
p.add(labelP, c);
c.gridx = 1;
c.gridy = 3;
fieldP = new JTextField (10);
p.add(fieldP, c);
c.gridx = 0;
c.gridy = 4;
labelE = new JLabel ("Email:");
p.add(labelE, c);
c.gridx = 1;
c.gridy = 4;
fieldE = new JTextField (10);
p.add(fieldE, c);
c.gridx = 0;
c.gridy = 5;
labelA = new JLabel ("Address:");
p.add(labelA, c);
c.gridx = 1;
c.gridy = 5;
fieldA = new JTextField (10);
p.add(fieldA, c);
c.gridx = 1;
c.gridy = 6;
aLine2 = new JTextField (10);
p.add(aLine2, c);
c.gridx = 0;
c.gridy = 7;
labelW = new JLabel ("Website:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 7;
fieldW = new JTextField (10);
p.add(fieldW, c);
c.gridx = 0;
c.gridy = 8;
labelW = new JLabel ("Relationship:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 8;
relationship = new JComboBox(relationshipValues);
p.add(relationship, c);
c.gridx = 1;
c.gridy = 9;
buttonS = new JButton("Save:");
p.add(buttonS, c);
c.gridx = 0;
c.gridy = 10;
tableDisplay = new JTable();
p.add(tableDisplay, c);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(1400,900); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // End of Gui Method
private void UpdateTable() {
try {
String sql = "SELECT * FROM contact";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
tableDisplay.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
}
});
} // End main Method
} // End class Driver
It's difficult to know why you're having issues with the registering a MouseListener, there's not enough context to diagnose the problem.
You should start by placing out put statements in the code to check to see if the method is been called and that the query is returning values.
If all else fails, you should try regsitering the mouse listener manually. See How to Write a Mouse Listener for more details.
You query is also including spaces in the match...
String sql = " select * from contact where id = ' " + tableClick + " ' ";
^------------------^-----
Which will affect the ability for the database to match results to your query. Try removing these
String sql = " select * from contact where id = '" + tableClick + "'";
This is a JDBC project. Data from a MySQL database on a WAMP server is displayed in a JTable. I want a user-entered ID on my JSpinner to delete the row with that ID from the table. I made a SQL Query and everything works, but the data on the my JTable doesn't refresh when my query is executed. I click my JNazad button (my back button), and reenter that window so that my JTable shows refreshed data. I don't implemented FireTableModel in my NapraviTablicu method, because its DefaultTableModel, and updates are automatically done with it . I don't know what I did wrong:
public class GUIBDelete extends JFrame{
private SpinnerModel SM;
private JSpinner Spinner;
private JLabel LUnos;
private JButton BNazad, BIzvrsi;
private String ID, SqlQuery;
private Vector NaziviKolona = new Vector();
private Vector Podaci = new Vector();
private JTable Tablica=new JTable();
private JScrollPane ScrollPane;
private DefaultTableModel model;
private JTable NapraviTablicu(){
try {
String SqlQuery = "SELECT * FROM `nfc_baza`";
Podaci.clear();
NaziviKolona.clear();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/nfc", "root", "");
Statement Stat = con.createStatement();
ResultSet Rez = Stat.executeQuery(SqlQuery);
ResultSetMetaData md = Rez.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
NaziviKolona.addElement(md.getColumnName(i));
}
while (Rez.next()) {
Vector red = new Vector(columns);
for (int i = 1; i <= columns; i++) {
red.addElement(Rez.getObject(i));
}
Podaci.addElement(red);
}
Rez.close();
Stat.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
model = new DefaultTableModel(Podaci, NaziviKolona);
JTable table = new JTable(model);
return table;
}
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
dispose();
new GUIIzbornik();
}
};
ActionListener a2 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
ID=null;
SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
IzvrsiQuery();
}
private void IzvrsiQuery() {
Object sp = Spinner.getValue();
ID = sp.toString();
SqlQuery=SqlQuery+ID;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con2 = DriverManager.getConnection(
"jdbc:mysql://" + "localhost:3306/nfc", "root", "");
Statement Stat = con2.createStatement();
int Rez = Stat.executeUpdate(SqlQuery);
Stat.close();
con2.close();
JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
"Poruka!", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
};
GUIBDelete(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
Tablica=NapraviTablicu();
ScrollPane = new JScrollPane(Tablica);
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(2, 2, 2, 2);
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 4;
c.gridheight = 2;
c.gridx = 0;
c.gridy = 0;
add(ScrollPane, c);
LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(LUnos, c);
SM = new SpinnerNumberModel(1, 1, 1000, 1);
Spinner = new JSpinner(SM);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 2;
add(Spinner, c);
BNazad = new JButton("Nazad");
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
BNazad.addActionListener(a1);
add(BNazad, c);
BIzvrsi = new JButton("Izvrši");
c.gridx = 2;
c.gridy = 3;
BIzvrsi.addActionListener(a2);
add(BIzvrsi, c);
setSize(400, 500);
setTitle("Brisanje podataka");
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIBDelete i = new GUIBDelete();
}
});
}
}
It looks like you're deleting a row from a database table, and you want the JTable to reflect the change. In izvrsiQuery() update your TableModel and the JTable will update itself. For example,
...
con2.close();
model.removeRow(((Number)(spinner.getValue())).intValue() - 1);
JOptionPane.showMessageDialog(...);
...
Note that row numbers start at 0, and they must be translated when using a RowSorter.
As an aside, your code will be easier for others to read if you use common Java naming conventions and factor out constants.
Addendum: The example just removes a row by number. You'll have to search your TableModel for the row that corresponds to the deleted ID.
Addendum: Although less practical, you may want to refresh the entire table from the database after a DML operation using setModel(), as shown here.
I have a JTextField in a JApplet with a ActionListener. I compiled it using Eclipse and it works fine. But when I try to load it in a .html file using applet, the JTextField does not register/recognize the ENTER key when I press it. It seems like the ActionListener did not work. I used:
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
question = ProcessString(question);
answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
static String noAnswer;
static boolean knowAnswer = true;
// process the question string, take out non-ACSII characters, spaces, to
// lower space
public String ProcessString(String question) {
question = question.toLowerCase();
String[] words = question.split("\\s+");
question = "";
for (int wordCount = 0; wordCount < words.length; wordCount++) {
words[wordCount] = words[wordCount].replaceAll("[^A-Za-z]", "");
if (wordCount != words.length - 1)
question = question + words[wordCount] + " ";
else
question = question + words[wordCount];
// System.out.println(words[wordCount]);
}
return question;
}
public String Answer(String question) {
String answer = "";
/*
if the database know the answer (did not not know), then return the
answer. if the database does not know the answer, then recover the
answer in database.
*/
if (knowAnswer == true) {
// open the database file and search if questions matches any one in
// the
// database
Scanner sc = null;
try {
sc = new Scanner(new File("database.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int answerFrequency = 0;
boolean matchFound = false;
while (sc.hasNext()) {
int questionCount = sc.nextInt();
String line = sc.nextLine();
String[] databaseLine = line.split("\\s+");
String databaseQuestion = "";
String databaseAnswer = "";
// collect words for database questions
for (int wordCount = 1; wordCount <= questionCount; wordCount++) {
if (wordCount != questionCount)
databaseQuestion = databaseQuestion
+ databaseLine[wordCount] + " ";
else
databaseQuestion = databaseQuestion
+ databaseLine[wordCount];
}
// collect words for database answer
for (int wordCount = questionCount + 2; wordCount < databaseLine.length; wordCount++) {
databaseAnswer = databaseAnswer + databaseLine[wordCount]
+ " ";
}
// if the question is found in database, print answer
if (question.equals(databaseQuestion)) {
matchFound = true;
// the current answer is more frequency than the previous
// found
// answer, reassign the current answer the find answer
if (answerFrequency < Integer
.parseInt(databaseLine[questionCount + 1])) {
answerFrequency = Integer
.parseInt(databaseLine[questionCount + 1]);
answer = databaseAnswer;
}
}
}
if (matchFound == true) {
// System.out.println(answer);
knowAnswer = true;
} else {
// System.out.println("I don't know what you mean. How should I answer your question?");
knowAnswer = false;
noAnswer = question;
answer = "I don't know how to respond. How should I answer that?";
}
sc.close();
} else if (knowAnswer == false) {
String[] word = noAnswer.split(" ");
BufferedWriter writer = null;
answer = question;
try {
writer = new BufferedWriter(
new FileWriter("database.txt", true));
writer.newLine();
writer.write(word.length + " " + noAnswer + " 1 " + answer);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
System.out.println("Cannot write to file");
}
}
answer = "I got that.";
knowAnswer = true;
}
return answer;
}
Really appreciate the help.
This seems to work for me....
public class TestApplet04 extends JApplet implements ActionListener {
private JTextField textField;
private JTextArea textArea;
private String newline;
public void init() {
textField = new JTextField(20);
textField.setText("Enter your question here.");
textField.selectAll();
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// Add Components to the Applet.
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
gridBag.setConstraints(textField, c);
contentPane.add(textField);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
gridBag.setConstraints(scrollPane, c);
contentPane.add(scrollPane);
newline = System.getProperty("line.separator");
}
public void actionPerformed(ActionEvent event) {
String text = textField.getText();
String question = "";
String answer = "";
question = textField.getText();
// question = ProcessString(question);
// answer = Answer(question);
textArea.append(text + newline);
textArea.append(answer + newline);
textField.selectAll();
}
}
Updated after feedback
Here's you major problem...
sc = new Scanner(new File("database.txt"));
This is going to cause you a number of problems. First of all, the applet isn't likely to have access rights to read from the client machine, so you're likely to run into a security exception. Secondly, as the previous statement may have suggested, the file ins't likely to exist on the client machine.
You need to embed this resource within the Jar of your application and use getClass().getResource("...") to gain access to it. This will return a URL, from which you can use URL#openConnection to gain access to a InputStream, which can use in your scanner.
Try adding an Action to the ActionMap and setting the InputMap up for ENTER key.
textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter" );
textField.getActionMap().put("enter", new AbstractAction() {...} );
The field will have to have focus.
I'm also a newbie to Java, but found out that JTextfield is only a single line entry.
If you want a multiline entry, you would need to use a JTextArea instead.
Hope this helps :)