Fill some JTable columns with data from array - java

I have a csv file (5 columns, with | as delimiter) and I want to fill 2 JTable columns with two data columns from csv file.
public class jTable extends JFrame {
public static int rowNumber() {
int num = 0;
try {
File files = new File("C:\\BorsaItalia2.csv");
BufferedReader bf = new BufferedReader(new FileReader(files));
String lines = "";
while ((lines = bf.readLine()) != null) {
num++;
}
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
JTable table;
public jTable() {
setLayout(new FlowLayout());
String[] columnNames = {"a", "b", "c", "d", "e"};
Object[][] data = new Object[rowNumber()][5];
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(600, 950));
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
add(scroll);
}
public static void main(String[] args) {
try {
int row = 0;
int col = 0;
Object[][] imported = new Object[rowNumber()][5];
File file = new File("C:\\BorsaItalia2.csv");
BufferedReader bfr = new BufferedReader(new FileReader(file));
String line = "";
while ((line = bfr.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "|");
col = 0;
while (st.hasMoreTokens()) {
imported[row][col] = st.nextToken();
System.out.println("number["+ row + "]["
+ col + "]:" + imported[row][col]);
col++;
}
row++;
}
bfr.close();
Object[] description = new Object[imported.length];
Object[] symbol = new Object[imported.length];
for (int i = 0; i < imported.length; i++) {
description[i] = imported[i][2];
symbol[i] = imported[i][0];
}
for (int i = 1; i < imported.length; i++) {
System.out.println("Description is " + description[i]
+ " and symbol is: " + symbol[i]);
}
System.out.println("");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("error " + e);
}
jTable gui = new jTable();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(650, 950);
gui.setVisible(true);
gui.setTitle("Project Table");
}
}
I would like to fill table column a with Object[] symbol and column c with Object[] description.
Any coding help really appreciated.
Thanks all.

Instead of using the DefaultTableModel implied by your JTable constructor, create your own implementation of AbstractTableModel, as shown in How to Use Tables: Creating a Table Model. Arrange for your getValueAt() to return the data from the arrays you've read. There's a related example here.

Related

how can I "refresh" my table, so that I could display same table with different data?

How can I "refresh" my table, so that I could display same table with different data?
String columnNames[] = {"First Name", "Last Name", "Phone Number", "E-mail"};
JTable contactTable = new JTable(data, columnNames);
jScrollPane = new JScrollPane(contactTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
where is your data saved ?
i save it in a text file and use this way to refresh my data but you need a button to refresh every time
here is my code
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// Refresh Button
try {
for (int r = 0; r < 100; r++) { //initializing row
for (int c = 0; c < 4; c++) { //initializing column
jTable1.setValueAt(null, r, c);
}
}
BufferedReader rdfile = new BufferedReader(new FileReader("items.txt"));
String[] item = new String[100];
String[] temp;
int x = 0; //read item
while ((item[x] = rdfile.readLine()) != null) {
temp = item[x].split("\t");
jTable1.setValueAt((1000 + x + 1), x, 0);
for (int j = 1; j < 4; j++) {
jTable1.setValueAt(temp[j - 1], x, j);
}
x++;
}
rdfile.close();
} catch (IOException e) {
}
}

cannot return Double Value in JTable

I am making a ui in which i read data from a text file and save it to another text file after the user edits in it.i want to return integer values for all columns except column 6 and 7.For column 6 and 7 i want to return double values.Everything in this program works fine only for column 6 and column 7 when user edit in it until they enter a integer value it shows red marks in the cells whereas i should be double values for column 6 and column 7.please help
Code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Read extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Read()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("test1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens() )
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null)
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
final JTable table = new JTable(new DefaultTableModel(data, columnNames){
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return Integer.class;
}
});
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button1 = new JButton( "Save" );
buttonPanel.add( button1 );
button1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Object Value = table.getValueAt (i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("new.txt"));
fileWriter.write(con.toString());
fileWriter.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Read a = new Read();
a.setDefaultCloseOperation( EXIT_ON_CLOSE );
a.pack();
a.setVisible(true);
}
}
text file
1 2 3 4 5 6 7 8
78 12 12 45 4 0.0045 0.0078 45
45 45 69 56 7 0.0056 0.0023 21
45 89 76 42 1 0.0036 0.0023 36
TableModel#getColumnClass is used to determine which renderer AND which editor should be used by the JTable.
When you use Integer.class for the column class, the JTable sets up a JFormattedField configured to only allow whole numbers to be accepted. You need to modify the getColumnClass to return the correct data type of the given column, for example...
#Override
public Class getColumnClass(int column) {
return column == 5 || column == 6 ? Double.class : Integer.class;
}
You should also make sure that the data you are entering into the model is capable of meeting this contract, for example...
while (st2.hasMoreTokens()) {
Object num = null;
String value = st2.nextToken();
Number num = NumberFormat.getNumberInstance().parse(value);
row.addElement(num);
}

reading desired data from file but saving the whole file data

I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX

Unable to display header for jTable

These are my codes for my jTable in java swing.
private JTable getJTable() {
if (jTable == null) {
Vector columnNames = new Vector(); //Vector class allows dynamic array of objects
Vector data = new Vector();
JPanel panel = new JPanel();
panel.setSize(new Dimension(198, 106));
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select * from forumTopics";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}
String header[] = {"description", "title", "category", "posted by"};
for(int i=0;i<jTable.getColumnCount();i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel().getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.setBounds(new Rectangle(82, 218, 736, 292));
jTable.setEnabled(false);
jTable.setRowHeight(50);
jTable.getRowHeight();
}
return jTable;
}
I set an array for the header of my table. However, the program only shows the data inside my database without any header. Can somebody please enlighten me? Thanks in advance.
Put your JTable in JScrollPane like
add(new JScrollPane( getJTable() ) );

Scroll a JScrollPane to a specific row on a JTable [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JTable Scrolling to a specified row index
I have a JTable and I programmatically need to select a row by using this code:
myTable.setRowSelectionInterval(i, j);
(where i and j are valid row and column numbers respectively).
The problem is, when you jump to a row, the JScrollPane does not move.
In this case, the table is quite long, and often the "selected row" is not visible on the screen, so the user has to stay scrolling up/down manually to find it. I would like to know how I can make the JScrollPane automatically jump to the specific location of the row.
Edit: Found this one liner which can do it:
table.scrollRectToVisible(table.getCellRect(row,0, true));
just extends post by #Eng.Fouad +1, no works as I exactly expected (with kind help by StanislavL from another Java Swing forum)
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 200));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 200));
sp2.setViewportView(jTable2);
final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 200));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
TableSelectionGood tableSelection = new TableSelectionGood();
}
}
I used this in my old project:
public static void scrollToVisible(JTable table, int rowIndex, int vColIndex)
{
if (!(table.getParent() instanceof JViewport)) return;
JViewport viewport = (JViewport)table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x-pt.x, rect.y-pt.y);
viewport.scrollRectToVisible(rect);
}
Reference: http://www.exampledepot.com/egs/javax.swing.table/Vis.html

Categories

Resources