In the below image I am trying to achieve the fo开发者_Go百科llowing.I have a table and lots of labels embossed over table cells.The height of the labels is always equal to the cell height.So if two labels come in the same point one hides the another as shown in the longer rectangles with red rect over blue.Alternatively what I want is to make the height as half and there by show both the rectangles(showing starting and end points of the rectangle since height is of no use I can half the height of the rectangle to accomodate one more in the same cell.)
I have to do this inside a JTable.To attach a label we can create a JLabel object by setting the rectangular bounds and using table.add(label);
image here
Where did you get the idea that you can do table.add(label)
and hope that the label be magically painted over the table?
(Same ??? for @dpatch's answer.)
You have to use cell renderer/editor for any custom painting inside table. (Or layered pane/glass pane if it's something floating above table, but it looks like you want the labels in the cells.)
A crude renderer that paints cell (0, 0) as half-height blue on top of full-height red:
table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer()
{
private int row_ = 0;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
row_ = row;
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
public void setUI(LabelUI ui)
{
super.setUI(new BasicLabelUI()
{
public void paint(Graphics g, JComponent c)
{
super.paint(g, c);
if( row_ == 0 )
{
Rectangle r = g.getClipBounds();
g.setColor(Color.RED);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor(Color.BLUE);
g.fillRect(r.x, r.y + 1, r.width, r.height/2 - 1);
}
}
});
}
});
Check out the following presentation. I think it talks about solution to similar problem
http://developers.sun.com/learning/javaoneonline/2008/pdf/TS-4982.pdf?cid=925395
When you find two labels that need to be in the same cell, create a JPanel
with the red and blue labels each taking up half the height of the panel. Then just add the panel to the table.
精彩评论