wood burning stoves*
The moose likes Swing / AWT / SWT and the fly likes How to add JLabel In a JTable cell Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to add JLabel In a JTable cell" Watch "How to add JLabel In a JTable cell" New topic
Author

How to add JLabel In a JTable cell

Phani Kiran
Greenhorn

Joined: Jan 06, 2005
Posts: 11
Hi everybody,

I wanted a help from U all.
I have scenario in wch i have 3 text fields in a row in JTable and now I would like to know how to add a JLabel into that JTable row.
and if we click on that label the other textfields in that row must be deleted.

Plz help me on this.

Thanks in advance.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
A JLabel is not an interactive component (i.e. you cannot click on it to achieve anything). Sounds to me like you just want to remove a row from your table. Why not just use a JButton? And remember - it is not the JTable from which you remove - it is the underlying table model.

What you will have to do is make a JButton and add an ActionListener to it. Then in the actionPerformed method, find out which row is currently selected, then delete that information from your underlying data structure (array, Vector, whatever). Finally, call the method fireTableRowsDeleted(int firstRow, int lastRow) in the table model.
prithvi s zankat
Greenhorn

Joined: Jul 18, 2005
Posts: 12
You are making a mistake. JLable is an interactive component too. JLalble supports many mouse events.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
You are right in that you can add a MouseListener to a JLabel and then use mouseEntered, mouseClicked, etc. What I should have said was that it does not make sense to use a JLabel for such - it isn't really intended for such functionality (for example it does not provide feedback like changing its appearance when you click on it).

Anyway, if you still want to use a JLabel, follow my advice but add a MouseListener instead of an ActionListener, and put the code in the mouseClicked() intstead of actionPerformed().
hatim osman
Ranch Hand

Joined: Jun 10, 2005
Posts: 105
Hi there...
Yes you can add a JLabel to a JTable, although you will be loosing great functionalty. Take note if you add a label to a cell, then you will you have to do extra work to query the value of the containing cell.
However, this can be done using a custome cell renderer, if your GUI requires your label to have a particular foreground color then you must set the opaue property to true. Make use of this method:

setDefaultCellRenderer(Class class, TableCellRenderer renderer)

now if you intend to display text then your class argument should refernce String.class, however this will effect all cells.
The TableCellRenderer interface contains a single method:
getTableCellRendererComponent()
Alternatively; you can subclass the DefaultCellRenderer class which implements the above mentioned interface. Note this interface is located in javax.swing.table package.
hope this help
hatim osman
Ranch Hand

Joined: Jun 10, 2005
Posts: 105
Part 2: Now consider the following:



1. I thought that it's possible to add a MouseListner to a custom JLabel renderer. This will not work since, JTable object only invokes the paint() method of the underlying renderer, the renderer its self isn't visible or it's not part of the GUI. Therefore, adding a MouseListener to the renderer will never generate any event. On the other hand, designing your renderer to return a new instance everytime it's asked to draw defeats Swing architecture (Renderes are indirectly Singlton) and also will not work for the reason mentioned above.

2. You suggested that you will add a MouseListener to every JLabel, possibly you can do this in your TableModel and most likely by making use of an inner MouseListener class. Note Swing cries :JTable, JTree and JComboBox editing must be handeled by editors. This also defeats the architecture.

3. I did some research, and couldn't find any better solution than this:

* to add a JLabel:

DefeaultCellRenderer LabelRenderer = new DefaultCellRenderer(){
public void setValue(Object value) {
if (value instanceof JLabel) {
//do whatever you want with the label
JLabel label = (JLabel) value;
label.setOpaque(true); }
}
}
table.setDefaultCellRenderer(JLabel.class, new labelRenderer());
or you can create your own renderer by implementing the TableCellRenderer interface found in javax.swing.table package

*let's create a custom JLabel editor that know which row to edit upon receiving an editing gesture:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

public class LabelEditor extends DefaultCellEditor {

//you must know in advance which column to edit when the JLabel
//receive the editing event
private static int columnToBeEdited;

//reference to the table
private JTable table

public LabelEditor(JTable table, int column) {
this.table = table;
columnToBeEdited = column;
}

//now let's override this method, it will disallow editing in the
//label, but will start editing the desired column in the same row
public boolean isCellEditable(EventObject event) {

//in case you want to start editing in response to a certain event,
//then you must validate the event, let's say when the right mouse
//button is clicked

if (event instanceof MouseEvent) {
MouseEvent me = (MouseEvent) event;
if ((me.getID() == MouseEvent.Mouse_Clicked) &&
(SwingUtitlites.isRightMouseButton(me))) {

//let's get the point where the mouse is clicked
Point point = me.getPoint();

//now we will convert the point to a valid row in the table
int row = table.rowAtPoint(point);
//Great!...we know the row, let's start editing the desired column
//in the same row
table.editCellAt(row,columnToBeEdited);
}
}

//always return false to indicate that our label is not editable
return false;
}
}

for this editor to work, you must do the following:
a. set it as the default editor for JLabel instances

//the number 3 indicates which column to be edited
tabel.setDefaultEditor(JLabel.class, new LabelEditor(table, 3);

b. Your table model must return "JLabel.class" when the label column index is passed to the method:
//must return JLabel.class if index corresponds to the JLabel column
getColumnClass(int index)

c. Your table model must return true from the method isCellEditable when the index corresponds to the JLabel column or
the column you want to edit when the label editor recieve the magical editing event
//return true if index is the JLabel column or it's any other
//column you want editable
public boolean isCellEditable(int index)

I really, didn't understand what you mean by "textfields in that row must be deleted". Do you mean the value of the textfield is deleted or you mean the cell its self is physically deleted?. But for the sake of completeness try this:
when your label editor recieve the editing event invoke the table method setValue().Ex:

//repalce the table.editCellAt(row, columnToBeEdited) in the
//LabelEditor class with this
//note that we need to create a new string rather than the anonymous ""
//so we can achieve atumocity
//change the value of columnToBeEdited for every cell you want to change
table.setValue(new String(""), row, columnToBeEdited);


Finally, I hope this help

Java is more than coffee
Phani Kiran
Greenhorn

Joined: Jan 06, 2005
Posts: 11
Hi again,

Thanks to U all for ur replies.
I'll try to implement wat Mr.Hatim has said and i thank him again for the pain he took to give that reply.
But u asked to make me clear whether u are clearing the text fields, NO i want to clear that total ROW, by deleting those text fields and even that delete Label when clicking that.

I Hope u r more clear now and would thank U if u give me more Clear explanation on how to achieve this.

Thanking U all in advance.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
The components you see in the JTable (the JLabels, JComboBoxes, etc) are just representations (views) of the underlying data. You do not delete them directly. Instead, you delete the data from your TableModel. Then when you call fireTableRowsDeleted(), the TableModel will be re-read and will no longer display components for those rows.

In short, I think you need to implement your own TableModel.
hatim osman
Ranch Hand

Joined: Jun 10, 2005
Posts: 105
Hi
in this case, I agree, implement your own TableModel. But take note, you should "and not must" subclass the AbstractTableModel class. This abstract class found in the javax.swing.table package and it implements the TableModel interface. It contains very useful methods, most important of all, those concerned with firing the proper DataModel events, methods like fireTableRowsDeleted() and fireTableRowsInserted() as an example. When these events are fired the table will query the model and then update the view automatically for you.
However, you must still be concerned about how is the table going to render your JLabel and JTextFields. The DefaultTableCellRenderer will only disply whatever returned by the toString() methods respectively, hence, any visual properties will be lost. Visual properties like border, forgroundColor, alignment etc. My advice, is to also implement a renderer that knows how display your components accordingly.
wish you all the luck.
Phani Kiran
Greenhorn

Joined: Jan 06, 2005
Posts: 11
Hi Guys

With the help of all u guys i have put a Label into Table, but statically. Wat my requirement is i need to add textfields and the Label "Delete" DYNAMICALLY when we press an ADD Button below the tabel.

And by clicking that Label "Delete" the that particular row should be deleted, which i think can be achieved

How to add Rows dynamically into TableModel i.e., actually into Tabel.


Plz help me on this.
Waiting for ur replies.

Thaks in advance.
hatim osman
Ranch Hand

Joined: Jun 10, 2005
Posts: 105
As I mentioned, you need to implement your own TableModel. For instance, if you want to delete the 3rd row you should invoke this method fireTableRowsDeleted(2, 2). Where should you issue this method, depends on how you are detecting the JLabel MouseEvent. Did you add a MouseListener to he JLabels or you are listening to the Table SelectionModel?
Phani Kiran
Greenhorn

Joined: Jan 06, 2005
Posts: 11
Hi all.

Thanks for ur replies.

What my requirement is i need to add a JLabel into the cell along with textfields into the JTable "DYNAMICALLY".

From ur suggestions we can add only text fiels dynamically which i have done previously but not JLabels/JButtons.

I WANT TO ADD JLABEL/JBUTTON TO THE CELL OF A JTABLE ALONG WITH TEXTFIELDS DYNAMICALLY.

Plz have a look on this and send me some suggestions.
Waiting for ur replies.

Thanks in advance.
Phani Kiran
Greenhorn

Joined: Jan 06, 2005
Posts: 11
Hi all.

Thanks for ur replies.

What my requirement is i need to add a JLabel into the cell along with textfields into the JTable "DYNAMICALLY".

From ur suggestions we can add only text fiels dynamically which i have done previously but not JLabels/JButtons.

I WANT TO ADD JLABEL/JBUTTON TO THE CELL OF A JTABLE ALONG WITH TEXTFIELDS DYNAMICALLY.

Plz have a look on this and send me some suggestions.
Waiting for ur replies.

Thanks in advance.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
Can you post some of the code you have (the TableModel and the code that creates the table) please?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to add JLabel In a JTable cell