Storing and Reading data

Storing and Reading data

Hello, I'm developing a GUI application as part of an assignment but stuck on how my program stores and reads the data the user entered into the GUI table I created. I also wanted to apply a java code that limits the data type and the character size that can be entered into the table fields. I got as far as creating the table and the column fields. Can you please guide me. Thanks in advance.

import java.io.*; import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel;

public class Contacts {

public static void main (String[] args)  {
       //declare members
JFrame frame = new JFrame ("Contacts");    

String [] colNames = {"First Name", "MI", "Last Name", "Age", "E-Mail Address", "Cellphone"};
Object [][] data = new Object[30][30];
DefaultTableModel model = new DefaultTableModel(data, colNames);
JTable contactsTable = new JTable(model);
JScrollPane s = new JScrollPane(contactsTable);

frame.setVisible(true);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.add(contactsTable);

} }

View Answers

September 27, 2012 at 10:49 AM

Here is an example that reads data from jtable and display on the console.

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;

public class GetDataFromDatabase{
JTable table;
JButton button;
public static void main(String[] args) {
new GetDataFromDatabase();
}

public GetDataFromDatabase(){
JFrame frame = new JFrame("Getting Cell Values in JTable");
JPanel panel = new JPanel();
String data[][] = {{"Angelina","Mumbai"},{"Martina","Delhi"}};

String col[] = {"Name","Address"};
DefaultTableModel model = new DefaultTableModel(data, col);
table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
button=new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
int index=1;
int count=table.getRowCount();

for(int i=0;i<count;i++){
Object obj1 = GetData(table, i, 0);
Object obj2 = GetData(table, i, 1);
String value1=obj1.toString();
String value2=obj2.toString();

System.out.println(value1+"\t"+value2);
index++;
}

}
});
panel.add(pane);
panel.add(button);
frame.add(panel);
frame.setSize(500,250);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public Object GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index);
}
}

September 27, 2012 at 10:51 AM

Here is an example that inserts jtable data to database.

import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;

public class InsertJTableDatabase{
JTable table;
JButton button;
public static void main(String[] args) {
new InsertJTableDatabase();
}

public InsertJTableDatabase(){
JFrame frame = new JFrame("Getting Cell Values in JTable");
JPanel panel = new JPanel();
String data[][] = {{"Angelina","Mumbai"},{"Martina","Delhi"}};

String col[] = {"Name","Address"};
DefaultTableModel model = new DefaultTableModel(data, col);
table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
button=new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
PreparedStatement pstm;
ResultSet rs;
int index=1;
int count=table.getRowCount();

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:access");
for(int i=0;i<count;i++){
Object obj1 = GetData(table, i, 0);
Object obj2 = GetData(table, i, 1);
String value1=obj1.toString();
String value2=obj2.toString();

System.out.println(value1);
System.out.println(value2);

pstm=connect.prepareStatement("insert into data values(?,?)");
pstm.setString(1,value1);
pstm.setString(2,value2);

index++;
}
pstm.executeUpdate();
}
catch(Exception e){}
}
});
panel.add(pane);
panel.add(button);
frame.add(panel);
frame.setSize(500,250);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public Object GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index);
}
}

September 27, 2012 at 10:56 AM

Here is an example that retrieves data from database and stored into jtable.

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

public class JTableDatabase {
public static void main(String[] args) {
Vector columnNames = new Vector();
Vector data = new Vector();
JPanel p=new JPanel();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root" );
String sql = "Select name,address from data";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++){
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
}
catch(Exception e){
System.out.println(e);
}
JTable table = new JTable(data, columnNames);
TableColumn col;
for (int i = 0; i < table.getColumnCount(); i++) {
col = table.getColumnModel().getColumn(i);
col.setMaxWidth(250);
}
JScrollPane scrollPane = new JScrollPane( table );
p.add( scrollPane );
JFrame f=new JFrame();
f.add(p);
f.setSize(600,400);
f.setVisible(true);
}
}









Related Tutorials/Questions & Answers:
Storing and Reading data
Storing and Reading data   Hello, I'm developing a GUI application as part of an assignment but stuck on how my program stores and reads the data... that limits the data type and the character size that can be entered
Reading Text file and storing in map
Reading Text file and storing in map  Hi I have multiple text files. I want to read thoses files and store those records in map. Map will be of "LinkedHashMap<String, Map<String, String>>" type. Please let me know
Advertisements
sorting and storing data
sorting and storing data   sorting and storing data in UITableView
iphone storing and fetching data
iphone storing and fetching data  How to store and fetch data in an iphone application
storing data into flat files
storing data into flat files  how can i retrive data from database and store data in flat files   Hi Friend, Try the following code:ADS_TO_REPLACE_1 import java.io.*; import java.sql.*; import java.util.*; class
storing data in xml - XML
storing data in xml  Can u plz help me how to store data in xml using java  Hi Friend, Try the following code: import java.io.*; import java.util.*; import org.w3c.dom.*; import javax.xml.parsers.*; import
reading the records from a .xlsx file and storing those records in database table
reading the records from a .xlsx file and storing those records in database...(); } } } } Here the problem is after reading the records line by line the data is not converted to String. And i want to know
to fetch data from ms word and storing into database
to fetch data from ms word and storing into database  i want to know how to fetch datafields from ms word and storing into database??? please answer soon .its urgent
reading data using struts and jsp java
reading data using struts and jsp java  how can i read data entered... that after reading emp_id it can be read into struts action class for retrieving other employee related data
Application reading data from JDBC database
Application reading data from JDBC database  I would like to develop an online registration system that captures details of potential candidates..." should read data from from a JDBC database named PrimeGame with TABLE PRIMEGAMETABLE
reading data from excel file and plotting graph
reading data from excel file and plotting graph  I am doing a project... the data in excel file, i have to plot graphs based on CELL ID selected. please help... that reads an excel file using POI api and using the data of excel file
excel sheet reading and using that data - JSP-Servlet
excel sheet reading and using that data  i have to do a read a excel sheet file of a employee record and then i have to use a employee details to send mail to those employees how to do in jsp sir please help me sir.. Thanks
Error in reading Excel data using jsp
Error in reading Excel data using jsp  ERROR while executing bellow code:java.io.IOException: Invalid header signature; read 576460838270094160, expected -2226271756974174256 &lt;%@page import="java.io.*"%> &lt
Storing and retrieving data alongwith image in mysql db using jsp
Storing and retrieving data alongwith image in mysql db using jsp  I want to store and retrieve the whole data as shown below in mysql db. I've put... | | | file_data | longblob | YES | | NULL
Produces XML file but format not correct for storing data using JSP and XML
Produces XML file but format not correct for storing data using JSP and XML  hii I have created a project using JSP and XML as database to store data entered by user in XML file ,It stores data entered in XML file
Java Servlet : Reading Form Data Example
Java Servlet : Reading Form Data Example In this tutorial, we are discussing about reading form data of a servlet. Reading Form Data : There are three methods of servlet to handle the form data. These are listed below -ADS
Reading the data from property file from java stand alone application in linux
Reading the data from property file from java stand alone application in linux  Please send me the example of reading the data from a property file from java stand alone application in linux. I don't know how to give path
reading a csv file from a particular row
reading a csv file from a particular row  how to read a csv file from a particular row and storing data to sql server by using jsp servlet
reading data from a text box with the same name using servlets - JSP-Servlet
reading data from a text box with the same name using servlets  Hello sir, i want to get the values from four textboxes having the same name like a= b= c= using servlet i want to print all the values from each text
Error in reading Excel data using jsp even having .xls and POI Library in respective folders
Error in reading Excel data using jsp even having .xls and POI Library in respective folders  Hi, hello.xls and POI library files are there in respective folders. the printStackTrce() method shows the following Error message
Why string is storing null value - IoC
Why string is storing null value  I am reading lines from a file...! then it is storing it in a temp variable.... but when i am running the program it is also storing null value in temp. WHY so
storing csv into oracle database
storing csv into oracle database  i want jsp code for storing csv file into oracle database
uploading and reading the excel daa
uploading and reading the excel daa  uploading the excel file not getting the data of the excel
Reading XML Data from a Stream
Reading XML Data from a Stream       This Example shows you how to Read XML Data via a Stream in a DOM... parsers.There are some of the methods used in code given below for Reading XML
Storing array in php
Storing array in php  How to store an array in PHP
Storing Data (Retrieved from a XML Document) to a File
Storing Data (Retrieved from a XML Document) to a File... simple program that helps you in storing the data to a specified file in different... to store data (retrieved from the XML document) to a specified file (with 
storing xml into database - XML
storing xml into database   hi i have an xml file it contains elements with attributes as well as nested elements so how to go forward .......with it i know how to persist a simple xml file into data base but i m finding some
Reading UTF - 8 Encoded Data in Java
s a f i l e Reading Process Completly Successfully... the InputStreamReader and FileInputStream classes to read data or contents from the specified file in the specified encoded data format that has been mentioned
Uploading a Software and storing in the database
Uploading a Software and storing in the database  I want to upload a software(may be of maximum 20mb) through JSP, and store it in the database. The coding present in the site for uploading and storing in the database
Remote file storing in mobile
Remote file storing in mobile  Hai.. i want to do my semester project..i have selected a topic "Remote file storing in mobile"..it is in the form like any Java enabled GPRS based mobile phone users can store their images,video
Remote file storing in mobile
Remote file storing in mobile  Hai.. i want to do my semester project..i have selected a topic "Remote file storing in mobile"..it is in the form like any Java enabled GPRS based mobile phone users can store their images,video
Reading files in Java
Reading files in Java  I have to make a program in my project of finance that reads the text file and process the data in it. How to read the text.... Please provide me the example code for reading big text file in Java. What do you
Reading ISO Latin-1 Encoded Data in Java
Reading ISO Latin-1 Encoded Data in Java   ... for reading contents from the specified file in standard ISO-1 format using the "... : Filterfile.txt File Text : WelCome to RoseIndia.Net Reading
Reading Value From console
Reading Value From console  In case of String data Type readLine method of DataInputStream class read complete line of the given string but the next method of Scanner class doesn't read the complete line of String. why
Reading Value From console
Reading Value From console  In case of String data Type readLine method of DataInputStream class read complete line of the given string but the next method of Scanner class doesn't read the complete line of String. why
web page reading in java
web page reading in java  i wanna read webpage in that i want to get the data from the particular tags like (,) and store into the data base...; Are you going to read the data in XML format ? If yes , there are lot
Reading file into bytearrayoutputstream
input stream and byte output stream. This is and good example of reading file... the file into byte array and then write byte array data into a file.ADS_TO_REPLACE_1 In this example we have used the class InputStream for reading the file
svg file reading and display
svg file reading and display  i want a sample program for reading and displaying the content of a svg file
Reading a text file in java
Reading a text file in java  What is the code for Reading a text file... in java.io.* package for reading and writing to a file in Java. To learn more about reading text file in Java see the tutorial Read File in Java. Thanks
Error in Storing date - Development process
Error in Storing date  Hi, U have given this code for storing date in database. But this is not working . i want it with Statement not PreparedStatement created table in msaccess : InsertDate   Hi Friend
Thread for reading txt file
Thread for reading txt file  how to use 3 thread to read 3 txt file? To create three threads for reading the file and three threads for getting the strings out of the queue and printing them. thanks
Reading a xml file - JSP-Servlet
Reading a xml file  how to read a xml file using jsp and then i have to retrive a data from that file use it in code?  Hi Friend, Please visit the following link: http://www.roseindia.net/jsp/parsing-xml.shtml
reading excel sheet in java
reading excel sheet in java  can anyone tell me a proper java code to read excel sheet using poi   Here is a java code that reads an excel file using POI api and display the data on the console. import java.io.
Reading and writting multiple files
Reading and writting multiple files  how can i read and write say two different files at the same time using threads
Reading multiple xml files
Reading multiple xml files  How can we read many xml files from a folder? The same procedure as that of "listfiles
Writing and Reading A File
Writing and Reading A File  Hello, I've been trying to learn writing and reading data from file for our assignment, but just stuck on how to proceed...", "Age"}; Object [][] data = new Object[30][5]; DefaultTableModel model = new
Reading big file in Java
Reading big file in Java  How to read a big text file in Java program?   Hi, Read the complete tutorial at How to read big file line by line in java? Thanks
Excel sheet image reading issue
Excel sheet image reading issue   Hello every one.I?m trying... columns of data, the first 5 are all text but the last is image. While I?m reading the record, It?s doing fine on the first 5 columns but return me
Problem reading word file
Problem reading word file  Deepak you provide me code for extarcting equation from a word file and also to write in a word file.But when I again want to read preveously created word file(created by your code) it gives an error
Reading an excel file into array
Reading an excel file into array  Hi, I'm trying to read in an excel file, search a column for containing key words (entered by a user) and then displaying the matching rows in a table. I'm fairly new to JavaScript. Can anyone

Ads