views:

29

answers:

3

In the below image I am trying to achieve the following.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

A: 

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

eugener
this does not help.But thanks
Harish
I'm not sure can do it any other way.
eugener
A: 

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.

dpatch
A: 

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);
                }
            }
        });
    }
});
Geoffrey Zheng
It works.You can try by setting the label.setOpaque(true) and label.setVisible(true);
Harish
If it works, I'd appreciate if you can accept the answer. Thanks!
Geoffrey Zheng