Merging cells in JTable...help
Can someone give me some direction into how I can handle this....
After hours of poking around, I figured out all i needed was an extended BasicTableUI class. With the help of tames MergedCell example, I havepulled out what I need out of his class and stripped it down alot to what I needed. hopefully this will help others also...
package foo;
import java.lang.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.*;
/*This class extends BasicTableUI class which is responsible for drawing the cells in a JTable
Functionality has been added to this class to allow a column cell to be spanned, or merged across
the entire length of the table.*/
See the paintRow() method to define when and how to span the cells.
public class LogicTableUI extends BasicTableUI
public void paint(Graphics g, JComponent c)
//get the rectangle bounds of the current graphic to be drawn
Rectangle oldClipBounds = g.getClipBounds();
//makes a new rectangle the same size as the current rectangle
Rectangle clipBounds = new Rectangle(oldClipBounds);
//gets the width of all combined columns and assigns to tableWidth
int tableWidth = table.getColumnModel().getTotalColumnWidth();
//sets the width of the new rectangle to equal the either the current rect size of the table width
clipBounds.width = Math.min(clipBounds.width, tableWidth);
//Sets the current clip to the rectangle specified by the given coordinates
g.setClip(clipBounds);
//define the first and last rows that are visible
int firstIndex = table.rowAtPoint(new Point(0, clipBounds.y));
int lastIndex = table.getRowCount()-1;
//define a rowRect. This is a rectangle spanning the entire visible part of the table
Rectangle rowRect = new Rectangle(0,0,tableWidth, table.getRowHeight() + table.getRowMargin());
rowRect.y = firstIndex*rowRect.height;
//for every row that is visible, paint it
for (int index = firstIndex; index <= lastIndex; index++)
//is the clipBounds of the current object to be drawn in this row?
if (rowRect.intersects(clipBounds))
paintRow(g, index);
//move to next row
rowRect.y += rowRect.height;
g.setClip(oldClipBounds);
private void paintRow(Graphics g, int row)
//define rect as the current graphic objects bounds
Rectangle rect = g.getClipBounds();
//the graphic has not been drawn yet
boolean drawn = false;
//define how many columns we have to draw for this row
int numColumns = table.getColumnCount();
//for every column in the row, paint it
for (int column = 0; column < numColumns; column++)
//define cellRect
Rectangle cellRect = table.getCellRect(row,column,true);
int cellRow;
int cellColumn;
cellRow = row;
cellColumn = column;
if (cellRect.intersects(rect))
drawn = true;
DefinitionTableModel tblmod = (DefinitionTableModel) table.getModel();
try
LogicGroup grp = tblmod.getLogicGroupByRow(cellRow);
//is this a statement row? If so, apply special treatment to the cell,
//otherwise paint the cell normally
if (grp.getEnd()==cellRow)
//We are on a row we want to span. If its the 1st column, increase
//the width of the rectangle to span the entire table width and
//call paintCell. Otherwise, do not even paint the cell.
if (cellColumn==0)
cellRect.width=table.getColumnModel().getTotalColumnWidth();
paintCell(g, cellRect, cellRow, cellColumn);
else
paintCell(g, cellRect, cellRow, cellColumn);
catch(Exception e)
e.printStackTrace();
else
if (drawn)
break;
private void paintCell(Graphics g, Rectangle cellRect, int row, int column)
int spacingHeight = table.getRowMargin();
int spacingWidth = table.getColumnModel().getColumnMargin();
Color c = g.getColor();
g.setColor(table.getGridColor());
g.drawRect(cellRect.x,cellRect.y,cellRect.width-1,cellRect.height-1);
g.setColor(c);
cellRect.setBounds(cellRect.x + spacingWidth/2, cellRect.y + spacingHeight/2,
cellRect.width - spacingWidth, cellRect.height - spacingHeight);
if (table.isEditing() && table.getEditingRow()==row &&
table.getEditingColumn()==column)
Component component = table.getEditorComponent();
component.setBounds(cellRect);
component.validate();
else
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component component = table.prepareRenderer(renderer, row, column);
if (component.getParent() == null)
rendererPane.add(component);
rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y,
cellRect.width, cellRect.height, true);
//end of class
Similar Messages
-
I want to merge cells of JTable. I searched on net about this and found that there is no direct API available for doing this.
After visiting many forums I found that jp.gr.java_conf.tame.swing.table package is needed to merge cells. Where will I get this package from and is this package for free? Other packages for merging cells will also do.
Thanks in advancePranav_Tipnis wrote:
I found that jp.gr.java_conf.tame.swing.table package is needed to merge cells. Where will I get this package from and is this package for free? Yes, this package is for free. You get it from here: [http://www.codeguru.com/java/articles/137_tame1.zip]
However, the component is complicated and difficult to adapt and debug in case you need special functionality. -
Merge cells in JTable.......
Plz some help me out ......i want to merge two consecutive cells of a row in one cell in JTable......... how to do that.....give some code if possible....
Well, as a new member you should learn to search the forum first before posting questions. Using keywords like "jtable merge cell" will find other postings on this topic. Some with solutions some without, so you will need to read a few and decide on the approach you want to take.
-
Hi
I have some problem with JTable that have merged cell.
Have you got any examples for JTable with merged cell.
Thank in advancecheck this....there are plenty of examples....
http://www2.gol.com/users/tame/swing/examples/JTableExamples4.html -
i want to merge the cell in the jtable , as one cell requires more space than other kindly tell me how to do so
Try http://codeguru.earthweb.com/java/articles/139.shtml
-
Hi there,
I'm building a class which contains a JTable, and I'd like to be able to merge cells (both rows and columns, it depends on). I've just searched help on this forum, but in many topics, answers specify a link to
http://www2.gol.com/users/tame/swing/examples/JTableExamples4.html
or something like that, but this link is not enabled.
Could someone give me some help, please ??
Thanks.So I found the issue, and I'm gonna talk about it, because I think many people could be interested.
Thus, 2 lines need to be changed. Those line are identical, and are as follows :
TableCellRenderer renderer = aColumn.getHeaderRenderer();You just have to modify it with the following code :
TableCellRenderer renderer = header.getDefaultRenderer();Those 2 lines are located in the paintCell() and the getHeaderHeight() methods. -
Can we merge two cells of JTable, the way we do it in html using rowspan and colspan?
no, that's unsupported. There are some (partly oldish, google should help) experiments out there - but beware: they all require tweaks on the level of the ui-delegates which isn't a real option most of the time.
Cheers
Jeanette -
How to Merge Cells in a JTable?
First, a brief background. I have a 1.3.1 Swing application, and have a custom table framework that is extended from Swing. My table model manages row classes. Each row class has its own collection of renderers and editors. Renderers and editors are never shared; each cell has its own. My custom table asks each row for the renderer/editor as needed. This allows the GUI programmer to customize every cell of a row class, down to the renderer/editor, including which cells are editable. Essentially, my custom table framework puts all the brains into row classes. Each screen has its own row class. So, it's very granular but very powerful. However, I need more power.
I need a way to merge cells across columns (column spanning). These merged cells do NOT need to be editable for now. I don't know how I can get the table to render one cell across others in the same row. I suspect this is largely a painting issue, and could really use some help.
Thanks!
AndyThanks for the direction, Ian! That got me on my way.
I subclassed BasicTableUI and copy-pasted the private methods into my subclass, and made them protected. I then modified the paintCell( ) method to change the rendering for the particular table row I'm interested in (test case).
To make the first cell span the entire row, I changed the width of the painting rectangle to be the width of the table, instead of the width of the cell. I also had to NOT render any other cells in that row, so they wouldn't "interfere" with the first renderer. In other words, if I allow cell 3 to be rendered, it will prevent cell 0 from spanning, since cell 3 is rendered AFTER cell 0.
Here's an example of my proof-of-concept (POC):
// For row 5, only render cell 0
if (row == 5) {
if (column == 0) {
rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y, table.getWidth(), cellRect.height, true);
return;
}You can see that only cell 0 will be rendered, and it will be as wide as the table.
My next step will be to experiment with multiple spans in the same row, and then having a cell in the middle span the entire row. I'll post my results for the sake of posterity. -
Ask for suggestion: merge cell or multiple jtable
I would like to have a jtable like this:
+----------+------+------+------+-----+
| 1.Item no|2.Desc|3.Type|4.Size|5.Qty|
+----------+------+------+------+-----+
| 001 | ... | A1 | 3 | 5 |
| | |------|------|-----|
| | | A2 | 2 | 6 |
+----------+------+------+------+-----+
| 002 | ... | A1 | 4 | 4 |
| | |------|------|-----|
| | | A3 | 2 | 6 |
+----------+------+------+------+-----+For each item, it would have say, 2 types (2 rows beginning from the third column).
The question is, I'm now considering whether 1)i should use multiple jtables, one from column 1 -2 and the other from column 3 to 5. OR 2)merge cells
In fact, i just have thought of this 2 methods and not yet implemented them yet. Any suggestion?
Many thanks,
PippenThanks thahn2 but I 've tried out the examples before and found them not so useful for me. And some of them even have problems running on jdk1.4.
Any suggestion on either choice will be welcomed. (or even other suggestions) -
Help with merged cells in table
I'm just learning how to use Dreamweaver 8 and tables. I am
trying to use a table with merged cells filled with graphics --
only one graphic per cell. I make my jpg the size of my cell, which
it seems to fill. Then, when I upload it to view in browser, it
looks as though the graphic doesn't take up the entire cell. At one
point, it was working both in Dreamweaver and the browser. Now, in
the browser view, it looks as though there is extra space above the
graphic and below it. Any suggestions on what is going on???It's not the use of tables with your graphics that is
necessarily the
problem, it's HOW you are using the tables with your
graphics. Can we see
the page you have built so we can examine the code?
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
==================
"degazon" <[email protected]> wrote in
message
news:gasr2p$10m$[email protected]..
> Thanks! It's now evident that I shouldn't use tables
with the graphics. -
Equivalent to SpreadSheet? (I need to merge cells)
Hey all,
I'm making a program dealing with scheduling.
Now i need something that works as a Spreadsheet.
a lot of you may say 2 use JTable,
but there's a problem with that idea, i can't merge cells.
For example
The Columns are days of the week, Rows are Activities
i have an activity that is 3 days long,
i want that activity/cell to be 3 cells long( like in excel when you merge cells).
any ideas on how i can achieve this? or alternative ideas?
any help will be greatly appreciated.
avdzm
Message was edited by:
avdzmHi,
Browse though excellent blog at
http://www.jroller.com/page/santhosh
Excellent leads n discussion there.
Cheers
Ravi -
Is there a way of merging cells (not columns) in a Flex Datagrid?
Hello everyone!
I'm new to Flex and I have been searching for a solution to this problem for two days now, so any help would be really appreciated!
I have a datagrid of, lets say x columns of fixed size, with the ability to add or remove rows dynamically. When adding a row o popup comes up and lets the user determine the positions(order) and widths of the desired cells of the row. So what I want to do is to be able to merge cells of the new Datagrid row appropriately, to satisfy the user's choices. Thats the general idea.
Is there a way to have a Datagrid (or other similar component) with different cell number and widths for each row in Flex? I need a component similar to the Datagrid because I want to be able to select rows and process their data.
Any idea would be very helpful as I'm pressed for time and I could use someone's experience to search in the right direction and not loose time.
Thanks in advance!Thank you very much for your response. I finally did what I wanted without using a Datagrid. I used a Table Flex Component (which extends Flex Grid) that I found here:
http://code.google.com/p/flex-table/#Demo
I downloaded the source and changed some things to make it work as I need. -
Setting Focus to a particular cell in JTable
Hi, can i know how to set the focus to a particular cell in JTable.
Say I have a table with 2 rows and 10 columns. The focus now is at position (1, 9) which is the last cell in the table. But I want to set the focus to (1, 3). How can i achieve this ? Pls help. ThanksOK. It's partially working. The right methods to use are setRowSelectionInterval and setColumnSelectionInterval. Jeanette was right. Mine didn't work because of a thread issue. I put the those two methods in a block such as:
SwingUtilities.invokeLater(new Runnable(){
public void run()
table.setRowSelectionInterval(tblLineItem.getRowCount()-1,
table.getRowCount()-1);
table.setColumnSelectionInterval(0,0);
Then it worked.
But after I finished editing the first cell of the newly created row and press ENTER, the selection went back to the cell that's next to the originally editing cell on the first(old) row, instead of staying at the current row and going to the second cell.
Can anybody shed a light on what I'm missing? -
Adding Image in JTable - help needed(Urgent).
Hai Friends,
i want to add two icon in the cells of JTable... i dont know where am going wrong... the icon is not getting displayed in the cell but instead if i double click the cell the name of the icon is displayed in editable mode... any suggestion...
this is my code... i got this from the forum only... but tis not working....
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame
public TableIcon()
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{new ImageIcon("juggler.ico"), "Copy"},
{new ImageIcon("favicon.gif"), "Add"},
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
System.out.println("getValueAt(0, column)"+getValueAt(0, 0));
return getValueAt(0, 0).getClass();
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
public static void main(String[] args)
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}Urgent... pls help...
Regards,
Ciya.Hai Chris,
Thanks for ur reply,
Now Its throwing null pointer exception in the URL....
Can u pls look into d code and tell me pls...
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class MyIcon extends JPanel
private JScrollPane jScrollPane1 = new JScrollPane();
private JTable jTable1;
private GridBagLayout gridBagLayout1 = new GridBagLayout();
public MyIcon()
try
jbInit();
catch(Exception e)
e.printStackTrace();
private void jbInit() throws Exception
this.setLayout(gridBagLayout1);
jTable1 = new JTable(new AbstractTableModel()
URL lURL = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
URL lURL2 = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
Object[][] data =
{new ImageIcon(lURL), "Copy"},
{new ImageIcon(lURL), "Add"},
public int getRowCount()
return 2;
public int getColumnCount()
return 2;
public Object getValueAt(int row, int column)
return data[row][column];
jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer());
jScrollPane1.getViewport().add(jTable1, null);
this.add(jScrollPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(60, 20, 125, 25), -97, -287));
public static void main(String a[])
MyIcon c = new MyIcon();
JFrame f = new JFrame();
f.getContentPane().add(c);
f.setSize(400,400);
f.setVisible(true);
class Renderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
setIcon((ImageIcon) value);
return this;
}Ciya... -
Unable to edit cells in JTable on single click of the cell.
Hi,
I am unable to edit a cell in JTable on single click of the cell. If I double click on the cell, I am able to edit it. Please help me.
Thanks
SubbuThanks for all replies. Now, i am able to edit the cell on single click.
Maybe you are looking for
-
We can't connect our HP5mp or 6mp to our Mac Mini. Help?
We have Yosemite 10.10.2 and a 25 pin to USB adapter cable from best buy. It worked fine for a while, now nada. ???
-
Wireless Network hard drive till macbook
I used to have a Wireless Network hard drive with my PC (Edmini-not good). Now, owning my new macbook I want to buy a new Wireless Network hard disk. Not only for backup but even to save Itunes musik and pictures which takes too much place on macbook
-
Is it safe to never turn your pb off and leave it plugged in
Just wondering, is it safe to never turn off your pb and have it plugged into the electricity most of the time? Will my battery run out quicker or anything stuff up? cheers to you all
-
Hi guys, WRT to ESS MSS what is the clock-in clock-out process. We are nw2004s SP9. We see the clock-in clock-out corrections ESS application. But we do not find any approval mechanism for the same in UWL for the manger. Though a work item is generat
-
HP Probook 4530s Bluetooth drivers problem
Hi, I need some help. I want to know if my laptop is equipped with a bluetooth adaptor. I'm running Windows 7 Home Premium 64-bit, and these are the specifications: HP ProBook 4530s Notebook PC (ENERGY STAR) Serial Number: {Private Information Rem