Writing a JTable
Hello,
I have a table (my own table model) and I want to write all of the data (Vector containing vectors) to a text file. Is it possible to do something similar to this taking in a vector instead of a map?
public void saveFile(SortedMap<String,String> saveData, String fileName) throws IOException{
FileOutputStream fileWrite = new FileOutputStream(fileName);
PrintStream writeData = new PrintStream(fileWrite);
Iterator write = saveData.entrySet().iterator();
while (write.hasNext()){
Map.Entry pairs = (Map.Entry)write.next();
writeData.print(pairs);
writeData.println();
writeData.flush();
writeData.close();
fileWrite.flush();
fileWrite.close();
} Based on that code I tried this but it doesn't seem to work.
public void saveFile(Vector saveData, String fileName) throws IOException{
FileOutputStream fileWrite = new FileOutputStream(fileName);
PrintStream writeData = new PrintStream(fileWrite);
Iterator write = saveData.iterator();
while (write.hasNext()){
writeData.println();
writeData.flush();
writeData.close();
fileWrite.flush();
fileWrite.close();
}I'm guessing I can not iterate over a Vector and need to write a for or while loop?
Nowhere are you referencing the vector elements. You might want to try:
while (write.hasNext())
writeData.println(write.next());
}Also calling the flush method prior to close is superfluous as the close method will call flush.
Similar Messages
-
How to write the JTables Content into the CSV File.
Hi Friends
I managed to write the Database records into the CSV Files. Now i would like to add the JTables contend into the CSV Files.
I just add the Code which Used to write the Database records into the CSV Files.
void exportApi()throws Exception
try
PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
System.out.println("Connected");
stexport=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rsexport=stexport.executeQuery("Select * from IssuedBook ");
ResultSetMetaData md = rsexport.getMetaData();
int columns = md.getColumnCount();
String fieldNames[]={"No","Name","Author","Date","Id","Issued","Return"};
//write fields names
String rec = "";
for (int i=0; i < fieldNames.length; i++)
rec +='\"'+fieldNames[i]+'\"';
rec+=",";
if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
writing.println(rec);
//write values from result set to file
rsexport.beforeFirst();
while(rsexport.next())
rec = "";
for (int i=1; i < (columns+1); i++)
try
rec +="\""+rsexport.getString(i)+"\",";
rec +="\""+rsexport.getInt(i)+"\",";
catch(SQLException sqle)
// I would add this System.out.println("Exception in retrieval in for loop:\n"+sqle);
if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
writing.println(rec);
writing.close();
}With this Same code how to Write the JTable content into the CSV Files.
Please tell me how to implement this.
Thank you for your Service
JofinHi Friends
I just modified my code and tried according to your suggestion. But here it does not print the records inside CSV File. But when i use ResultSet it prints the Records inside the CSV. Now i want to Display only the JTable content.
I am posting my code here. Please run this code and find the Report.csv file in your current Directory. and please help me to come out of this Problem.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class Exporting extends JDialog implements ActionListener
private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
private ButtonGroup bg;
private JPanel exportpanel;
private JButton btnExpots;
FileReader reading=null;
FileWriter writing=null;
JTable table;
JScrollPane scroll;
public Exporting()throws Exception
setSize(550,450);
setTitle("Export Results");
this.setLocation(100,100);
String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
{"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
{"B0203","PHP DEVELOPMENT","SUNITHA","123"},
{"B0204","PRIAM","SELVI","1354"},
{"B0205","JAVA PROGRAMING","JAMES","1234.00"},
{"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
{"B0207","PHP DEVELOPMENT","SUNITHA","123"},
{"B0208","PRIAM","SELVI","1354"}};
btnExpots= new JButton("Export");
btnExpots.addActionListener(this);
btnExpots.setBounds(140,200,60,25);
table = new JTable();
scroll=new JScrollPane(table);
((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
System.out.println(table.getModel());
exportpanel= new JPanel();
exportpanel.add(btnExpots,BorderLayout.SOUTH);
exportpanel.add(scroll);
getContentPane().add(exportpanel);
setVisible(true);
public void actionPerformed(ActionEvent ae)
Object obj=ae.getSource();
try {
PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
if(obj==btnExpots)
for(int row=0;row<table.getRowCount();++row)
for(int col=0;col<table.getColumnCount();++col)
Object ob=table.getValueAt(row,col);
//exportApi(ob);
System.out.println(ob);
System.out.println("Connected");
String fieldNames[]={"BOOK ID","NAME","AUTHOR","PRICE"};
String rec = "";
for (int i=0; i <fieldNames.length; i++)
rec +='\"'+fieldNames[i]+'\"';
rec+=",";
if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
writing.println(rec);
//write values from result set to file
rec +="\""+ob+"\",";
if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
writing.println(rec);
writing.close();
catch(Exception ex)
ex.printStackTrace();
public static void main(String arg[]) throws Exception
Exporting ex= new Exporting();
}Could anyone Please modify my code and help me out.
Thank you for your service
Cheers
Jofin -
Unable to capture VK_TAB in JTable
Hi,
One of our application screen contains a JTable. The problem in this screen is whenever the user press TAB key, the event is not gettting triggered. I have confirmed this by writing s.o.p in the ActionListener class. All the KEYS are getting fired expect VK_TAB.
The most important point is the same screen works fine in WINDOWS platform i.e VK_TAB is getting triggered. Whereas the same is not working properly in UNIX.
What could be the reason ? Do i need to make any settings ?
Please provide me the solution.
Thanks in advance,
Karthik
Message was edited by:
tkarthikeyan
Message was edited by:
tkarthikeyanHi camickr,
The following was the one, which i referred as ActionListener.
/* START - SAMPLE CODE BLOCK */
private void registerTabEvent(){
new DBPTabListener(this);
public class DBPTabListener implements ActionListener {
public DBPTabListener(JTable tabJtable){
tabJtable.registerKeyboardAction(this,"TAB_KEY",KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0,false),JComponent.WHEN_FOCUSED);
public void actionPerformed(ActionEvent e)
System.out.println("key pressed = " + e.getActionCommand());
if (e.getActionCommand().compareTo("TAB_KEY")==0) {
System.out.println("TAB_KEY has been pressed");
/* END - SAMPLE CODE BLOCK */
Moreover inputMap solution also doesn't work for us as we use JDK 1.2.2
Following is the JDK version which we use for our application.
java version "1.2.2"
Solaris VM (build Solaris_JDK_1.2.2_10, native threads, sunwjit)
This version doesn't have setInputMap() & getInputMap for JComponents.
Could you please help me out.
Thanks in advance,
Karthik -
Inserting a Row to a Specific Position in a Sorted JTable
Hello,
I am currently writing an application that will be a network alerting tool. Periodically it will query a database, and if alerts are found, display them on a JTable for a user to see. However, my problem is the following. If the user sorts the table by a column, new alerts are entering the table in their sorted position. This could cause the table to rearrange and be confusing to the user, also causing them to possibly miss alerts. So, what I would like to happen is that new alerts get inserted at the top of the table, while all previous alerts will stay in their sorted order. For example, say alerts received in the order D A C B . The user then sorts the table, so that the alerts are now in the order A B C D. If alert E comes in, I want the table to show as E A B C D. Then, if the user sorts again, the table would become A B C D E, and so on.
I have attempted multiple ways to achieve this. My most recent being using the table.setRowSorter(null), inserting into the model, and then re-enabling sorting. However, switching to null appears to make all the rows go back to their previously unsorted position. Any help would be greatly appreciated as to what I am missing.You can implement your own RowSorter, such that rows that have been added since the latest explicit sort are ranked first (override RowSorter.rowsInserted() to know them).
You'll have to override methods convertRowIndexToModel(int) and convertRowIndexToView(int) . This is easy if you used the rowsInserted() events to, e.g., maintain one atrribute latestUnsortedRow. -
How do I change the colour of a selected cell in a jTable?
I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
Thanks.
Chrishttp://www2.gol.com/users/tame/swing/examples/SwingExamples.html
there you can find some examples with CellRenderer's and so on ...
have fun -
How to edit databases from JTable?
Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
I have the installer of an application which I made with Java SE called FuelStation.exe
My class files are ready for sharing along with its source files.
I have placed it in this location in my website:
http://www.apachevista.com/alphaprojects/runfiles/
It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
Here is my sample code:
// DisplayQueryResults.java
// Display the contents of the Authors table in the
// Books database.
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JInternalFrame;
import java.util.*; // for the Bundle
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.event.InternalFrameAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.*; // step 1
import javax.swing.table.TableModel; // step 1
public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
// JDBC driver, database URL, username and password
ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
final String JDBC_DRIVER = bundle.getString("Driver");
final String DATABASE_URL = bundle.getString("URL");
final String USERNAME = bundle.getString("User");
final String PASSWORD = bundle.getString("Password");
// default query retrieves all data from authors table
//static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
final String DEFAULT_QUERY = bundle.getString("Query");
private ResultSetTableModel tableModel;
private JTextArea queryArea;
static final int xOffset = 0, yOffset = 200;
private boolean ALLOW_COLUMN_SELECTION = false;
private boolean ALLOW_ROW_SELECTION = true;
// create ResultSetTableModel and GUI
public DisplayQueryResults() {
super("Sales of the Day",
true, //resizable
true, //closable
true, //maximizable
false);//iconifiable
//...Create the GUI and put it in the window...
//Set the window's location.
setLocation(xOffset, yOffset);
// create ResultSetTableModel and display database table
try {
// create TableModel for results of query SELECT * FROM authors
tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
USERNAME, PASSWORD, DEFAULT_QUERY);
// set up JTextArea in which user types queries
queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
queryArea.setWrapStyleWord(true);
queryArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(queryArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// set up JButton for submitting queries
JButton submitButton = new JButton("Submit Query");
// create Box to manage placement of queryArea and
// submitButton in GUI
Box box = Box.createHorizontalBox();
box.add(scrollPane);
box.add(submitButton);
// create JTable delegate for tableModel
JTable resultTable = new JTable(tableModel);
resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
resultTable.setRowSelectionAllowed(true);
resultTable.getModel().addTableModelListener(this); // step 3
// place GUI components on content pane
add(box, BorderLayout.NORTH);
add(new JScrollPane(resultTable), BorderLayout.CENTER);
// create event listener for submitButton
submitButton.addActionListener(
new ActionListener()
// pass query to table model
public void actionPerformed(ActionEvent event)
// perform a new query
try
tableModel.setQuery(queryArea.getText());
} // end try
catch ( SQLException sqlException)
JOptionPane.showMessageDialog(null,
sqlException.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE);
// try to recover from invalid user query
// by executing default query
try {
tableModel.setQuery(DEFAULT_QUERY);
queryArea.setText(DEFAULT_QUERY);
} // end try
catch (SQLException sqlException2) {
JOptionPane.showMessageDialog(null,
sqlException2.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE);
// ensure database connection is closed
tableModel.disconnectFromDatabase();
System.exit(1); // terminate application
} // end inner catch
} // end outer catch
} // end actionPerformed
} // end ActionListener inner class
); // end call to addActionListener
//...Then set the window size or call pack...
setSize(750,300);
setVisible(true); // display window
} // end try
catch (ClassNotFoundException classNotFound) {
JOptionPane.showMessageDialog(null,
"MySQL driver not found", "Driver not found",
JOptionPane.ERROR_MESSAGE);
System.exit(1); // terminate application
} // end catch
catch (SQLException sqlException) {
JOptionPane.showMessageDialog(null, sqlException.getMessage(),
"Database error", JOptionPane.ERROR_MESSAGE);
// ensure database connection is closed
tableModel.disconnectFromDatabase();
System.exit(1); // terminate application
} // end catch
// dispose of window when user quits application (this overrides
// the default of HIDE_ON_CLOSE)
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// ensure database connection is closed when user quits application
addInternalFrameListener(
new InternalFrameAdapter() {
// disconnect from database and exit when window has closed
public void windowClosed(WindowEvent event) {
tableModel.disconnectFromDatabase();
System.exit(0);
} // end method windowClosed
} // end WindowAdapter inner class
); // end call to addWindowListener
} // end DisplayQueryResults constructor
public void tableChanged(TableModelEvent e) { // step 4
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object tableModel = model.getValueAt(row, column);
// Do something with the data...
System.out.println(tableModel);
System.out.println("data");
// execute application
public static void main(String args[]) {
new DisplayQueryResults();
} // end main
} // end class DisplayQueryResults
My question is in lines 177-187:
public void tableChanged(TableModelEvent e) { // step 4
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object tableModel = model.getValueAt(row, column);
// Do something with the data...
System.out.println(tableModel);
System.out.println("data");
Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
PS:
When you have solved the problem, please notify me with the code that's changed
and please share it to others if you like so.
Best Wishes: Oliver Bob Lagumen
Email: [email protected]
website: www.apachevista.com
Oliver Bob Lagumen
Edited by: Oliverbob on Jan 24, 2008 9:03 PMWhy is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
When you have solved the problem, please notify me with the code that's changedAvoid this.
What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours. -
Intercepting editing start and stop/cancel in a JTable
Hi,
I've been seaching the forum for days but could not find anything that solved my problem.
Problem:
I'm writing a multiclient server. The data of the server is displayed in a JTable. The rows(cells) in the table is editable and to make sure no two clients edit the same row at the same time I've implemented a locking mechanism in the server and would like to lock a row whenever a user starts editing and release the lock when the user either stops or cancels editing.
The JTable is 'hooked up' with a TableModel class that I've written to handle the locking and notification of the lock and unlock events from the server.
I've tried a couple of things but non worked very good. It would be nice if the CellEditorListener implemented a startEditing but it does not so letting my model implement the interface was no good.
Any ideas? If anyone knows how to solve this, please reply
Yours, JohanPlaying around with some methods in JTable, and some minimal testing, I came up with:
table = new JTable(...)
private int editingRow = -1;
public boolean editCellAt(int row, int column, EventObject e)
boolean editingCell = super.editCellAt(row, column, e);
if (isEditing())
editingRow = row;
System.out.println("started");
return editingCell;
public void removeEditor()
if (isEditing())
editingRow = -1;
System.out.println("stopped");
super.removeEditor();
}; -
JTable sorting - problem when adding elements (complete code inside)
I�m writing this email with reference to a recent posting here but this time with the code example. (I apologize for the duplicated posting � this time it will be with the code)
Problem: when adding more elements to the JTable (sorted) the exception: ArrayIndexOutOfBoundsException is thrown.
Example: If the elements in the table are 10 and then the user requests for 8 � the table will produce the correct result. However, if the user will ask for 11 items (>10) the exception will be thrown.
The program: The program below (compiles and running). A JTable is constructed with 3 items, when you click the button - the return result should be 4 items - this will generate the error, WHY?
I would highly appreciate your thoughts why this is happening and most importantly � how to fix it.
Thanks a lot
3 files:
(1) TableSorterDemo
(2) Traveler
(3)TableSorter
//TableSorterDemo:
package sorter;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
* TableSorterDemo is like TableDemo, except that it
* inserts a custom model -- a sorter -- between the table
* and its data model. It also has column tool tips.
public class TableSorterDemo implements ActionListener
private JPanel superPanel;
private JButton clickMe = new JButton("click me to get diff data");
private boolean DEBUG = false;
private DefaultListModel defaultListModel;
private JTable table;
public TableSorterDemo()
superPanel = new JPanel(new BorderLayout());
defaultListModel = new DefaultListModel();
init1();
TableSorter sorter = new TableSorter(new MyTableModel(defaultListModel)); //ADDED THIS
table = new JTable(sorter); //NEW
sorter.setTableHeader(table.getTableHeader()); //ADDED THIS
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Set up tool tips for column headers.
table.getTableHeader().setToolTipText(
"Click to specify sorting; Control-Click to specify secondary sorting");
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
superPanel.add("Center", scrollPane);
superPanel.add("South",clickMe);
clickMe.addActionListener(this);
public JPanel getPanel()
return superPanel;
public void init1()
//in real life this will be done from the db
Traveler a = new Traveler();
Traveler b = new Traveler();
Traveler c = new Traveler();
a.setFirstName("Elvis");
a.setLastName("Presley");
a.setSprot("Ping Pong");
a.setNumYears(3);
a.setVegetarian(true);
b.setFirstName("Elton");
b.setLastName("John");
b.setSprot("Soccer");
b.setNumYears(2);
b.setVegetarian(true);
c.setFirstName("shaquille");
c.setLastName("oneil");
c.setSprot("Golf");
c.setNumYears(22);
c.setVegetarian(true);
defaultListModel.addElement(a);
defaultListModel.addElement(b);
defaultListModel.addElement(c);
public void init2()
//in real life this will be done from the db
Traveler d = new Traveler();
Traveler e = new Traveler();
Traveler f = new Traveler();
Traveler g = new Traveler();
d.setFirstName("John");
d.setLastName("Smith");
d.setSprot("Tennis");
d.setNumYears(32);
d.setVegetarian(true);
e.setFirstName("Ron");
e.setLastName("Cohen");
e.setSprot("Baseball");
e.setNumYears(12);
e.setVegetarian(true);
f.setFirstName("Donald");
f.setLastName("Mac Novice");
f.setSprot("Vallyball");
f.setNumYears(1);
f.setVegetarian(true);
g.setFirstName("Eithan");
g.setLastName("Superstar");
g.setSprot("Vallyball");
g.setNumYears(21);
g.setVegetarian(true);
defaultListModel.addElement(d);
defaultListModel.addElement(e);
defaultListModel.addElement(f);
defaultListModel.addElement(g);
class MyTableModel extends AbstractTableModel
private DefaultListModel myModel;
public MyTableModel(DefaultListModel m)
myModel=m;
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return myModel.size();
public String getColumnName(int column)
return getNames()[column];
public String[] getNames()
String[] names = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
return names;
public Object getValueAt(int row, int col)
return distributeObjectsInTable(row, col, (Traveler) myModel.elementAt(row));
public Object distributeObjectsInTable(int row, int col, Traveler tr)
switch(col)
case 0:
return tr.getFirstName();
case 1:
return tr.getLastName();
case 2:
return tr.getSprot();
case 3:
return new Integer(tr.getNumYears());
case 4:
return new Boolean (tr.isVegetarian());
default:
return "Error";
public Class getColumnClass(int c)
return getValueAt(0, c).getClass();
private static void createAndShowGUI()
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TableSorterDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableSorterDemo newContentPane = new TableSorterDemo();
newContentPane.getPanel().setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane.getPanel());
//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();
public void actionPerformed(ActionEvent ae)
if (ae.getSource()==clickMe)
defaultListModel.removeAllElements();
init2(); //if the size of the model was less than 2 items - the result will be ok.
//in other words, if you commens the last 2 rows of this method (addElement(f) & g)
// the result will be fine.
table.updateUI();
}//(2) Traveler
package sorter;
public class Traveler
private String firstName;
private String lastName;
private String sprot;
private int numYears;
private boolean vegetarian;
public String getFirstName()
return firstName;
public String getLastName()
return lastName;
public int getNumYears()
return numYears;
public String getSprot()
return sprot;
public boolean isVegetarian()
return vegetarian;
public void setFirstName(String firstName)
this.firstName = firstName;
public void setLastName(String lastName)
this.lastName = lastName;
public void setNumYears(int numYears)
this.numYears = numYears;
public void setSprot(String sprot)
this.sprot = sprot;
public void setVegetarian(boolean vegetarian)
this.vegetarian = vegetarian;
}//(3)TableSorter
package sorter;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
public class TableSorter extends AbstractTableModel {
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
private void clearSortingState() {
viewToModel = null;
modelToView = null;
public TableModel getTableModel() {
return tableModel;
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
clearSortingState();
fireTableStructureChanged();
public JTableHeader getTableHeader() {
return tableHeader;
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
public boolean isSorting() {
return sortingColumns.size() != 0;
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
return EMPTY_DIRECTIVE;
public int getSortingStatus(int column) {
return getDirective(column).direction;
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
sortingStatusChanged();
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
private void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
return LEXICAL_COMPARATOR;
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
if (isSorting()) {
Arrays.sort(viewToModel);
return viewToModel;
public int modelIndex(int viewIndex)
return getViewToModel()[viewIndex].modelIndex;
private int[] getModelToView()
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
return modelToView;
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
public String getColumnName(int column) {
return tableModel.getColumnName(column);
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
return 0;
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
// We can map a cell event through to the view without widening
// when the following conditions apply:
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
public int getIconWidth() {
return size;
public int getIconHeight() {
return size;
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
return c;
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}The table listens to the TableModel for changes. Changing the table by adding/removing
rows or columns has no affect on its table model. If you make changes to the table model
the table will be notified by its TableModelListener and change its view. So tell
MyTableModel about the change of data:
public class TableSorterDemo implements ActionListener
MyTableModel tableModel;
public TableSorterDemo()
defaultListModel = new DefaultListModel();
init1();
tableModel = new MyTableModel(defaultListModel);
TableSorter sorter = new TableSorter(tableModel);
public void actionPerformed(ActionEvent ae)
if (ae.getSource()==clickMe)
defaultListModel.removeAllElements();
init2();
tableModel.fireTableStructureChanged();
} -
Hi!
I'm currently using preferences API to back-up my jTable (lots of coding).
can I back up my entire jTable with single serialization file?
try {
FileOutputStream fos = new FileOutputStream (jTable);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (table.ser);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}can you show me an example of how that is done?Sorry, I don't feel like writing the code, but I
would guess that opening a file, writing a loop,
write some data, and close the file is done inless
than 30-40 lines of code.
KajWhen you say "write a loop" do you infer that the
data must be extracted by row and column coordinates?Yes -
How can I add a new row in a JTable dynamically?
Dear Sir(s)
I want to add a new row in a Jtable as I press enter key the time focus is on the last cell of the row? pls helpTomDooley wrote:
Hello,
...I write directly to a cvs file ...my loop slows down to 0.2 Hz
Writing a series of 5 values to a file should not take so long. There is probably something wrong in the way you are saving your data. May be you should post a simplified version of your vi, so we could see how to improve your code.
CC
Chilly Charly (aka CC)
E-List Master - Kudos glutton - Press the yellow button on the left... -
Jtable Update problem .. Please help !!!!!!!!
Hi ,
I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
Here is the code .... Please see it and tell me if it is possible :
package newpackage;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.*;
import newpackage.ExcelExporter;
import java.awt.Dimension;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.*;
import java.io.*;
import java.util.Random.*;
import javax.swing.*;
import java.text.*;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class tab7le extends javax.swing.JFrame {
Vector columnNames = new Vector();
Vector data = new Vector();
Connection con;
Statement stat;
ResultSet rs;
int li_cols = 0;
Vector allRows;
Vector row;
Vector newRow;
Vector colNames;
String dbColNames[];
String pkValues[];
String tableName;
ResultSetMetaData myM;
String pKeyCol;
Vector deletedKeys;
Vector newRows;
boolean ibRowNew = false;
boolean ibRowInserted = false;
private Map<String, Color> colormap = new HashMap<String, Color>();
/** Creates new form tab7le */
public tab7le() {
populate();
initComponents();
public void updateDB(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e){
System.out.println("Cannot Load Driver!");
try{
String url = "jdbc:odbc:FAMS";
con = DriverManager.getConnection(url);
stat = con.createStatement();
rs = stat.executeQuery("Select * from SubAllot");
deletedKeys = new Vector();
newRows = new Vector();
myM = rs.getMetaData();
tableName = myM.getTableName(1);
li_cols = myM.getColumnCount();
dbColNames = new String[li_cols];
for(int col = 0; col < li_cols; col ++){
dbColNames[col] = myM.getColumnName(col + 1);
allRows = new Vector();
while(rs.next()){
newRow = new Vector();
for(int i = 1; i <= li_cols; i++){
newRow.addElement(rs.getObject(i));
} // for
allRows.addElement(newRow);
} // while
catch(SQLException e){
System.out.println(e.getMessage());
String updateLine[] = new String[dbColNames.length];
try{
DatabaseMetaData dbData = con.getMetaData();
String catalog;
// Get the name of all of the columns for this table
String curCol;
colNames = new Vector();
ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
while (rset1.next()) {
curCol = rset1.getString(4);
colNames.addElement(curCol);
rset1.close();
pKeyCol = colNames.firstElement().toString();
// Go through the rows and perform INSERTS/UPDATES/DELETES
int totalrows;
totalrows = allRows.size();
String dbValues[];
Vector currentRow = new Vector();
pkValues = new String[allRows.size()];
// Get column names and values
for(int i=0;i < totalrows;i++){
currentRow = (Vector) allRows.elementAt(i);
int numElements = currentRow.size();
dbValues = new String[numElements];
for(int x = 0; x < numElements; x++){
String classType = currentRow.elementAt(x).getClass().toString();
int pos = classType.indexOf("String");
if(pos > 0){ // we have a String
dbValues[x] = "'" + currentRow.elementAt(x) + "'";
updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
pos = classType.indexOf("Integer");
if(pos > 0){ // we have an Integer
dbValues[x] = currentRow.elementAt(x).toString();
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString();
else{
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
pos = classType.indexOf("Boolean");
if(pos > 0){ // we have a Boolean
dbValues[x] = currentRow.elementAt(x).toString();
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
} // For Loop
// If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
int numNewRows = newRows.size();
int insertRow = 0;
boolean newRowFound;
for (int z = 0;z < numNewRows;z++){
insertRow = ((Integer) newRows.get(z)).intValue();
if(insertRow == i+1){
StringBuffer InsertSQL = new StringBuffer();
InsertSQL.append("INSERT INTO " + tableName + " (");
for(int zz=0;zz<=dbColNames.length-1;zz++){
if (dbColNames[zz] != null){
InsertSQL.append(dbColNames[zz] + ",");
// Strip out last comma
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
InsertSQL.append(" VALUES(" + pkValues[i] + ",");
for(int c=1;c < dbValues.length;c++){
InsertSQL.append(dbValues[c] + ",");
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
System.out.println(InsertSQL.toString());
stat.executeUpdate(InsertSQL.toString());
ibRowInserted=true;
} // End of INSERT Logic
// If row has not been INSERTED perform an UPDATE
if(ibRowInserted == false){
StringBuffer updateSQL = new StringBuffer();
updateSQL.append("UPDATE " + tableName + " SET ");
for(int z=0;z<=updateLine.length-1;z++){
if (updateLine[z] != null){
updateSQL.append(updateLine[z]);
// Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
System.out.println(updateSQL.toString());
stat.executeUpdate(updateSQL.toString());
} //for
catch(Exception ex){
System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
// Delete records from the DB
try{
int numDeletes = deletedKeys.size();
String deleteSQL;
for(int i = 0; i < numDeletes;i++){
deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
((Integer) deletedKeys.get(i)).toString();
System.out.println(deleteSQL);
stat.executeUpdate(deleteSQL);
// Assume deletes where successful. Recreate Vector holding PK Keys
deletedKeys = new Vector();
catch(Exception ex){
System.out.println(ex.getMessage());
public void populate()
try
// Connect to the Database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
System.out.println("ok1");
// Read data from a table
String sql;
sql = "Select * from SubAllot";
System.out.println("ok1");
Statement stmt = con.createStatement();
System.out.println("ok1");
ResultSet rs = stmt.executeQuery( sql );
System.out.println("ok1");
ResultSetMetaData md = rs.getMetaData();
System.out.println("ok1");
int columns = md.getColumnCount();
for(int i = 0;i<columns;i++){
columnNames.addElement(md.getColumnName(i+1));
System.out.println("ok2");
while (rs.next())
Vector row = new Vector(columns);
for (int i = 1; i <columns+1; i++)
row.addElement( rs.getObject(i) );
data.addElement( row );
catch(Exception e){
e.printStackTrace();
public void dropmenu(JTable table,TableColumn subpref1) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
for (int i = 0;i<=20;i++)
comboBox.addItem(i);
subpref1.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
subpref1.setCellRenderer(renderer);
abstract class StringTransferHandler extends TransferHandler {
public int dropAction;
protected abstract String exportString(final JComponent c);
protected abstract void importString(final JComponent c, final String str);
@Override
protected Transferable createTransferable(final JComponent c) {
return new StringSelection(exportString(c));
@Override
public int getSourceActions(final JComponent c) {
return MOVE;
@Override
public boolean importData(final JComponent c, final Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String) t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
} catch (UnsupportedFlavorException ufe) {
} catch (IOException ioe) {
return false;
@Override
public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
for (int ndx = 0; ndx < flavors.length; ndx++) {
if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
return true;
return false;
class TableTransferHandler extends StringTransferHandler {
private int dragRow;
private int[] dragColumns;
private BufferedImage[] image;
private int row;
private int[] columns;
public JTable target;
private Map<String, Color> colormap;
private TableTransferHandler(final Map<String, Color> colormap) {
this.colormap = colormap;
@Override
protected Transferable createTransferable(final JComponent c) {
JTable table = (JTable) c;
dragRow = table.getSelectedRow();
dragColumns = table.getSelectedColumns();
createDragImage(table);
return new StringSelection(exportString(c));
protected String exportString(final JComponent c) {
JTable table = (JTable) c;
row = table.getSelectedRow();
columns = table.getSelectedColumns();
StringBuffer buff = new StringBuffer();
colormap.clear();
for (int j = 0; j < columns.length; j++) {
Object val = table.getValueAt(row, columns[j]);
buff.append(val == null ? "" : val.toString());
if (j != columns.length - 1) {
buff.append(",");
colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
table.repaint();
return buff.toString();
protected void importString(final JComponent c, final String str) {
target = (JTable) c;
DefaultTableModel model = (DefaultTableModel) target.getModel();
String[] values = str.split("\n");
int colCount = target.getSelectedColumn();
int max = target.getColumnCount();
for (int ndx = 0; ndx < values.length; ndx++) {
String[] data = values[ndx].split(",");
for (int i = 0; i < data.length; i++) {
String string = data;
if(colCount < max){
Object val = model.getValueAt(target.getSelectedRow(), colCount);
model.setValueAt(string, target.getSelectedRow(), colCount);
model.setValueAt(val, dragRow, dragColumns[i]);
colCount++;
public BufferedImage[] getDragImage() {
return image;
private void createDragImage(final JTable table) {
if (dragColumns != null) {
try {
image = new BufferedImage[dragColumns.length];
for (int i = 0; i < dragColumns.length; i++) {
Rectangle cellBounds = table.getCellRect(dragRow, i, true);
TableCellRenderer r = table.getCellRenderer(dragRow, i);
DefaultTableModel m = (DefaultTableModel) table.getModel();
JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
lbl.setBounds(cellBounds);
BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
lbl.paint(graphics);
graphics.dispose();
image[i] = img;
} catch (RuntimeException re) {
class TableDropTarget extends DropTarget {
private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
private Rectangle rect2D = new Rectangle();
private TableTransferHandler handler;
public TableDropTarget(final TableTransferHandler h) {
super();
this.handler = h;
@Override
public void dragOver(final DropTargetDragEvent dtde) {
handler.dropAction = dtde.getDropAction();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
Point location = dtde.getLocation();
int row = table.rowAtPoint(location);
int column = table.columnAtPoint(location);
table.changeSelection(row, column, false, false);
paintImage(table, location);
autoscroll(table, location);
super.dragOver(dtde);
public void dragExit(final DropTargetDragEvent dtde) {
clearImage((JTable) dtde.getDropTargetContext().getComponent());
super.dragExit(dtde);
@Override
public void drop(final DropTargetDropEvent dtde) {
Transferable data = dtde.getTransferable();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
clearImage(table);
handler.importData(table, data);
super.drop(dtde);
private final void paintImage(final JTable table, final Point location) {
Point pt = new Point(location);
BufferedImage[] image = handler.getDragImage();
if (image != null) {
table.paintImmediately(rect2D.getBounds());
rect2D.setLocation(pt.x - 15, pt.y - 15);
int wRect2D = 0;
int hRect2D = 0;
for (int i = 0; i < image.length; i++) {
table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
pt.x += image[i].getWidth();
if (hRect2D < image[i].getHeight()) {
hRect2D = image[i].getHeight();
wRect2D += image[i].getWidth();
rect2D.setSize(wRect2D, hRect2D);
private final void clearImage(final JTable table) {
table.paintImmediately(rect2D.getBounds());
private Insets getAutoscrollInsets() {
return autoscrollInsets;
private void autoscroll(final JTable table, final Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = table.getVisibleRect();
Rectangle inner = new Rectangle(outer.x + insets.left,
outer.y + insets.top,
outer.width - (insets.left + insets.right),
outer.height - (insets.top + insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
cursorLocation.y - insets.top,
insets.left + insets.right,
insets.top + insets.bottom);
table.scrollRectToVisible(scrollRect);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setModel(new javax.swing.table.DefaultTableModel(
data, columnNames
jScrollPane1.setViewportView(table);
//populate();
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setDragEnabled(true);
TableTransferHandler th = new TableTransferHandler(colormap);
table.setTransferHandler(th);
table.setDropTarget(new TableDropTarget(th));
dropmenu(table, table.getColumnModel().getColumn(11));
jButton1.setText("Update");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Ex");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(347, 347, 347)
.addComponent(jButton1)
.addGap(115, 115, 115)
.addComponent(jButton2)))
.addContainerGap(73, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButton1)
.addContainerGap(83, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addGap(65, 65, 65))))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
updateDB(); // TODO add your handling code here:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
pathToDesktop = pathToDesktop + "//Final Allotment.xls";
ExcelExporter exp = new ExcelExporter();
exp.exportTable(table, new File(pathToDesktop));
JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
} // TODO add your handling code here:
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new tab7le().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
// End of variables declaration
Please help !!!!!!!!
Thanks in advance.....Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
Why post code with access to a database? We can't access the database.
Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour. -
Hello, I am having a hard time getting my JTable to show up on my panel. There is a fair bit of code to wade through so I have put comments in all CAPS lined with an '*' so it should be easy to find where I am having my problems.
What I would like to do is have a new table row added each time the user enters a service and clicks a button. A service name and an integer for the durration of the service. Additonaly the opposite when the remove service button is clicked.
When running the app, click the employees tab; there is a NullPointerException error right now with the line
return getValueAt(0, c).getClass(); at line 904 once that tab is clicked.
Things to look for in my code are:
-westPanel
-westRight
-table
-MyTableModel
-scrollpane2
-(maybe servicePanel) undecided and it is commented out at this moment.
Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.
Thanks in advance.
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.table.AbstractTableModel;
public class Administration extends JFrame implements ActionListener,ListSelectionListener,ItemListener {
private JTabbedPane jtp;
public String[] columnNames;
public Object[][] data;
public static JPanel servicePanel;
public static int checkRow;
private JPanel westPanel;
private JPanel westTop;
private JPanel westCenter;
private JPanel westCenterTop;
private JPanel westCenterBottom;
private JPanel westBottom;
private JPanel westBottomRight;
private JPanel westLeft;
private JPanel westRightTop;
private JPanel westRight;
private JPanel northPanel;
private JPanel centerPanel;
private JPanel centerRight;
private JPanel centerLeft;
private JPanel eastPanel;
private JPanel eastRight;
private JPanel eastLeft;
private JPanel eastBottom;
public static JPanel eastEastTop;
private JPanel eastEastCenter;
private JPanel southPanel;
private JPanel southTop;
private JPanel southLeft;
private JPanel southCenter;
private JPanel southBottom;
private GridBagLayout gbl;
private GridBagConstraints gbc;
//private JComboBox employees;
private JComboBox[] openAmPm = new JComboBox[7];
private JComboBox[] closedAmPm = new JComboBox[7];
private JComboBox startAmPm;
private JComboBox endAmPm;
private JComboBox cmbServices;
private JList employees;
private JList listEmpl;
private JList listServices;
private JList listDays;
private JList listSchedule;
//private Vector nameData;
private JScrollPane scrollpane;
private JScrollPane scrollpane2;
private JScrollPane scrollPane3;
private JScrollPane scrollPane4;
private JLabel lblEmployees;
public static JLabel lblEmployeeName;
public static JLabel lblMonthStat;
public static JLabel lblDay;
public static JLabel lblYear;
public static String service = null;
private JLabel lblLength;
private JLabel lblBizHours;
private JLabel lblServices;
private JLabel lblHoliday;
private JLabel lblOpen;
private JLabel lblClosed;
private JLabel lblsouthHeading;
private JLabel lblStartTime;
private JLabel lblEndTime;
private JLabel lblDayOff;
private JLabel space;
private JLabel space2;
private JLabel space3;
private JLabel space4;
private JLabel space5;
private JLabel blank1;
private JLabel blank2;
private JLabel colon;
private JLabel colon2;
private JLabel lblSelect;
private JLabel[] weekDay =new JLabel[7];
//private String[] fakeName = {"Leon","Mike","Lori","Shannon","Rob"};
private final static String[] dow = {"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"};
public static JTextField[] startHr = new JTextField[7];
public static JTextField[] startMin = new JTextField[7];
public static JTextField[] finishHr = new JTextField[7];
public static JTextField[] finishMin = new JTextField[7];
private JButton[] btnUpdate = new JButton[7];
private JButton btnAddEmployee;
private JButton btnNextDay;
private DefaultListModel nameData;
private DefaultListModel serviceData;
private DefaultListModel dayData;
private DefaultListModel holidayData;
private DefaultListModel scheduleData;
private static final String hireString="Add Employee";
private static final String fireString="Remove Employee";
private static final String addService="Add Service";
private static final String removeService="Remove Service";
private JButton fireButton;
private JButton hireButton;
private JButton addServices;
private JButton removeServices;
private JButton btnAttatch;
private JTextField employeeName;
private JTextField serviceName;
private JTextField txtOpenTime;
private JTextField txtClosedTime;
private int size;
public static String timeText;
private boolean result;
private boolean totalResult;
private String holidayMsg = "Here, you can select and \n schedule off days \n for employees from \n the list";
private String message1 = "Enter a maximum of \n 3 digits";
private String message2 = "Enter numbers only";
private String minutes=" min";
private String name;
private boolean dbRecord=true;
private int serviceSize;
private JCheckBox[] dayOff = new JCheckBox[7];
private int jlistCellWidth =100;
public static final int MAX_CHARS = 1;
private String myMonth;
public static boolean removed=false;
public Administration()
//jtp.setDefaultLookAndFeelDecorated(true);
checkRow = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
//employees = new JComboBox();
//employees.setEditable(false);
cmbServices = new JComboBox();
startAmPm = new JComboBox();
startAmPm.addItem("AM");
startAmPm.addItem("PM");
startAmPm.setEditable(false);
endAmPm = new JComboBox();
endAmPm.addItem("AM");
endAmPm.addItem("PM");
endAmPm.setEditable(false);
employeeName=new JTextField("",10);
serviceName = new JTextField("",10);
txtOpenTime = new JTextField("",5);
txtClosedTime = new JTextField("",5);
nameData = new DefaultListModel();
holidayData = new DefaultListModel();
/** Eventualy put this into an isItemSelected function that retrieves names from
* the database
/*nameData.addElement("Leon");
nameData.addElement("Brenda");
nameData.addElement("Megumi");
nameData.addElement("jun");
//populate employee combobox with names from nameData
//int listSize = nameData.getSize();
/* for(int i=0;i<fakeName.length;i++)
nameData.addElement(fakeName);
//listEmpl.setSelectedIndex(i);
//String eName =(String)nameData.get(listEmpl.getSelectedIndex());
holidayData.addElement(fakeName[i]);
serviceData = new DefaultListModel();
dayData = new DefaultListModel();
listEmpl=new JList(nameData);
listEmpl.addListSelectionListener(this);
listServices = new JList(serviceData);
employees = new JList(holidayData);
employees.addListSelectionListener(this);
employees.setFixedCellWidth(jlistCellWidth);
listDays = new JList(dayData);
scheduleData = new DefaultListModel();
listSchedule = new JList(scheduleData);
listSchedule.setFixedCellWidth(jlistCellWidth);
dayData.addElement("Sunday");
dayData.addElement("Monday");
dayData.addElement("Tuesday");
dayData.addElement("Wednesday");
dayData.addElement("Thursday");
dayData.addElement("Friday");
dayData.addElement("Saturday");
// listEmpl.setSelectedIndex(0);
listDays.setSelectedIndex(0);
listSchedule.setSelectedIndex(0);
//listEmpl.addListSelectionListener(this);
listEmpl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listDays.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
employees.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
size = nameData.getSize();
//employeeName.setText("size is "+size);
listEmpl.setVisibleRowCount(5);
listDays.setVisibleRowCount(7);
employees.setVisibleRowCount(5);
listSchedule.setVisibleRowCount(5);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.CENTER;
//declare labels
lblLength = new JLabel("SERVICE LENGTH",lblLength.CENTER);
lblSelect=new JLabel("Select a name from the list",lblSelect.CENTER);
lblsouthHeading = new JLabel("EMPLOYEE SCHEDULE",lblsouthHeading.CENTER);
lblEmployees = new JLabel("CURRENT EMPLOYEES",lblEmployees.CENTER);
lblEmployees.setOpaque(true);
//lblEmployees.setBackground(Color.yellow);
lblServices = new JLabel("CURRENT SERVICES",JLabel.LEFT);
lblBizHours= new JLabel("BUSINESS HOURS",lblBizHours.CENTER);
lblStartTime = new JLabel("Open",lblStartTime.LEFT);
lblEndTime = new JLabel("Closed",lblEndTime.LEFT);
blank1 = new JLabel("");
blank2=new JLabel("");
lblHoliday = new JLabel(holidayMsg);
lblEmployeeName = new JLabel("Name");
//lblEmployeeName.setForeground(Color.white);
lblMonthStat = new JLabel("");
lblDay = new JLabel("");
lblYear = new JLabel("");
//check myCalendar method to see if a button has been clicked
lblMonthStat.setForeground(Color.white);
lblDay.setForeground(Color.white);
lblYear.setForeground(Color.white);
//declare buttons
JButton btnAttatch = new JButton("<html>Attatch service<br> to employee</html>");
btnAttatch.setBorder(BorderFactory.createRaisedBevelBorder());
JButton fireButton = new JButton(fireString);
JButton hireButton = new JButton(hireString);
JButton addServices = new JButton(addService);
JButton removeServices = new JButton(removeService);
addServices.addActionListener(this);
addServices.setActionCommand(addService);
removeServices.addActionListener(this);
removeServices.setActionCommand(removeService);
hireButton.addActionListener(this);
fireButton.setActionCommand(fireString);
fireButton.addActionListener(this);
JButton btnAddEmployee = new JButton("Add Employee");
fireButton.setBorder(BorderFactory.createRaisedBevelBorder());
JButton btnServices = new JButton("Add Service");
addServices.setBorder(BorderFactory.createRaisedBevelBorder());
removeServices.setBorder(BorderFactory.createRaisedBevelBorder());
hireButton.setBorder(BorderFactory.createRaisedBevelBorder());
//declare layouts
BorderLayout southBorder = new BorderLayout();
FlowLayout flo = new FlowLayout(FlowLayout.CENTER,30,30);
FlowLayout westFlo = new FlowLayout(FlowLayout.CENTER,10,10);
FlowLayout southFlo = new FlowLayout(FlowLayout.LEFT,10,10);
GridLayout northGrid = new GridLayout(0,4);
GridLayout southGrid = new GridLayout(1,1);
GridLayout westGrid = new GridLayout(1,2);
GridLayout southRow1 = new GridLayout(1,1,10,10);
GridLayout southRow2 = new GridLayout(2,0,10,10);
GridLayout eastGrid = new GridLayout(0,2,10,10);
//declare panels
servicePanel=new JPanel();
servicePanel.setLayout(new GridLayout(0,2));
//servicePanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
servicePanel.setPreferredSize(new Dimension(100,0));
westPanel = new JPanel();
westTop = new JPanel();
westCenter = new JPanel();
westBottomRight= new JPanel();
westCenterBottom = new JPanel();
westBottom = new JPanel();
westLeft = new JPanel();
westRightTop = new JPanel();
westRight = new JPanel();
northPanel = new JPanel();
centerPanel = new JPanel();
centerRight = new JPanel();
centerLeft = new JPanel();
eastPanel=new JPanel();
eastRight = new JPanel();
eastLeft = new JPanel();
eastBottom = new JPanel();
eastEastTop = new JPanel();
eastEastCenter = new JPanel();
southPanel = new JPanel();
southTop = new JPanel();
southLeft = new JPanel();
southCenter = new JPanel();
southBottom = new JPanel();
/////////////////set the panels/////////////////////
//NORTH
northPanel.setLayout(flo);
//northPanel.setBackground(Color.cyan);
//WEST
westPanel.setLayout(westGrid);
westPanel.setBorder(BorderFactory.createEtchedBorder());
westTop.setLayout(new GridLayout(2,1));
westTop.setBorder(BorderFactory.createEtchedBorder());
westCenter.setBorder(BorderFactory.createRaisedBevelBorder());
westCenter.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
westBottom.setLayout(new GridLayout(3,3,10,10));
westLeft.setLayout(new GridLayout(0,1));
//westRightTop.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
westRightTop.setLayout(new GridLayout(0,2));
westRight.setLayout(new GridLayout(1,1));
//westBottom.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
//westBottom.setLayout(new GridLayout(2,2,20,20));
//CENTER
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
centerRight.setLayout(gbl);
centerRight.setPreferredSize(new Dimension(500,200));
centerRight.setBorder(BorderFactory.createRaisedBevelBorder());
//EAST
eastPanel.setLayout(eastGrid);
eastRight.setLayout(new GridLayout(1,1));
eastEastTop.setLayout(new FlowLayout(FlowLayout.LEFT));
eastEastCenter.setLayout(new FlowLayout(FlowLayout.CENTER));
eastPanel.setBorder(BorderFactory.createEtchedBorder());
//SOUTH
southPanel.setBorder(BorderFactory.createRaisedBevelBorder());
southPanel.setLayout(southBorder);
southPanel.setPreferredSize(new Dimension(0,227));
southTop.setLayout(westGrid);
southLeft.setLayout(southGrid);
southLeft.setPreferredSize(new Dimension(70,0));
//southLeft.setBorder(BorderFactory.createRaisedBevelBorder());
//southRight.setLayout(westGrid);
southCenter.setLayout(southFlo);
southCenter.setPreferredSize(new Dimension(100,200));
southCenter.setBorder(BorderFactory.createRaisedBevelBorder());
//add to scrolling pane
scrollpane = new JScrollPane(employees);
scrollpane.getViewport().add(employees);
CREATING AN INSTANCE OF JTABLE
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(200,200));
ADDING THE TABLE TO THE SCROLLPANE2
scrollpane2 = new JScrollPane(table);
//scrollpane2.getViewport().add(servicePanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane3 = new JScrollPane(listEmpl);
scrollPane3.getViewport().add(listEmpl);
scrollPane4 = new JScrollPane(listSchedule);
scrollPane4.getViewport().add(listSchedule);
//get the content pane
Container pane = getContentPane();
JPanel calendars = new JPanel(new GridLayout(0,1));
JScrollPane jsp = new JScrollPane(calendars);
GregorianCalendar gc = new GregorianCalendar();
//gc.set(GregorianCalendar.DAY_OF_YEAR,1);
gc.set(GregorianCalendar.DAY_OF_MONTH,1);
for (int i=0; i<12; i++)
calendars.add(new CalendarPanel(gc,this));
gc.add(GregorianCalendar.MONTH, 1);
cmbServices.setEditable(true);
//add components to the panels
northPanel.add(lblsouthHeading);
westTop.add(lblEmployees);
westTop.add(scrollpane);
westCenter.add(hireButton);
westCenter.add(employeeName);
westCenter.add(fireButton);
westCenter.add(addServices);
westCenter.add(serviceName);
westCenter.add(removeServices);
westLeft.add(westTop);
westLeft.add(westCenter);
ADDING THE SCROLLPANE2 WHICH HOLDS
JTABLE TO THE WESTRIGHT PANEL
THEN FINALY TO THE WESTPANEL
westRight.add(scrollpane2);
westRight.add(new JLabel("TEST"));
westPanel.add(westLeft);
westPanel.add(westRight);
//westPanel.add(westCenter);
//westPanel.add(westBottom,BorderLayout.SOUTH);
westPanel.setBorder(BorderFactory.createRaisedBevelBorder());
eastLeft.add(lblSelect);
eastLeft.add(scrollPane3);
eastRight.add(eastLeft,BorderLayout.CENTER);
eastRight.add(jsp,BorderLayout.EAST);
//eastEastTop.add(lblEmployeeName);
//eastEastTop.setBackground(Color.black);
//eastEastTop.add(lblMonthStat);
eastEastTop.add(lblDay);
eastEastTop.add(lblYear);
eastPanel.add(eastRight,BorderLayout.CENTER);
eastPanel.add(eastEastTop);
//eastPanel.add(eastEastCenter);
//eastPanel.add(eastBottom,BorderLayout.SOUTH);
southTop.add(lblBizHours);
//southLeft.add(scrollpane);
southLeft.add(listDays);
southCenter.add(lblStartTime);
southCenter.add(txtOpenTime);
southCenter.add(startAmPm);
southCenter.add(lblEndTime);
southCenter.add(txtClosedTime);
southBottom.add(btnNextDay = new JButton("Next Day"));
southCenter.add(endAmPm);
southPanel.add(southTop,BorderLayout.NORTH);
southPanel.add(southLeft,BorderLayout.WEST);
southPanel.add(southCenter,BorderLayout.CENTER);
//southPanel.add(jsp,BorderLayout.EAST);
southPanel.add(southBottom,BorderLayout.SOUTH);
int row =1;
lblOpen = new JLabel("Start Time",lblOpen.RIGHT);
lblClosed = new JLabel("Quiting Time",lblClosed.RIGHT);
lblDayOff = new JLabel("Day Off");
space5 = new JLabel();
centerLeft.add(lblEmployeeName);
addComp(centerRight,lblDayOff,gbl,gbc,0,5,1,1,1,1);
for(int i=0;i<dow.length;i++){
weekDay[i]= new JLabel(""+dow[i],weekDay[i].LEFT);
colon = new JLabel(":",colon.CENTER);
colon2 = new JLabel(":",colon2.CENTER);
weekDay[i].setForeground(Color.red);
startHr[i] = new JTextField("",1);
keyListener kl=new keyListener();
startHr[i].addKeyListener(kl);
startMin[i] = new JTextField("",1);
startMin[i].addKeyListener(kl);
finishHr[i] = new JTextField("",1);
finishHr[i].addKeyListener(kl);
finishMin[i] = new JTextField("",1);
finishMin[i].addKeyListener(kl);
btnUpdate[i] = new JButton("Update");
dayOff[i] = new JCheckBox();
dayOff[i].addItemListener(this);
space = new JLabel();
space2 = new JLabel();
space3 = new JLabel();
space4 = new JLabel();
btnUpdate[i].setBorder(BorderFactory.createRaisedBevelBorder());
//lblOpen = new JLabel("Shift Start",lblOpen.RIGHT);
//lblClosed = new JLabel("Shift End",lblClosed.RIGHT);
openAmPm[i] = new JComboBox();
closedAmPm[i] = new JComboBox();
openAmPm[i].addItem("AM");
openAmPm[i].addItem("PM");
closedAmPm[i].addItem("AM");
closedAmPm[i].addItem("PM");
addComp(centerRight,space,gbl,gbc,row,2,1,1,1,1);
addComp(centerRight,weekDay[i],gbl,gbc,row,3,1,1,1,1);
addComp(centerRight,space3,gbl,gbc,row,4,1,1,1,1);
addComp(centerRight,dayOff[i],gbl,gbc,row,5,1,1,1,1);
//addComp(centerRight,lblOpen,gbl,gbc,row,6,1,1,1,1);
addComp(centerRight,startHr[i],gbl,gbc,row,7,1,1,1,1);
addComp(centerRight,colon,gbl,gbc,row,8,1,1,1,1);
addComp(centerRight,startMin[i],gbl,gbc,row,9,1,1,1,1);
addComp(centerRight,openAmPm[i],gbl,gbc,row,10,1,1,1,1);
//addComp(centerRight,lblClosed,gbl,gbc,row,11,1,1,1,1);
addComp(centerRight,finishHr[i],gbl,gbc,row,12,1,1,1,1);
addComp(centerRight,colon2,gbl,gbc,row,13,1,1,1,1);
addComp(centerRight,finishMin[i],gbl,gbc,row,14,1,1,1,1);
addComp(centerRight,closedAmPm[i],gbl,gbc,row,15,1,1,1,1);
addComp(centerRight,space4,gbl,gbc,row,16,1,1,1,1);
addComp(centerRight,btnUpdate[i],gbl,gbc,row,17,1,1,1,1);
addComp(centerRight,space2,gbl,gbc,row,18,1,1,1,1);
row++;
}//end for loop
//add the panels
//pane.add(northPanel,BorderLayout.NORTH);
//pane.add(centerRight,BorderLayout.CENTER);
//pane.add(westPanel,BorderLayout.WEST);
// pane.add(eastPanel,BorderLayout.EAST);
// pane.add(southPanel,BorderLayout.SOUTH);
centerPanel.add(centerLeft);
centerPanel.add(centerRight);
//set up tabbed pane
jtp = new JTabbedPane();
jtp.addTab("Schedule",centerPanel);
jtp.addTab("Employees",westPanel);
jtp.addTab("Holidays",eastPanel);
jtp.addTab("Business Hours",southPanel);
pane.add(jtp,BorderLayout.CENTER);
}//end init
private void addComp(JPanel panel,Component c,GridBagLayout gbl,
GridBagConstraints gbc, int row,
int column, int numRows, int numColumns,
int weightx, int weighty)
gbc.gridy = row;
gbc.gridx = column;
gbc.gridheight = numRows;
gbc.gridwidth = numColumns;
gbc.weightx = weightx;
gbc.weighty = weighty;
//set the constraints in the GridBagLayout
gbl.setConstraints(c,gbc);
panel.add(c);
}//end addcomp
public void actionPerformed(ActionEvent e)
//This method can be called only if
//there's a valid selection
int intLength;
String command=e.getActionCommand();
int listIndex1 = listEmpl.getSelectedIndex();
int listIndex2 = listServices.getSelectedIndex();
String firstName=null;
//String service=null;
if(command.equals("Add Employee"))
firstName = employeeName.getText();
//employeeName.setText(""+index);
//User didn't type in a unique name...
if (firstName.equals("") || alreadyInList(nameData,firstName))
Toolkit.getDefaultToolkit().beep();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}//end if
//int index = listEmpl.getSelectedIndex();
//get selected index
//if (listIndex1 == -1)
//no selection, so insert at beginning
//listIndex1 = 0;
//employeeName.setText("listIndex=-1");
//}//end if
else
//add after the selected item
//promptServices();
nameData.addElement(firstName);
size=nameData.getSize();
//fill the employee combobox
//employees.addItem(firstName);
holidayData.addElement(firstName);
listIndex1++;
employeeName.setText("size is "+size);
//Reset the text field.
employeeName.requestFocusInWindow();
employeeName.setText("");
scrollpane.revalidate();
scrollpane.repaint();
}//end if
if(command.equals("Remove Employee"))
nameData.remove(listIndex1);
holidayData.remove(listIndex1);
//removed item in last position
listIndex1--;
size = nameData.getSize();
employeeName.setText("size is "+size);
if (size==0)
//Nobody's left, disable firing.
fireButton.setEnabled(false);
}//end if
else
//Select an index.
if (listIndex1 == nameData.getSize())
listEmpl.setSelectedIndex(listIndex1);
listEmpl.ensureIndexIsVisible(listIndex1);
}//end if
}//end if
HERE IS WHERE A NEW ROW WITH A SERVICE AND DURRATION SHOULD BE ADDED TO THE JTABLE
EACH TIME THE BUTTON IS CLICKED
if(command.equals("Add Service"))
service=serviceName.getText();
if (service.equals("") || alreadyInList(serviceData,service))
Toolkit.getDefaultToolkit().beep();
serviceName.requestFocusInWindow();
serviceName.selectAll();
return;
}//end if
else
do{
timeText = JOptionPane.showInputDialog(listServices, "Enter the time allowed in minutes for \n a "+service+ " appointment");
totalResult=validateInputBox(timeText);
}while(!totalResult);
repaint();
//add after the selected item
//serviceData.addElement(service+" "+ timeText+ minutes);
//cmbServices.addItem(service);
serviceName.requestFocusInWindow();
serviceName.setText("");
listIndex2++;
//scrollpane.revalidate();
//scrollpane.repaint();
scrollpane2.revalidate();
scrollpane2.repaint();
//int time = Integer.parseInt(timeText);
}//end else
}//end if
/* else if(command.equals("Remove Service"))
System.out.println("Selected:"+CheckServices.selected);
if(CheckServices.selected){
//for(int i=0;i<
servicePanel.remove(CheckServices.newChk);
servicePanel.remove(CheckServices.lengthLbl);
repaint();
int index = listEmpl.getSelectedIndex();
serviceData.remove(listIndex2);
//removed item in last position
listIndex2--;
size = serviceData.getSize();
//employeeName.setText("size is "+size);
if (size == 0)
//Nobody's left, disable firing.
removeServices.setEnabled(false);
}//end if
else
//Select an index.
if (listIndex2 == serviceData.getSize())
listServices.setSelectedIndex(listIndex2);
listServices.ensureIndexIsVisible(listIndex2);
}//end if
}//end if
//Select the new item and make it visible.
//listEmpl.setSelectedIndex(listIndex1);
//listEmpl.ensureIndexIsVisible(listIndex1);
//listServices.ensureIndexIsVisible(listIndex2);
//listServices.setSelectedIndex(listIndex2);
}//end actionperformed
public void itemStateChanged(ItemEvent e)
boolean selected=false;
int status = e.getStateChange();
if(status==ItemEvent.SELECTED)
for(int i=0;i<dayOff.length;i++)
if(dayOff[i].isSelected())
int index = i;
startHr[i].setEditable(false);
startHr[i].setText("DAY OFF");
startMin[i].setEditable(false);
finishHr[i].setEditable(false);
finishMin[i].setEditable(false);
}//end if
}//end for
}//end if
if(status==ItemEvent.DESELECTED)
for(int i = 0;i<dayOff.length;i++)
if(!dayOff[i].isSelected())
startHr[i].setEditable(true);
startMin[i].setEditable(true);
finishHr[i].setEditable(true);
finishMin[i].setEditable(true);
}//end if
}//end for
}//end if
public boolean validateInputBox(String t)
result=false;
int intLength= t.length();
if(intLength <=3)
for(int i = 0;i<intLength;i++)
if(!Character.isDigit(timeText.charAt(i)))
JOptionPane.showMessageDialog(listServices,message2 );
return result;
//break;
result=true;
return result;
}//end if
else{
JOptionPane.showMessageDialog(listServices,message1 );
return result;
}//end validate method
//This method tests for string equality. You could certainly
//get more sophisticated about the algorithm. For example,
//you might want to ignore white space and capitalization.
protected boolean alreadyInList(DefaultListModel myList,String name)
return myList.contains(name);
//handler for list selection changes
public void valueChanged(ListSelectionEvent event)
if(event.getSource()==listEmpl && !event.getValueIsAdjusting())
/**Load up any relating service information from the database
for the selected employee. If there is no record then reset the
serviceData list to empty so new services can be added
if(dbRecord){
serviceData.addElement("Record added");
dbRecord=false;
else
serviceData.clear();
}//end if
if(event.getSource()==employees ||event.getSource()==listEmpl && !event.getValueIsAdjusting()){
System.out.println("value changed");
int index = employees.getSelectedIndex();
Object item =employees.getModel().getElementAt(index);
lblEmployeeName.setText((String)item);
//lblEmployeeName.setText("Changed");
//centerLeft.add(lblEmployeeName);
}//end valueChanged
public void promptServices()
JOptionPane.showMessageDialog(employees,"Enter a service");
HERE IS THE MYTABLEMODEL CLASS. NOTE:ELEMENT INTEGER(5) WILL BE REPLACED
WITH THE VARIABLE TIMETEXT BECAUSE THIS ELEMENT IS USER DEFINED BUT
DOING SO RIGHT NOW THROWS AN ERROR
class MyTableModel extends AbstractTableModel{
String columnNames[] = {"Service", "Minutes", "Select"};
Object data[][] = { {service, new Integer(5), new Boolean(false)} };
public int getColumnCount()
return columnNames.length;
public int getRowCount()
return data.length;
public String getColumnName(int col)
return columnNames[col];
public Object getValueAt(int row, int col)
return data[row][col];
/* * JTable uses this method to determine the default renderer
/ * editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box. */
public Class getColumnClass(int c)
THIS LINE IS THROWING A NULLPOINTEREXCEPTION ERROR
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
System.out.println("hey hey hey");
//Note that the data/cell address is constant
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
* Don't need to implement this method unless your table's
* data can change.
//public void setValueAt(Object value, int row, int col) {
// data[row][col] = value;
// fireTableCellUpdated(row, col);
class keyListener extends java.awt.event.KeyAdapter
//key listener class watches character count
public void keyTyped(java.awt.event.KeyEvent event){
Object object = event.getSource();
for(int i =0; i<7;i++)
if (object == startHr[i])
if ( startHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume(); //if over limit, pretend nothing happened..
if(object ==startMin[i])
if ( startMin[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume();
if(object==finishHr[i])
if ( finishHr[i].getText().length()>MAX_CHARS && event.getKeyChar()!='\b')
event.consume();
if(object==finishMin[i])
if ( finishMin[i].getText().length()>MAX_CHARS && event.getKeyChar(Any help would be greatly appreciated seeing that I know squat about JTables and the JTableModel.So why do you start by writing a 1000 line program. Start with something small. Understand how they work and then incorporate it into your program.
First. Use the DefaultTableModel. It will do everything you need. Why reinvent the wheel by extending AbstractTableModel. This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=418866]posting shows how to create a table and populate it with some data in 5 lines of code or less. It also gives examples of adding new rows of data to the DataModel (something your TableModel can't do) in a couple of lines of code.
Next, we have Basic Debugging 101. If you have a NullPointerException, then you need to determine which variable is null. I simply added the following code before the line that was causing the problem:
System.out.println(getValueAt(0, c) + " : " + c);
return getValueAt(0, c).getClass();
The value in column 0 was null. So where does the value from the first column come from. Well in your TableModel you tried to create it with one default row of data:
Object data[][] = { {service, new Integer(5), new Boolean(false)} };
So it would appear the "service" variable is null.
Don't post 1000 lines programs again. Create simple code that demonstrates the problem. Chances are while your creating this demo program you will resolve your problem. -
Add new column to a jtable by pressing a button
Hi
I am writing a program that have Jtables and user can add one or many columns to one of those Jtables by pressing a button and that column type user can select by from a combo box.
there have to be column types for select integer type,float type,String type or jcomponent
I need you help to make that specific jtableHi pro_udara,
It can be done this way : while treating the mouse event, you just build a new table model and you refresh your JTable with the new model.
See how to [*create a table model*|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data] -
Hi
I am facing one problem. there is some data should be displayed in Jtable cell.
The thing is that the whole data shall be visible in the cell.. for this I am writing one renderer.. but I could not find the desire solution.. please check it out
class Item_Details extends JFrame {
ApsJTable itemTable = null;
ApsJTable imageTable = null;
ArrayList data = new ArrayList();
String[] columns = new String[2];
ArrayList data1 = new ArrayList();
String[] columns1 = new String[2];
ItemTableModel itemTableModel = null;
ItemTableModel itemTableModel1 = null;
public Item_Details()
super("Item Details");
this.setSize(600,100);
this.setVisible(true);
init();
private void init(){
////////////// Get data for first Table Model ////////////////////////////
data = getRowData();
columns = getColData();
System.out.println(columns[0]);
itemTableModel = new ItemTableModel(data,columns);
/////////////Get Data for Second Table Model //////////////////////////////
try{
data1 = getRowData1();
}catch(Exception e){}
columns1 = getColumns1();
itemTableModel1 = new ItemTableModel(data1,columns1);
///////////// Set Data In Both Table Model //////////////////////////////////
itemTable = new ApsJTable(itemTableModel);
imageTable = new ApsJTable(itemTableModel1);
this.itemTable.setShowGrid(false);
this.imageTable.setShowGrid(false);
this.itemTable.setColumnSelectionAllowed(false);
this.imageTable.setColumnSelectionAllowed(false);
System.out.println(itemTable.getColumnCount());
this.imageTable.setRowHeight(getImageHeight()+3);
JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScrollPane.setRowHeaderView(this.itemTable);
tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
itemTable.getTableHeader().setReorderingAllowed(false);
itemTable.setColumnSelectionAllowed(false);
//itemTable.setRowHeight(25);
itemTable.setCellSelectionEnabled(false);
itemTable.setFocusable(false);
imageTable.getTableHeader().setReorderingAllowed(false);
imageTable.setFocusable(false);
imageTable.setCellSelectionEnabled(false);
//tableScrollPane.setOpaque(false);
itemTable.setAutoCreateColumnsFromModel(false);
int columnCount = itemTable.getColumnCount();
for(int k=0;k<columnCount;k++)
/* TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer(); // NEW
editor = new TextAreaCellEditor();
TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
itemTable.addColumn(column);*/
itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
//itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
this.imageTable.getParent().setBackground(Color.WHITE);
this.itemTable.getParent().setBackground(Color.WHITE);
tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
getContentPane().add(tableScrollPane,BorderLayout.CENTER);
getContentPane().setVisible(true);
public static void main(String[] str){
com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
try {
javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Item_Details ID = new Item_Details();
ID.setVisible(true);
public ArrayList getRowData()
ArrayList rowData=new ArrayList();
Hashtable item = new Hashtable();
item.put(new Long(0),new String("Item No:"));
item.put(new Long(1),new String("RED-1050"));
rowData.add(0,item);
item = new Hashtable();
item.put(new Long(0),new String("Description:"));
item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
rowData.add(1,item);
item = new Hashtable();
item.put(new Long(0),new String("Stage:"));
item.put(new Long(1),new String("Draft"));
rowData.add(2,item);
item = new Hashtable();
item.put(new Long(0),new String("Price: "));
item.put(new Long(1),new String(" 999.00"));
rowData.add(3,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(4,item);
/*item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(5,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(6,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(7,item);
return rowData;
public String[] getColData()
String[] colData = new String[]{"Attribute","Value"};
return colData;
public ArrayList getRowData1()throws MalformedURLException{
ArrayList rowData = new ArrayList();
Hashtable item = new Hashtable();
String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url = new URL(str);
ImageIcon ic = new ImageIcon(url);
ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
item.put(new Long(0), scaledImage);
rowData.add(0,item);
String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url1 = new URL(str1);
ImageIcon ic1 = new ImageIcon(url1);
ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
item.put(new Long(0),scaledImage1);
rowData.add(1,item);
return rowData;
public String[] getColumns1(){
String[] colData = new String[]{"Image"};
return colData;
public int getImageHeight(){
ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
return ic.getIconHeight();
class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
public MultiLineCellRenderer() {
setLineWrap(true);
setWrapStyleWord(true);
JScrollPane m_scroll = new JScrollPane(this,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
setOpaque(true);
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
/*if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
// setFont(table.getFont());
/* if (hasFocus) {
setBorder( UIManager.getBorder("Table.focusCellHighlightBorder") );
if (table.isCellEditable(row, column)) {
setForeground( UIManager.getColor("Table.focusCellForeground") );
setBackground( UIManager.getColor("Table.focusCellBackground") );
} else {
setBorder(new EmptyBorder(1, 2, 1, 2));
int width = table.getColumnModel().getColumn(column).getWidth();
//setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(row) != rowHeight)
table.setRowHeight(row, rowHeight);
setText((value == null) ? "" : value.toString());
return this;
}what wrong with this code..
ThanksIn summary, you have one or more columns for which the data must be wholly visible - correct? If you need all the columns to show the whole of their data, you are goinf to have to expand the table, otherwise you can expand a column with something like
myTable.getColumnModel().getColumn(whichever).setPreferredWidth(whatever); -
Problem in JTable cell renderer
Hi
One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
Thanks
package com.apsiva.tryrowmerge;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Hashtable;
import java.net.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
class Item_Details extends JFrame {
ApsJTable itemTable = null;
ApsJTable imageTable = null;
ArrayList data = new ArrayList();
String[] columns = new String[2];
ArrayList data1 = new ArrayList();
String[] columns1 = new String[2];
ItemTableModel itemTableModel = null;
ItemTableModel itemTableModel1 = null;
public Item_Details()
super("Item Details");
this.setSize(600,100);
this.setBackground(Color.WHITE);
this.setVisible(true);
init();
private void init(){
////////////// Get data for first Table Model ////////////////////////////
data = getRowData();
columns = getColData();
System.out.println(columns[0]);
itemTableModel = new ItemTableModel(data,columns);
/////////////Get Data for Second Table Model //////////////////////////////
try{
data1 = getRowData1();
}catch(Exception e){}
columns1 = getColumns1();
itemTableModel1 = new ItemTableModel(data1,columns1);
///////////// Set Data In Both Table Model //////////////////////////////////
itemTable = new ApsJTable(itemTableModel);
imageTable = new ApsJTable(itemTableModel1);
this.itemTable.setShowGrid(false);
this.imageTable.setShowGrid(false);
this.itemTable.setColumnSelectionAllowed(false);
this.imageTable.setColumnSelectionAllowed(false);
System.out.println(itemTable.getColumnCount());
this.imageTable.setRowHeight(getImageHeight()+3);
JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tableScrollPane.setRowHeaderView(this.itemTable);
//itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
itemTable.getTableHeader().setResizingAllowed(false);
itemTable.getTableHeader().setReorderingAllowed(false);
itemTable.setColumnSelectionAllowed(false);
//itemTable.setRowHeight(25);
itemTable.setCellSelectionEnabled(false);
itemTable.setFocusable(false);
imageTable.getTableHeader().setReorderingAllowed(false);
imageTable.setFocusable(false);
imageTable.setCellSelectionEnabled(false);
//tableScrollPane.setOpaque(false);
itemTable.setAutoCreateColumnsFromModel(false);
int columnCount = itemTable.getColumnCount();
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer(); // NEW
// editor = new TextAreaCellEditor();
// TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
System.out.println(k);
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);
//itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
/*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
// itemTable.setShowGrid(false);
//itemTable.addColumn(column);
//itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
//itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
////////////---------------------- Here background color is being set--------------//////////////////
this.imageTable.getParent().setBackground(Color.WHITE);
this.itemTable.getParent().setBackground(Color.WHITE);
tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
getContentPane().add(tableScrollPane,BorderLayout.CENTER);
getContentPane().setVisible(true);
public static void main(String[] str){
com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
try {
javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
javax.swing.UIManager.setLookAndFeel(alloyLnF);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Item_Details ID = new Item_Details();
ID.setVisible(true);
public ArrayList getRowData()
ArrayList rowData=new ArrayList();
Hashtable item = new Hashtable();
item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
item.put(new Long(1),new String("RED-1050"));
rowData.add(0,item);
item = new Hashtable();
item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
rowData.add(1,item);
item = new Hashtable();
item.put(new Long(0),new String("Stage:"));
item.put(new Long(1),new String("Draft"));
rowData.add(2,item);
item = new Hashtable();
item.put(new Long(0),new String("Price: "));
item.put(new Long(1),new String("999.00"));
rowData.add(3,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(4,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(5,item);
item = new Hashtable();
item.put(new Long(0),new String("Features:"));
item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
rowData.add(6,item);
/*item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(5,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(6,item);
item.put(new Long(0),new String("Family Sequence"));
item.put(new Long(1),new String("8.00"));
rowData.add(7,item);
return rowData;
public String[] getColData()
String[] colData = new String[]{"Attribute","Value"};
return colData;
public ArrayList getRowData1()throws MalformedURLException{
ArrayList rowData = new ArrayList();
Hashtable item = new Hashtable();
String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url = new URL(str);
ImageIcon ic = new ImageIcon(url);
ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
item.put(new Long(0), scaledImage);
rowData.add(0,item);
String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
URL url1 = new URL(str1);
ImageIcon ic1 = new ImageIcon(url1);
ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
item.put(new Long(0),scaledImage1);
rowData.add(1,item);
return rowData;
public String[] getColumns1(){
String[] colData = new String[]{"Image"};
return colData;
public int getImageHeight(){
ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
return ic.getIconHeight();
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;I think Problem is between these code only
for(int k=0;k<columnCount;k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
renderer = new TextAreaCellRenderer();
itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
public TextAreaCellRenderer() {
setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int nRow, int nCol)
if (value instanceof String)
setText((String)value);
// Adjust row's height
int width = table.getColumnModel().getColumn(nCol).getWidth();
setSize(width, 1000);
int rowHeight = getPreferredSize().height;
if (table.getRowHeight(nRow) != rowHeight)
table.setRowHeight(nRow, rowHeight);
this.setBackground(Color.WHITE);
return this;
}
Maybe you are looking for
-
Error When Creating Oracle Text index using Lexer Keyword
Hi All, I am getting following error when i creating oracle text index using lexer & stoplist keyword. Pls Help me if any body know. Thanks in Advance. Error starting at line 1 in command: CREATE INDEX TXT_INX_TEXT_SEARCH ON TEXT_SEARCH (BFILE_DOC) P
-
My iPhone 3GS has begun receiving mysterious alarms, similar to push notification alarms -but I've turned all the notifications off. When these two alarms go off my phone cuts its connection to the wifi. In order to reconnect I have to turn the wifi
-
Hello Experts, I created a lead in CRM using BAPI_LEAD_CREATEMULTI and now I would like to fill out lead survey( Evaluation tab) for this lead with another function module. Is there a function module that can do this? I read about BAPI_LEAD_ATT_CHANG
-
Unable to update iPad. Been backing up forever
Unable to update iPad. Been backing up forever
-
What does it all mean? Help! Mail error message!
The mailbox "~/Library/Mail/[email protected]/Sent Messages.mbox" is currently locked by "(null)" on host "c-24-20-121-133.hsd1.or.comcast.net". If you open a mailbox that already is in use, you may damage its contents. What does it all mean? It's ju