I am trying to populate a table from a text file using vectors. Should I be creating a new vector for each row? Is there anything else that appears wrong with my code? I'm not quite sure what to do from here.
public class myJTable {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> v = new Vector<String>();
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
//String splitting
try {
FileReader fReader = new FileReader("lakedata.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input;
String[] temp;
while((input=inFile.readLine())!=null) {
temp = input.split(",",3);
for(int i=0; i<temp.length; i++) {
v.addElement(temp[i]);
System.out.println(temp[i]);
}
System.out.println(v);
rowData.addElement(v);
}
inFile.close();
}
catch(Exception e) {
System.out.println("ERROR");
}
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Depth");
columnNames.addElement("Temperature");
columnNames.addElement("D.O.");
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(500,300);
frame.setVisible(true);
}
}
Instead of using Vector, you can create a DefaultTableModel then set it as the model of the table, then invoke its addRow method to directly put the read line result to the table. The table will automatically update itself when data to a table is added.
I took the liberty to revise your code into a cleaner one.
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class TablePopulation {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
/* Set the table data to null first since
* we will fetch data from file line by line
* -------------------------------------- */
DefaultTableModel model = new DefaultTableModel(null, new String[]{"Depth","Temperature","D.O."});
table.setModel(model);
/* String splitting
* ---------------- */
try {
FileReader fReader = new FileReader("file.txt");
BufferedReader inFile = new BufferedReader(fReader);
String input = inFile.readLine();
while(input !=null) {
String[] temp = input.split(",");
model.addRow(temp);
input = inFile.readLine();
}
inFile.close();
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(500,300);
frame.setVisible(true);
}
});
}
}
Also, atleast put e.printStackTrace() (since you're not using any logging framework) in the catch block to see the stack trace of what's going on in case some error has been caught.
Related
The code below takes data from a text file delimited by "|" and displays it in a JTable. When I run it on the JFrame itself it does work. However I cannot figure out how to move it to another class for itself and make it become a method such as public void viewUser(){}, then call it from the frame on click of a button.
public void viewUser(){
File file = new File("user.dat");
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] lines = br.lines().toArray();
for (Object line : lines) {
String[] row = line.toString().split("\\|");
model.addRow(row);
}
} catch (IOException ex) {
Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
}
You are getting this wrong conceptually: a model by itself is meaningless. It needs to be connected to a table in order to show its content.
The code you are showing is creating and filling a new table model. Then that model and all the information is thrown away. Reading data into an object is pointless, when that object isn't made available for further usage!
You might simply change the return type from void to DefaultTableModel and return the model object in the end. And then you can use that pre-filled model for any JTable!
Run this mcve and see if it mocks what you want to do:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TablePane extends JPanel {
private final JTable table;
public TablePane() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Age" };
Object[][] data = {
{"Kathy", new Integer(35)},
{"John", new Integer(63)},
{"Sue", new Integer(28)},
{"Joe", new Integer(70)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(300, 100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
void refresh() {
new Updater(table).getNewData();
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TablePane tablePane = new TablePane();
frame.add(tablePane);
JButton button = new JButton("Change data");
button.addActionListener(e -> tablePane.refresh());
frame.add(button, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
class Updater {
private DefaultTableModel model;
Object[][] testData = {
{"Bon", new Integer(15)},
{"Anna", new Integer(31)},
{"Dan", new Integer(82)},
{"Jane", new Integer(20)},
};
public Updater(JTable table) {
model = (DefaultTableModel)table.getModel();
}
void getNewData(){
//if you want to clear data : model.getDataVector().clear();
for (Object[] row : testData) {
model.addRow(row);
}
}
}
As commented by Andrew Thomson mcve with hard coded data is essential.
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
}
}
});
Can someone tell me how to modify below program? Program's data is passed by object[][] - instead of that will just give file name which is having data should be print in a table.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;
public SimpleTableDemo() {
super(new GridLayout(1,0));
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
}
private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();
System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If I understood question correct, you can replace Object[][] data with something like this:
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
File file = new File("\\file path");
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
}catch (Exception ex){
ex.printStackTrace();
System.out.println("File not found");
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
In this exemple, it will work if data in file is formatted as:
name, surname, sportage, is Vegetarian. However you can change that easily, but remember to also change symbol in brackets in line.split().
EDIT:
I don't fully understand what you want to achieve, however I would do it like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
public class Project {
private JScrollPane scrollPane;
private JFrame frame;
private JTable table;
public static void main (String[] args){
Project project = new Project();
project.createGUI();
}
public void createGUI(){
frame = new JFrame();
scrollPane = new JScrollPane();
JPanel panel = new JPanel();
JButton open = new JButton("Open");
open.addActionListener(new OpenListener());
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitListener());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new CancelListener());
panel.add(open);
panel.add(submit);
panel.add(cancel);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void createAndDisplayList(String[][] data){
String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
table = new JTable(data, columnNames);
frame.setVisible(false);
frame.remove(scrollPane);
scrollPane = new JScrollPane(table);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
private class OpenListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
fileChooser.showOpenDialog(frame);
try{
BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
reader.close();
}catch (Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
createAndDisplayList(data);
}
}
private class CancelListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
frame.remove(scrollPane);
scrollPane = new JScrollPane();
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
}
private class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()));
for(int i = 0; i<table.getRowCount(); i++){
for(int j = 0; j<table.getColumnCount(); j++){
System.out.println(i + "," + table.getRowCount());
bufferedWriter.write(table.getValueAt(i, j).toString() + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
}catch (IOException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
However be aware it is a primitive and amateur written code, but it works to some extent. You can open, change content and save file(submit), but you cannot add rows in table, you need to do it in .txt file (but you cannot leave any empty space at the end of file).
Anyway, I hope you will find something usufull here.
I have a problem creating a JTable in my GUI. The GUI is created in the main thread and enables a file to be opened. The file is then used to create a table model and add info to it. A JTable is then created with the table model and added to the GUI. My problem is that the GUI doesn't show. Code:
package example;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Example extends JFrame{
private JButton button;
private JTable table;
private DefaultTableModel model;
private String path = "C:/Users/gilbert/Documents/11111.xls";
public Example(){
super("Example");
setLayout(new BorderLayout());
button = new JButton("Start");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createTableModel_Three_By_Six(path);
}
});
add(button,BorderLayout.NORTH);
setSize(400, 400);
}
public void createTableModel_Three_By_Six(String fpath){
model = new DefaultTableModel();
ExcelParser exPareser = new ExcelParser(fpath);
int rows = exPareser.getRowNumber();
String rowToAdd[] = new String[3];
int i, j = 0;
while(j < rows){
i= 0;
while(i < 3){
rowToAdd[i] = exPareser.accessRow(j);
i++;
j++;
if(j == rows){
if(i==1){
rowToAdd[1] = "";
rowToAdd[2] = "";
}
else if(i==2){
rowToAdd[2] = "";
}
}
}
model.addRow(rowToAdd);
}
table = new JTable(model);
add(new JScrollPane(table));
}
public static void main(String[] args) {
Example app = new Example();
app.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
app.setVisible(true);
}
}
The problem, with your example, is the fact that there are no columns for the table, which means when you add the table to the frame, it doesn't know how to display the table contents.
So, by doing something as simple as...
model = new DefaultTableModel(new Object[]{"A", "B", "C"}, 0);
//...
table = new JTable(model);
add(new JScrollPane(table));
revalidate();
I was able to get the table to appear properly, with it's contents
Beware though, each time you call this method, a new JTable will be created. Instead, you should construct the JScrollPane and JTable at an earlier stage and simply update the TableModel
I want to display the JTable each time a row is added.
The code that i write below add a new row to table , then display the jtable for 2 seconds ,then add another row , then display the table. But the jtable is not displaying ,
It only display after adding all rows
Vector<Object> rowVector = null;
while(rs.next()){
rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
System.out.println(rowVector.toString());
//data.add(rowVector);
model.addRow(rowVector);
JTable table1 = new JTable(model);
JTableHeader header1 = table1.getTableHeader();
table1.setEnabled(false);
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
Thread.sleep(3000);
}
You're creating a new JTable in each iteration, you don't need to do that. Add the model to the table before the loop. And just add rows to the model in the loop
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
...
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
model.addRow(rowVector);
// DON'T CALL Thread.sleep();
}
UPDATE
If you dont want the table added until the database task is finished, just use a method
private JTable createTable(ResultSet rs) {
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
}
model.addRow(rowVector);
}
return table;
}
Then you can just add it to what ever panel
panel.add(new JScrollPane(createTable(rs));
UPDATE #2 after Op explained that they were trying to get a dynamic look the rows being added, instead of all at One time.
I used a java.swing.Timer to add the rows.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
public class TestTimerTable {
String[] cols = {"ID", "Name", "Country Code", "District", "Population"};
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
ResultSet rs = null;
JButton start = new JButton("Start");
Timer timer = new Timer(0, null);
public TestTimerTable() {
initDB();
JScrollPane scroll = new JScrollPane(table);
scroll.setViewportView(table);
JFrame frame = new JFrame("Test Timer Table");
frame.add(scroll);
frame.add(start, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
String s1 = rs.getString(1);
String s2 = rs.getString(2);
String s3 = rs.getString(3);
String s4 = rs.getString(4);
String s5 = rs.getString(5);
model.addRow(new Object[]{s1, s2, s3, s4, s5});
} else {
((Timer) e.getSource()).stop();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
}
private void initDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/...", "...", "...");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM city");
rs = ps.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTimerTable();
}
});
}
}