JTable with Groupable Header
Hi again, Im have problems with a JTable supporting Groupable Header
check this code please:
public class GroupableHeaderExample extends JFrame {
GroupableHeaderExample() {
super( "Groupable Header Example" );
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{
{"119","foo","bar","ja","ko","zh"},
{"911","bar","foo","en","fr","pt"}},
new Object[]{"SNo.","1","2","Native","2","3"});
JTable table = new JTable( dm ) {
protected JTableHeader createDefaultTableHeader() {
return new GroupableTableHeader(columnModel);
TableColumnModel cm = table.getColumnModel();
ColumnGroup g_name = new ColumnGroup("Name");
g_name.add(cm.getColumn(1));
g_name.add(cm.getColumn(2));
ColumnGroup g_lang = new ColumnGroup("Language");
g_lang.add(cm.getColumn(3));
ColumnGroup g_other = new ColumnGroup("Others");
g_other.add(cm.getColumn(4));
g_other.add(cm.getColumn(5));
g_lang.add(g_other);
GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
header.addColumnGroup(g_name);
header.addColumnGroup(g_lang);
JScrollPane scroll = new JScrollPane( table );
getContentPane().add( scroll );
setSize( 400, 120 );
}it could be like this :
* |-----------------------------------------------------|
* | | Name | Language |
* | |-----------------|--------------------------|
* | SNo. | | | | Others |
* | | 1 | 2 | Native |-----------------|
* | | | | | 2 | 3 |
* |-----------------------------------------------------|
* | | | | | | |
*/but it is looking like this:
* |-----------------------------------------------------|
* | SNo. | 1 | 2 | Native | 2 | 3 |
* |-----------------------------------------------------|
* | | | | | | |
*/its look like correct, but i think the problem is in one of the clases called. what do you think? ... thanks
Message was edited by:
iTzAngel
Message was edited by:
iTzAngel
STOP SPAMMING THE FORUMS!
http://forum.java.sun.com/thread.jspa?threadID=5202466
http://forum.java.sun.com/thread.jspa?threadID=5202411
http://forum.java.sun.com/thread.jspa?threadID=5202439
http://forum.java.sun.com/thread.jspa?threadID=5202369
by the way, you are really spamming the forums
Similar Messages
-
How to print jTable with custom header and footer....
Hello all,
I'm trying to print a jTable with custom header and footer.But
jTable1.print(PrintMode,headerFormat,footerFormat,showPrintDialog,attr,interactive)
does not allow multi line header and footer. I read in a chat that we can make custom header and footer and wrap the printable with that of the jTable. How can we do that..
Here's the instruction on the chat...
Shannon Hickey: While the default Header and Footer support in the JTable printing won't do exactly what you're looking for, there is a straight-forward approach. You can turn off the default header/footer and then wrap JTable's printable inside another Printable. This wrapper printable would then render your custom data, and then adjust the size given to the wrapped printable
But how can i wrap the jTable's Printable with the custom header and footer.
Thanks in advance,I also once hoped for an easy way to modify a table's header and footer, but found no way.
Yet it is possible. -
Print a JTable with several Header and Footers
Hi everybody,
my name is Lothar and I come from Germany. My english is not very well, but I hope you understand me an my problem.
I want to print a JTable, but I want to print a header with several headers and footers.
For example:
h3. Header
h5. 1. Subtitle
h5. 2. Subtitle
Table
h5. 3. Subtitle
h5. Footer
But, I do not know how I can do that. Can anybody tell me, how I can solve my problem. Please, explain for a newbie because I have learned Java since two months ;)
Here the code:
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Date;
import javax.swing.*;
public class Beispiel extends JFrame implements ActionListener {
private JTable table;
public static void main(String[] args) {
Beispiel tl = new Beispiel();
tl.setVisible(true);
tl.pack();
public Beispiel() {
setLayout(new BorderLayout());
// DruckButton
JButton print = new JButton("Print");
add(print, BorderLayout.SOUTH);
print.addActionListener(this);
// Tabelle
add(new JScrollPane(createTable()), BorderLayout.CENTER);
// schließt das Frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public JTable createTable() {
// titel
String[] title = new String[] { "Datum", "Von", "Bis",
"Dauerinsgesamt", "Bemerkung" };
// daten
String[][] data = new String[][] { { "", "", "", "", "" },
table = new JTable(data, title);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
return table;
public void actionPerformed(ActionEvent e1) {
MessageFormat header = new MessageFormat("Header");
MessageFormat footer = new MessageFormat("Footer");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
} catch (Exception e2) {
System.err.format("Cannot print %s%n", e2.getMessage());
}Nobody?
Can nobody solve my problem? -
Print Jtable with multiline header?
i want to print jtable with multi-lines header and footer
using the print function that takes MessageFormat as header and footer
i used MessageFormat header = new MessageFormat("hello\r\nworld");and i used '\n' only
but it was printed all in the same line
thnx in advanceYou can try something on the below lines. Set your custom renderer for the tableheader.
public class MultiLineHeaderRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent( table, value,
isSelected, hasFocus, row, column);
label.setText("<html>a<br>b</html>");
return label;
}Not the best way to do it. And might need to some modifications too to set the font position etc. -
JTable with row header plus value extraction from headers
Hi, I am trying to do the following:
Short Version-
1. Create a table that has both row and column headers
2. Allow the user to mouse over any of these headers such that doing so will display an image I have produced on a panel. (I already know how to create the image and how to display it, I'm just not sure how to associate it with a particular row or column header)
3. Make the row headers look as much as possible like the column headers.
Slightly Longer Version-
Column headers will be labled A-H (maximum) while row headers will be labled 1-12 (maximum). Either can be less, however, depending on user input. After the table has been realized, the user will move the mouse over say, header 'H' and when they do, a JPEG image will appear on another panel and a tooltip will appear above the cell showing a formula. This happens when either row or column headers are moused over.
Currently, I am using the following code from the O'reilly Swing book as a baseline for experimentation but any help you can offer will be appreciated. I'm fairly new to the JTable world... :-(
TableModel tm = new AbstractTableModel(){
String data[] = {"", "a", "b", "c", "d", "e"};
String headers [] = {"Row #", "Column1", "Column2", "Column3", "Column4", "Column5"};
public int getColumnCount(){ return data.length;}
public int getRowCount() { return 1000;}
public String getColumnName(int col){ return headers[col];}
public Object getValueAt(int row, int col){
return data[col] + row;
//creates a column model for the main table. This model ignores the first
//column added and sets a minimum width of 150 pixels for all others
TableColumnModel cm = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {first = false; return;}
tc.setMinWidth(150);
super.addColumn(tc);
//Creates a column model that will serve as the row header table. This model
//picks a maxium width and stores only the first column
TableColumnModel rowHeaderModel = new DefaultTableColumnModel(){
boolean first = true;
public void addColumn(TableColumn tc){
if(first) {
tc.setMaxWidth(tc.getPreferredWidth());
super.addColumn(tc);
first = false;
JTable grid = new JTable(tm, cm);
//set up the header column and hook it up to everything
JTable headerColumn = new JTable(tm, rowHeaderModel);
grid.createDefaultColumnsFromModel();
headerColumn.createDefaultColumnsFromModel();
//make sure the selection between the main table and the header stay in sync
grid.setSelectionModel(headerColumn.getSelectionModel());
headerColumn.setBorder(BorderFactory.createEtchedBorder());
headerColumn.setBackground(Color.lightGray);
headerColumn.setColumnSelectionAllowed(false);
headerColumn.setCellSelectionEnabled(false);
JViewport jv = new JViewport();
jv.setView(headerColumn);
jv.setPreferredSize(headerColumn.getMaximumSize());
//to make the table scroll properly
grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//have to manually attach row headers but after that, the scroll pane
//keeps them in sync
JScrollPane jsp = new JScrollPane(grid);
jsp.setRowHeader(jv);
jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
gridPanel.add(jsp, BorderLayout.NORTH);There a number of nice examples on JTable: http://www.senun.com/Left/Programming/Java_old/Examples_swing/SwingExamples.html
Hope you could find something suitable ...
Regards,
Anton. -
Print jTable with a header and footer panel
Hi Folks,
I'm currently at a sticking point in a project I'm playing around with. I have a data set of around 300 objects that i'd like printed out in a table. Now, I've gotten the display part down without a hitch but printing the data as well as a header panel and footer panel has been eluding me. I'd basically like something like this...
Name: some name Order date: some date
Address: some address Shipped To: some address
somewhere Some city, some state, etc
in some city
Date | Title | Etc | Etc | Etc
date1 title1 5 $3.00 $15.00
date1 title1 5 $3.00 $15.00
date2 title1 5 $3.00 $15.00
date2 title1 5 $3.00 $15.00
Total purchases: $60.00
Total Items: 20
# of Orders: 2
Am I barking up the wrong tree by making the first and third sections panels and the second section a table? If not, how the heck do I accomplish this? Most of the time the table has been multiple pages as well - I only need section one on the first page and section three on the last page, but whatever is easiest really.
My current approach has been basically to make a custom printables, print the first section, figure out how high it was, print the second section and hope for the best, but the third would never show up because it'd never go over two pages.
Any help would be very much appreciated.
Thanks,
Stephen
Edited by: stephenliberty on May 7, 2009 9:11 AM - more specific subjectI suppose as a quick update, this is as far as I've gotten and will likely get-
public class PrintForm extends JFrame implements Printable{
JComponent headerPanelForPrint;
JComponent footerPanelForPrint;
JTable dataTableForPrint;
public void setPieces(JComponent header, JTable table, JComponent footer){
this.headerPanelForPrint = header;
this.footerPanelForPrint = footer;
this.dataTableForPrint = table;
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
TableFormat tableFormat;
if(pageIndex>0){
tableFormat = new TableFormat(0, footerPanelForPrint.getHeight());
} else {
headerPanelForPrint.printAll(graphics);
tableFormat = new TableFormat(headerPanelForPrint.getHeight(), footerPanelForPrint.getHeight());
MessageFormat footer = new MessageFormat("Page - {0}");
Printable table = dataTableForPrint.getPrintable(PrintMode.FIT_WIDTH, null, footer);
int printme = table.print(graphics, tableFormat, pageIndex);
if(printme == table.NO_SUCH_PAGE){ return table.NO_SUCH_PAGE; }
return Printable.PAGE_EXISTS;
class TableFormat extends PageFormat {
double footerHeight;
double headerHeight;
public TableFormat(double headerHeight, double footerHeight){
this.headerHeight = headerHeight;
this.footerHeight = footerHeight;
@Override
public double getImageableHeight() {
return super.getImageableHeight() - ( this.footerHeight + this.headerHeight );
@Override
public double getHeight() {
return super.getImageableHeight() - ( this.footerHeight + this.headerHeight);
@Override
public double getImageableX() {
return 0;
@Override
public double getImageableY() {
return this.headerHeight;
}It works very well with just a header and the table, but I still have not been able to get a footer to show up in the appropriate spot or (preferably) on the last page.
Edited by: stephenliberty on May 8, 2009 12:29 PM -
Print JTable with column heading
Hi,
I'm very new to this JTable. I'm try to print a Jtable using the print() function (from JDK 1.5)
JTable.print(JTable.PrintMode.FIT_WIDTH, new MessageFormat(
_tabledata.getTitle() ),
new MessageFormat("Page {0,number}"));
The problem I have is that some time it print and other time it doens't print. Also, if it doesn't print, then the program become very slow or not respond. Is that the probelm with the new JDK or am I doing something wrong?
Thanks for you help.Don't rely on JTable.print() methods too much.
Sadly Sun didn't think anyone would need to print anything from java so support was added late and half heartedly (programmers hate printing stuff)
If you are new to java you need to focus on something simpler than printing documents; unfortunatly printing is a tedious burdonsome task for experreineced developers
for example: learn how to output your data from a table into an HTML formate/file; you can build beautiful reports/printouts easily and view them in java components easily but you will probably want to print them from a browser.
Even if you find a class or two to help with your printing efforts on the net you will find you need to know many other generic complicated aspects of java to continue
Sean -
Nested sub-header (Groupable Header) JTable Example and JDK 1.5
There is an old Nobuo Tamemasa example of making a JTable with grouped column headers at:
http://www.codeguru.com/java/articles/124.shtml
I made a couple of minor mods to get it to run under JDK 1.4. It works like a charm. If I run the same code under JDK 1.5.1, only the lowest level column headers are painted.
Has anyone noticed this and come up with a fix?
Here are the 4 classes (with my minor mods) required to run the test...
package GroupableColumnTable;
//File: ColumnGroup.java
* (swing1.1beta3)
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
* ColumnGroup
* @version 1.0 10/20/98
* @author Nobuo Tamemasa
public class ColumnGroup {
protected TableCellRenderer renderer;
protected Vector v;
protected String text;
protected int margin=0;
public ColumnGroup(String text) {
this(null,text);
public ColumnGroup(TableCellRenderer renderer,String text) {
if (renderer == null) {
this.renderer = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JTableHeader header = table.getTableHeader();
if (header != null) {
setForeground(header.getForeground());
setBackground(header.getBackground());
setFont(header.getFont());
setHorizontalAlignment(JLabel.CENTER);
setText((value == null) ? "" : value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return this;
} else {
this.renderer = renderer;
this.text = text;
v = new Vector();
* @param obj TableColumn or ColumnGroup
public void add(Object obj) {
if (obj == null) { return; }
v.addElement(obj);
* @param c TableColumn
* @param v ColumnGroups
public Vector getColumnGroups(TableColumn c, Vector g) {
g.addElement(this);
if (v.contains(c)) return g;
Enumeration enum = v.elements();
while (enum.hasMoreElements()) {
Object obj = enum.nextElement();
if (obj instanceof ColumnGroup) {
Vector groups =
(Vector)((ColumnGroup)obj).getColumnGroups(c,(Vector)g.clone());
if (groups != null) return groups;
return null;
public TableCellRenderer getHeaderRenderer() {
return renderer;
public void setHeaderRenderer(TableCellRenderer renderer) {
if (renderer != null) {
this.renderer = renderer;
public Object getHeaderValue() {
return text;
public Dimension getSize(JTable table) {
Component comp = renderer.getTableCellRendererComponent(
table, getHeaderValue(), false, false,-1, -1);
int height = comp.getPreferredSize().height;
int width = 0;
Enumeration enum = v.elements();
while (enum.hasMoreElements()) {
Object obj = enum.nextElement();
if (obj instanceof TableColumn) {
TableColumn aColumn = (TableColumn)obj;
width += aColumn.getWidth();
width += margin;
} else {
width += ((ColumnGroup)obj).getSize(table).width;
return new Dimension(width, height);
public void setColumnMargin(int margin) {
this.margin = margin;
Enumeration enum = v.elements();
while (enum.hasMoreElements()) {
Object obj = enum.nextElement();
if (obj instanceof ColumnGroup) {
((ColumnGroup)obj).setColumnMargin(margin);
package GroupableColumnTable;
//File: GroupableHeaderExample.java
/* (swing1.1beta3)
* |-----------------------------------------------------|
* | | Name | Language |
* | |-----------------|--------------------------|
* | SNo. | | | | Others |
* | | 1 | 2 | Native |-----------------|
* | | | | | 2 | 3 |
* |-----------------------------------------------------|
* | | | | | | |
//package jp.gr.java_conf.tame.swing.examples;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
* @version 1.0 11/09/98
public class GroupableHeaderExample extends JFrame {
GroupableHeaderExample() {
super( "Groupable Header Example" );
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{
{"119","foo","bar","ja","ko","zh"},
{"911","bar","foo","en","fr","pt"}},
new
Object[]{"SNo.","1","2","Native","2","3"});
JTable table = new JTable( dm ) {
protected JTableHeader createDefaultTableHeader() {
return new GroupableTableHeader(columnModel);
TableColumnModel cm = table.getColumnModel();
ColumnGroup g_name = new ColumnGroup("Name");
g_name.add(cm.getColumn(1));
g_name.add(cm.getColumn(2));
ColumnGroup g_lang = new ColumnGroup("Language");
g_lang.add(cm.getColumn(3));
ColumnGroup g_other = new ColumnGroup("Others");
g_other.add(cm.getColumn(4));
g_other.add(cm.getColumn(5));
g_lang.add(g_other);
GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
header.addColumnGroup(g_name);
header.addColumnGroup(g_lang);
JScrollPane scroll = new JScrollPane( table );
getContentPane().add( scroll );
setSize( 400, 120 );
public static void main(String[] args) {
GroupableHeaderExample frame = new GroupableHeaderExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
frame.setVisible(true);
package GroupableColumnTable;
//File: GroupableTableHeader.java
* (swing1.1beta3)
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
* GroupableTableHeader
* @version 1.0 10/20/98
* @author Nobuo Tamemasa
public class GroupableTableHeader extends JTableHeader {
private static final String uiClassID = "GroupableTableHeaderUI";
protected Vector columnGroups = null;
public GroupableTableHeader(TableColumnModel model) {
super(model);
setUI(new GroupableTableHeaderUI());
setReorderingAllowed(false);
public void setReorderingAllowed(boolean b) {
reorderingAllowed = false;
public void addColumnGroup(ColumnGroup g) {
if (columnGroups == null) {
columnGroups = new Vector();
columnGroups.addElement(g);
public Enumeration getColumnGroups(TableColumn col) {
if (columnGroups == null) return null;
Enumeration enum = columnGroups.elements();
while (enum.hasMoreElements()) {
ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
Vector v_ret = (Vector)cGroup.getColumnGroups(col,new Vector());
if (v_ret != null) {
return v_ret.elements();
return null;
public void setColumnMargin() {
if (columnGroups == null) return;
int columnMargin = getColumnModel().getColumnMargin();
Enumeration enum = columnGroups.elements();
while (enum.hasMoreElements()) {
ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
cGroup.setColumnMargin(columnMargin);
package GroupableColumnTable;
//File: GroupableTableHeaderUI.java
* (swing1.1beta3)
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.*;
public class GroupableTableHeaderUI extends BasicTableHeaderUI {
public void paint(Graphics g, JComponent c) {
Rectangle clipBounds = g.getClipBounds();
if (header.getColumnModel() == null) return;
((GroupableTableHeader)header).setColumnMargin();
int column = 0;
Dimension size = header.getSize();
Rectangle cellRect = new Rectangle(0, 0, size.width, size.height);
Hashtable h = new Hashtable();
int columnMargin = header.getColumnModel().getColumnMargin();
Enumeration enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
cellRect.height = size.height;
cellRect.y = 0;
TableColumn aColumn = (TableColumn)enumeration.nextElement();
Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
if (cGroups != null) {
int groupHeight = 0;
while (cGroups.hasMoreElements()) {
ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
Rectangle groupRect = (Rectangle)h.get(cGroup);
if (groupRect == null) {
groupRect = new Rectangle(cellRect);
Dimension d = cGroup.getSize(header.getTable());
groupRect.width = d.width;
groupRect.height = d.height;
h.put(cGroup, groupRect);
paintCell(g, groupRect, cGroup);
groupHeight += groupRect.height;
cellRect.height = size.height - groupHeight;
cellRect.y = groupHeight;
cellRect.width = aColumn.getWidth() + columnMargin;
if (cellRect.intersects(clipBounds)) {
paintCell(g, cellRect, column);
cellRect.x += cellRect.width;
column++;
private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
TableCellRenderer renderer = header.getDefaultRenderer ();
Component component = renderer.getTableCellRendererComponent(
header.getTable(), aColumn.getHeaderValue(),false, false, -1, columnIndex);
rendererPane.add(component);
rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
cellRect.width, cellRect.height, true);
private void paintCell(Graphics g, Rectangle cellRect,ColumnGroup cGroup) {
TableCellRenderer renderer = cGroup.getHeaderRenderer();
Component component = renderer.getTableCellRendererComponent(
header.getTable(), cGroup.getHeaderValue(),false, false, -1, -1);
rendererPane.add(component);
rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
cellRect.width, cellRect.height, true);
private int getHeaderHeight() {
int height = 0;
TableColumnModel columnModel = header.getColumnModel();
for(int column = 0; column < columnModel.getColumnCount(); column++) {
TableColumn aColumn = columnModel.getColumn(column);
TableCellRenderer renderer = header.getDefaultRenderer();
Component comp = renderer.getTableCellRendererComponent(
header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
int cHeight = comp.getPreferredSize().height;
Enumeration enum = ((GroupableTableHeader)header).getColumnGroups(aColumn);
if (enum != null) {
while (enum.hasMoreElements()) {
ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
cHeight += cGroup.getSize(header.getTable()).height;
height = Math.max(height, cHeight);
return height;
private Dimension createHeaderSize(long width) {
TableColumnModel columnModel = header.getColumnModel();
width += columnModel.getColumnMargin() * columnModel.getColumnCount();
if (width > Integer.MAX_VALUE) {
width = Integer.MAX_VALUE;
return new Dimension((int)width, getHeaderHeight());
public Dimension getPreferredSize(JComponent c) {
long width = 0;
Enumeration enumeration = header.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = (TableColumn)enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
return createHeaderSize(width);
}To anyone interested
I came across this example today, and had the same problem too.
The solution is very simple:
The main problem is that GroupableTableHeader UI is set on its constructor, and it should be on the overriden method for that purpose.
Here is the solution:
1. remove
setUI (new GroupableTableHeaderUI ());from the constructor
2. override the method
public void setUI (javax.swing.plaf.TableHeaderUI ui) {
super.setUI (new GroupableTableHeaderUI ());
}in this class.
Now it is only need to get column width fixed because of borders in the header, as the example dun take this into account...
Hope this helps, the same way as many other posts had help me to solve other problems;) and sorry for any spelling or grammar error. -
JTable with Multiple Row Header
well, Im do an application thats need formated ISOS Sheets, and most of them have a Table with Multiple Row Header , and Groupable Header, and both of them. I have the .java and in the class MultipleRowHeaderExample calls a class AttributiveCellTableModel for setColumnIdentifiers() and setDataVector() the cue is why this print stack :
Exception in thread "main" java.lang.StackOverflowError
at java.util.Vector.<init>(Unknown Source)
at java.util.Vector.<init>(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:54)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
at jp.gr.java_conf.tame.swing.table.AttributiveCellTableModel.setDataVector(AttributiveCellTableModel.java:55)
at javax.swing.table.DefaultTableModel.setColumnIdentifiers(Unknown Source)
.if in main class, have initialized the data, and column vars
public class MultipleRowHeaderExample extends JFrame {
Object[][] data;
Object[] column;
JTable table;
MultiSpanCellTable fixedTable;
public MultipleRowHeaderExample() {
super( "Multiple Row Header Example" );
setSize( 400, 150 );
data = new Object[][]{
{"SNo." ,"" },
{"Name" ,"1"},
{"" ,"2"},
{"Language","1"},
{"" ,"2"},
{"" ,"3"}};
column = new Object[]{"",""};
AttributiveCellTableModel fixedModel = new AttributiveCellTableModel(data, column) {
public boolean CellEditable(int row, int col) {
return false;
};What's the code in AttributiveCellTableModel?
* (swing1.1beta3)
package jp.gr.java_conf.tame.swing.table;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
* @version 1.0 11/22/98
public class AttributiveCellTableModel extends DefaultTableModel {
protected CellAttribute cellAtt;
public AttributiveCellTableModel() {
this((Vector)null, 0);
public AttributiveCellTableModel(int numRows, int numColumns) {
Vector names = new Vector(numColumns);
names.setSize(numColumns);
setColumnIdentifiers(names);
dataVector = new Vector();
setNumRows(numRows);
cellAtt = new DefaultCellAttribute(numRows,numColumns);
public AttributiveCellTableModel(Vector columnNames, int numRows) {
setColumnIdentifiers(columnNames);
dataVector = new Vector();
setNumRows(numRows);
cellAtt = new DefaultCellAttribute(numRows,columnNames.size());
public AttributiveCellTableModel(Object[] columnNames, int numRows) {
this(convertToVector(columnNames), numRows);
public AttributiveCellTableModel(Vector data, Vector columnNames) {
setDataVector(data, columnNames);
public AttributiveCellTableModel(Object[][] data, Object[] columnNames) {
setDataVector(data, columnNames);
public void setDataVector(Vector newData, Vector columnNames) {
if (newData == null)
throw new IllegalArgumentException("setDataVector() - Null parameter");
dataVector = new Vector();
setColumnIdentifiers(columnNames);
dataVector = newData;
cellAtt = new DefaultCellAttribute(dataVector.size(),
columnIdentifiers.size());
newRowsAdded(new TableModelEvent(this, 0, getRowCount()-1,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
@Override
public void setColumnIdentifiers(Vector arg0) {
// TODO Auto-generated method stub
super.setColumnIdentifiers(arg0);
public void addColumn(Object columnName, Vector columnData) {
if (columnName == null)
throw new IllegalArgumentException("addColumn() - null parameter");
columnIdentifiers.addElement(columnName);
int index = 0;
Enumeration enumeration = dataVector.elements();
while (enumeration.hasMoreElements()) {
Object value;
if ((columnData != null) && (index < columnData.size()))
value = columnData.elementAt(index);
else
value = null;
((Vector)enumeration.nextElement()).addElement(value);
index++;
cellAtt.addColumn();
fireTableStructureChanged();
public void addRow(Vector rowData) {
Vector newData = null;
if (rowData == null) {
newData = new Vector(getColumnCount());
else {
rowData.setSize(getColumnCount());
dataVector.addElement(newData);
cellAtt.addRow();
newRowsAdded(new TableModelEvent(this, getRowCount()-1, getRowCount()-1,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
public void insertRow(int row, Vector rowData) {
if (rowData == null) {
rowData = new Vector(getColumnCount());
else {
rowData.setSize(getColumnCount());
dataVector.insertElementAt(rowData, row);
cellAtt.insertRow(row);
newRowsAdded(new TableModelEvent(this, row, row,
TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
public CellAttribute getCellAttribute() {
return cellAtt;
public void setCellAttribute(CellAttribute newCellAtt) {
int numColumns = getColumnCount();
int numRows = getRowCount();
if ((newCellAtt.getSize().width != numColumns) ||
(newCellAtt.getSize().height != numRows)) {
newCellAtt.setSize(new Dimension(numRows, numColumns));
cellAtt = newCellAtt;
fireTableDataChanged();
public void changeCellAttribute(int row, int column, Object command) {
cellAtt.changeAttribute(row, column, command);
public void changeCellAttribute(int[] rows, int[] columns, Object command) {
cellAtt.changeAttribute(rows, columns, command);
}that's it -
JTable with custom column model and table model not showing table header
Hello,
I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
Thanks for your help.
import javax.swing.*;
import javax.swing.table.*;
public class Test1 extends JFrame
public static void main(String args[])
JTable table;
TableColumnModel colModel=createTestColumnModel();
TestTableModel tableModel=new TestTableModel();
Test1 frame=new Test1();
table=new JTable(tableModel, colModel);
frame.getContentPane().add(new JScrollPane(table));
frame.setSize(200,200);
frame.setVisible(true);
private static DefaultTableColumnModel createTestColumnModel()
DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
columnModel.addColumn(new TableColumn(0));
return columnModel;
static class TestTableModel extends AbstractTableModel
public int getColumnCount()
return 1;
public Class<?> getColumnClass(int columnIndex)
return String.class;
public String getColumnName(int column)
return "col";
public int getRowCount()
return 1;
public Object getValueAt(int row, int col)
return "test";
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
}Edited by: 802416 on 14-Oct-2010 04:29
addedKleopatra wrote:
jduprez wrote:
See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
When the TableColumn is created, the default headerValue is null
So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
- it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
- furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
Thanks for the opportunity to have some fun :-)
JeanetteNo problem, thanks for the insight :) -
Print JTable with multi line header
I need to print a JTable with multi line header, I want to know if I can use the method jTable.print(int, MessajeFormat, MessageFormat) by manipulation of the MessageFormat. How I can manipulate it?
Otherwise, How I can print this?hi again,
To print pdf in a swing application you don't need servlet.jar.
You'll only need itext.jar and a printer connected to your pc.
Download the iText source code and unzip it. See the following classes:
com.lowagie.tools.LPR and com.lowagie.tools.BuildTutorial. This latter is the main class of a swing tool that you can run.
Silent Print:
You have only to embed this javascript code in your pdf:
writer.addJavaScript("this.print(false);", false);
document.add(new Chunk("Silent Auto Print"));Then, you have to send the document to the printer.
Google : java print pdf
http://forum.java.sun.com/thread.jspa?threadID=523898 or
http://www.exampledepot.com/egs/javax.print/pkg.html for printing task.
Under unix system, I used this:
String PRINTER = ...;
try {
String cmd = "lp -d " + PRINTER + " " + PDF_PATH;
Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd });
} catch (Exception e) {
//handle the exception
e.printStackTrace();
}hth -
JTable with a JCheckBox in a header column
Hi everybody,
I have implemented a JTable with a JCheckbox in one of the header columns. For this I have used the following code from the Internet for rendering the table cell:
public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
protected CheckBoxColumnHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxColumnHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = (ExtendedJTableHeader)table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
setColumn(column);
rendererComponent.setText(value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
From a technical point of view, the checkbox works as expected. However, I have problems with the graphical layout of the checkbox in the header column:
1) The checkbox seems to be bigger than the height of the header column. It overlays the border lines of the table. When I increase the preferred size of the header row, the checkbox also increases its size and still overlays the table border lines.
2) The checkbox has a diffferent background shading than the other columns in the header.
Any help for solving these two layout problems are greatly appreciated.
Thanks, WalterHi,
here is now the complete code
package main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Arrays;
import java.util.Vector;
import javax.swing.table.*;
* <p>�berschrift: </p>
* <p>Beschreibung: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Organisation: </p>
* @author unbekannt
* @version 1.0
public class MainFrame extends JFrame {
JTable table3;
JScrollPane scp3;
//Den Frame konstruieren
public MainFrame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
//Initialisierung der Komponenten
private void jbInit() throws Exception {
this.setSize(new Dimension(500, 320));
this.setTitle("Action List");
Vector<Object> rowData = new Vector<Object>();
for (int i=0; i<3; i++) {
Vector<Object> colData = new Vector<Object>(Arrays.asList("Data R" + i + "C0", "Data R" + i + "C1", "Data R" + i +"C2", (i%2 == 0) ? Boolean.TRUE : Boolean.FALSE));
rowData.add(colData);
Vector<Object> hdr = new Vector<Object>(Arrays.asList("Column 0", "Column 1", "Column 2 (MyO)", "Column 3"));
DefaultTableModel tableM = new DefaultTableModel(rowData, hdr);
table3 = new JTable(tableM);
TableColumn tc = table3.getColumnModel().getColumn(3);
tc.setCellEditor(table3.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table3.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxColumnHeader(table3, new MyItemListener()));
scp3 = new JScrollPane(table3);
scp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
this.add(scp3);
//�berschrieben, so dass eine Beendigung beim Schlie�en des Fensters m�glich ist
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
protected CheckBoxColumnHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
protected JTable myTable;
public CheckBoxColumnHeader(JTable t, ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
myTable = t;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JTableHeader header = null;
if (table != null) {
header = (JTableHeader)table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
setColumn(column);
rendererComponent.setText(value.toString());
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
protected void setColumn(int column) {this.column = column; }
public int getColumn() {return column; }
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed=false;
JTableHeader header = (JTableHeader)(e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
doClick();
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
((JTableHeader)e.getSource()).repaint();
public void mousePressed(MouseEvent e) {
mousePressed = true;
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public JTable getTable() {return myTable; }
public class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
CheckBoxColumnHeader source = (CheckBoxColumnHeader)e.getSource();
if (source instanceof AbstractButton == false) return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = source.getTable().getRowCount(); x < y; x++) {
source.getTable().setValueAt(new Boolean(checked),x,3);
As originally said, the checkbox in the header column overlays the table borders and also has a different background shading than the other header columns. -
How do I create a jtable with horizontalScroll bar,plz help me!
I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
thank you in advance!Hi,
This piece of code will help :
//Get the Component Adapter for taking action against resizing of
//of Panel
ComponentListenerAdapter componentAdapter =
new ComponentListenerAdapter()
//Get the scrollbar or remove the scrollbar upon resizing
protected void resizingAction()
Container tableParent = table.getParent();
if (tableParent instanceof JViewport)
//Check if the width of the Table Parent Container
//is less than the Preferred Size of the Table
if (tableParent.getSize().getWidth() <
table.getPreferredSize().getWidth())
//Yes it is
//Remove the Auton Resize Function and get the
//Scrollbar
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
else
//No it is not
//Get the Auto Resize functionality back in place
table.setAutoResizeMode(
JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
//Add the component Adapter to the Table Header
table.getTableHeader().addComponentListener(componentAdapter);
private abstract class ComponentListenerAdapter
implements ComponentListener
* The <code>componentHidden<code> method has no implementation
* @param event The Event occured whenever the Component is Hidden
public void componentHidden(ComponentEvent event)
//No Implementaion - Intentially Left Blank
* The <code>componentShown</code> method has no implementation
* @param event The Event occured whenever the Component is Shown
public void componentShown(ComponentEvent event)
//No Implementaion - Intentially Left Blank
* The <code>componentMoved</code> method has no implementation
* @param event The Event occured whenever the Component is Moved
public void componentMoved(ComponentEvent event)
//No Implementaion - Intentially Left Blank
* The <code>componentResized</code> method is invoked whenever the
* component is resized. The resizing action will set the columns and
* scrollbar to act properly
* @param event The Event occured whenever the Component is Resized
public void componentResized(ComponentEvent event)
resizingAction();
* Subclasses of this override this method to determine what is to be
* done once the Component has been Resized
protected abstract void resizingAction();
Hope this will solve all your JTable horizontal resizing problems
--j -
JTable with AUTO_RESIZE_OFF not resizing at all!
I tried to find solution in other posts, but no success.
I created a JTable with
table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);That�s fine, but now I can�t resize it at all while interacting with it.
That�s the main code of the table.
I�d appreciate any any help.
Thanks in advice.
int preferredWidth = 0;
int preferredSizeSum = 0;
//Rebuild TableColumnModel with correct number of columns
((AbstractTableModel)getTable().getModel()).fireTableStructureChanged();
//Set the columns widths based on the field data
TableColumnModel columnModel = getTable().getColumnModel();
for (int i = 0; i <= multiProperties.size(); i++) {
TableColumn column = columnModel.getColumn(i);
//Start with the reported column width
preferredWidth = column.getWidth();
//Enforce minimum width needed to display column header text
preferredWidth = Math.max(preferredWidth, ((AbstractTableModel)getTable().getModel()).getColumnName(i).length() * 10);
//Enforce maximum width so long fields get truncated
preferredWidth = Math.min(preferredWidth, 200);
//Set the column width
column.setPreferredWidth( preferredWidth );
column.setMinWidth( 5 );
column.setMaxWidth( 500 );
preferredSizeSum += preferredWidth;
getTable().setMaximumSize( new Dimension( 500*multiProperties.size(), tableHeight ) );
getTable().setMinimumSize( new Dimension( 5*multiProperties.size(), tableHeight ) );
getTable().setPreferredSize( new Dimension( preferredSizeSum, tableHeight ) );
getTable().setSize( new Dimension( preferredSizeSum, tableHeight ) );Works fine for me:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=623692
If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting. -
IPod Touch no longer working with car Head Unit since update
Hi there, I have a problem with using my iPod Touch with my car's head unit.
I've been using my iPod Touch with the Alpine IDA X001 Head unit fitted in my car for the last 3 months without any problems, however I installed the latest software update for the Touch (v4.0) and now the head unit connects and then says no USB device. At first I thought it was the cable as the cable supplied with the head unit is pretty fragile, so I've replaced it with a new one but it still doesn't work.
I've tested with my iPod Nano and it works perfectly so its not a problem with the head unit or lead (I plugged the Touch in and it didn't work, plugged the Nano in and worked perfectly and then plugged the Touch in and didn't work).
Can anyone help or is it gonna be a case of Restoring the iPod Touch back to factory settings ????I was also having this problem with my Kenwood car stereo. I went into the store and they did a complete restore. I didn't think it worked but the next time I plugged it into my usb to connect with my car stereo it worked. So you might try doing a restore.
Maybe you are looking for
-
Firstly I am unable to use Apple mail except for hotmail, for blueyonder, gmail or Sky as the server shows as (off line) and I have no idea how to get them on line even though I tell them to go there. My pop up blocker doesn't work and I am blitzed
-
My CS4 has stopped working - help
I have CS 4 and when I try to launch any of the programmes it says "Licensing for this product has stopped working" It sites error number 148:3. Can any one help???/
-
I searched the site for a fix but the instructions weren't very clear about inserting files and lines. I could not find the user.js file and i was not sure how to create a file, but i could create a folder. Could I use a microsoft word file or what?
-
My PS/2 mouse problem :(
for some time now i boot up the computer and every other time the mouse works, i now use a usb keyboard and before when i had a ps2 keyboard it was that that wouldnt work, sometimes the mouse wouldnt work and when i restarted with pressing Ctrl+Alt+D
-
I am filming a sequence in a gymnasium using spotlights and I have an exit sign in the background that I woould like to remove.Could some one direct me to a tutorial thst would give me step by step info. to remove the sign? Can you use paintbrush to