Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Storing and Reading data

Have Programming Question? Ask it here!
 
 
 


Mike Lee
Storing and Reading data
3 Answer(s)      a year and 10 months ago
Posted in : Java Beginners


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);

} }


Advertisement
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: import java.io.*; import java.sql.*; import java.util.*; class StoreDataIntoFile
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
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
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
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
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 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
Storing Data (Retrieved from a XML Document) to a File
Storing Data (Retrieved from a XML Document) to a File... that helps you in storing the data to a specified file in different format. After... to store data (retrieved from the XML document) to a specified file (with 
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
storing csv into oracle database
storing csv into oracle database  i want jsp code for storing csv file into oracle database
Storing array in php
Storing array in php  How to store an array in PHP
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
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
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
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
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 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
Reading ISO Latin-1 Encoded Data in Java
Reading ISO Latin-1 Encoded Data in Java   ... InputStreamReader and FileInputStream classes to create buffer for reading contents from... to RoseIndia.Net Reading Process Completly Successfully
uploading and reading the excel daa
uploading and reading the excel daa  uploading the excel file not getting the data of the excel
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
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
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
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 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. In this example we have used the class InputStream for reading the file content into byte
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
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
jsp code for storing login and logout time to an account
jsp code for storing login and logout time to an account  I need simple jsp code for extracting and storing login and logout time in a database table..plz someone help me...   Please visit the following link: http
getting and storing dropdown list in database in jsp
getting and storing dropdown list in database in jsp  i have a drop... into data(language) values('"+selectedValue+"')"); out.println("Data... lyk this. but it storing null value in the database. :\ what to do
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
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 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.
complex xml parsing and storing in database - XML
complex xml parsing and storing in database  Hi Experts ,i want to parse my xml document and store it in mysql database. This is my code. How to parse this complex data. EDI_DC40 800 0000000000557748
Storing the Color Image pixel values into 2d array
Storing the Color Image pixel values into 2d array  i want to store the color image pixel values into 2d array and agiain the array have to store into a text file using java... plz provide the code
extracting phone number n storing in excel
extracting phone number n storing in excel  i need a program to open a doc file n extract phone numbers from it and store it in a excel sheet?? plz do reply and help me out with the problem
extracting phone number n storing in excel
extracting phone number n storing in excel  i need a program to open a doc file n extract phone numbers from it and store it in a excel sheet?? plz do reply and help me out with the problem
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
Advertisements
 

 

 

DMCA.com