Adding JPopupMenu to JTable cell
Hi,
I am just wondering if I can add a JPopup menu to each cell in a JTable, so that a user can perform some tasks.For example , a user should be able to delete a table cell by choosing the delete menu item in the popup menu
many thanks
Ramesh
Hi,
Add JPopupmenu and add JMenuItems on that according to your requirement. Add MouseListener to your table and on mouseReleased event check whether you have clicked the right mouse. If right mouse is clicked, then show the popup menu that you have already created. I think the following code will help you.
JPopupMenu lJPopupMenu = new JPopupMenu();
JMenuItem lJMenuItem1 = new lJMenuItem();
lJPopupMenu.add(lJMenuItem1);
lJTable.addMouseListener(this);
MouseReleased(java.awt.event.MouseEvent mouseEvent) {
if(mouseEvent.isPopupTrigger()){
lJPopupMenu.show(lJTable, mouseEvent.getX(), mouseEvent.getY());
ActionPerformed of the JMenuItem, you write the code based on the requirement.
Similar Messages
-
Adding JButton into JTable cells
Hi there!!
I want to add a JButton into JTable cells.In fact I have got two classes.Class2 has been extended from the AbstractTableModel class and Class1 which is using Class2's model,,,here's the code,,
Class1
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Class1 extends javax.swing.JFrame {
//////GUI specifications
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestTableButton().setVisible(true);
Class2 model=new Class2();
jTable1=new JTable(model);
jScrollPane1.setViewportView(jTable1);
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
private javax.swing.JTable jTable1;
}Class2
import javax.swing.table.*;
public class Class2 extends AbstractTableModel{
private String[] columnNames = {"A","B","C"};
private Object[][] data = {
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return false;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}what modifications shud I be making to the Class2 calss to add buttons to it?
Can anybody help plz,,,,,??
Thanks in advance..Hi rebol!
I did search out a lot for this but I found my problem was a bit different,,in fact I want to use another class's model into a class being extended by JFrame,,so was a bit confused,,,hope you can give me some ideas about how to handle that scenario,,I know this topic has been discussed before here many a times and also have visited this link,,
http://forum.java.sun.com/thread.jspa?threadID=465286&messageID=2147913
but am not able to map it to my need,,,hope you can help me a bit...
Thanks ..... -
Problem in adding image in jtable cells
hi all.
im creating a swing application using netbeans 6.0.
i want to display image in cells of one column.
for that i set an "image icon" directly to that cell in the "default table model", in that case it is displaying the path of that image in that cell!
then i created a new label, and set the image as icon of that label. added that label in that cell. in this case it is printing label.tostring() to that cell!!
please help.
thanks in advance.You need to override getColumnClass to return Icon.class for the column containing the icon. A code snippet that demonstrates how you might do this: table = new JTable (new DefaultTableModel (data, colNames) {
public Class getColumnClass (int columnIndex) {
switch (columnIndex) {
case 0: return Calendar.class;
case 1: return String.class;
case 2: return Icon.class;
//case 2: return Boolean.class;
return null;
});luck, db -
Adding checkbox to JTable cell
Hi, I am tryin to add a checkbox to JTabel cell.
But somehow i am ending up getting 'false' in the cell instead of checkbox.
Can anyone please help me.
here is my getColumnClass and getValuAt
public Class getColumnClass(int column)
{ if(column==0) return Boolean.class;
else return Object.class;
public Object getValueAt(int nRow, int nCol) {
if(nCol==0)
return new Boolean(ch.isSelected());
}You can use a cell rederer that will give you more flexibility .
Add the renderer to a specific column and that will do the job.
Here is the example:
public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer {
public CheckBoxRenderer() {
super();
public Component getTableCellRendererComponent(JTable table, java.lang.Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Color c = table.getBackground();
this.setBackground(c);
setSelected(value != null && ((Boolean) value).booleanValue());
return this;
}In order to edit the value in a check box you will need to write a cell editor which
is going to be easy. -
Adding JTree to JTable cell is not expanding??
Hi experts
My problem is that as Tree expands, my table cell should expands accordingly.
How do I do that??I do n't mind if other cells get expands.
Please help me...?
Thanks in advanceHow do I do that no such method is available.can you guide me or give me some code.I need urgently..
Thank you very much -
How to select rows in the inner JTable rendered in an outer JTable cell
I have wrriten the following code for creating cell specific renderer - JTable rendered in a cell of a JTable.
table=new JTable(data,columnNames)
public TableCellRenderer getCellRenderer(int row, int column)
if ((row == 0) && (column == 0))
return new ColorRenderer();
else if((row == 1) && (column == 0))
return new ColorRenderer1();
else
return super.getCellRenderer(row, column);
ColorRenderer and ColorRenderer1 are two inner classes, which implement TableCellRenderer to draw inner JTable on the outer JTable cell, having 2 rows and 1 column each.
Now what is happening the above code keeps executing continously, that is the classes are being initialised continously, inner JTables are rendered (drawn) continously, and this makes the application slow after some time. It throws java.lang.OutOfMemoryException.
WHY IS IT SO??? I can't understand where's the bug..
Any advice please???
Moreover i want selections in inner tables and not on outer table, how can this be possible.
I am working on this since a long time but have not yet found a way out...With your help i have overcome the problem of continous repeatition.
The major problem which I am facing is, in selecting rows in the inner rendered JTables.
I have added listener on outer JTable which select rows on the outer JTable, hence the complete inner JTable which being treated as a row, gets selected.
The thing is i need to select the rows of inner rendered JTables,not the outer JTable.
How to go about it??
I have even added listener to inner rendered JTables, but only first row of every table gets selected.
Please help....
Thanks in advance. -
Way to listen for change in JTable cell?
I am having troubles trying to catch a key event while the user is entering text inside a given JTable cell (x/y location). The JTable only seems to manage String objects in it's cells so I can't place a JTextField in there with a KeyListener on it.
Currently, I can only get control of the application once the user has left the cell they are editing.
Does anyone have an example of a JTable 'cell KeyListener' scenario? At this point I want to see if I can print 'hello world' each time I type a character within a cell. Then I'll go from there....If you want to know when the contents of a cell have been updated you should use a TableModelListener.
If you want to know when a character is added/removed from the cell editor then you need to first understand how this works with a simple text field.
Typically you would use a DocumentListener to receive notifies of a change to the text field. However, within the DocumentEvent you wouldn't be able to change the text field as this notification comes after the text field has already been updated.
If you need to ability to intercept changes to the text field before they happen, then you would need to use a DocumentFilter. An example of using a DocumentFilter is given in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features.
Once you get your regular text field working the way you want, the next step to create a DefaultCellEditor using this JTextField and use this editor in your JTable. The above tutorial also has a section on using editors in a table. -
2 combo box on a single jtable cell
I need to add two combo box to a single jtable cell..One for selecting the number and the other for specifying whether the number specifies daily, weekly or yearly data .Please help
hey thank you so much....it worked..... i am adding the code .....
this is how you add an editor to a column
TableColumn col=jtInfo.getColumnModel().getColumn(2);
col.setCellEditor(new ComboCellEditor());the class that extends cell editor
public class ComboCellEditor extends JPanel implements TableCellEditor
public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected,int row, int column)
this.setLayout(new GridLayout(1,2));
if(column==2)
jcbCombo1=new JComboBox();
for(int i=1;i<31;i++)
jcbCombo1.addItem(i);
jcbCombo2=new JComboBox();
jcbCombo2.addItem("Days");
jcbCombo2.addItem("Weeks");
jcbCombo2.addItem("Months");
this.add(jcbCombo1);
this.add(jcbCombo2);
return this;
public Object getCellEditorValue()
return this;
public boolean isCellEditable(EventObject e)
return true;
public boolean shouldSelectCell(EventObject e)
return true;
public boolean stopCellEditing()
return false;
public void cancelCellEditing()
public void addCellEditorListener(CellEditorListener e)
public void removeCellEditorListener(CellEditorListener e)
} -
AutoComplete JComboBox As JTable cell editor
Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
2) Unable to capture enter key event.
Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
Any advice? Thanks
import javax.swing.*;
import javax.swing.JTable.*;
import javax.swing.table.*;
import java.awt.event.*;
* @author yccheok
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
/* Combo Box Added In JFrame. Work as expected. */
final JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Chasing toddlers");
comboBox.setEditable(true);
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
System.out.println("is enter");
return;
System.out.println("typed");
comboBox.setSelectedIndex(0);
comboBox.showPopup();
getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
public JTable getMyTable() {
return new JTable() {
Combo Box Added In JTable as cell editor. Didn't work as expected:
1. Exception thrown when show pop up.
2. Unable to capture enter key event.
public TableCellEditor getCellEditor(int row, int column) {
final JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Chasing toddlers");
comboBox.setEditable(true);
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
System.out.println("is enter");
return;
System.out.println("typed");
comboBox.setSelectedIndex(0);
comboBox.showPopup();
return new DefaultCellEditor(comboBox);
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = getMyTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.
-
JButton "sticking" in a JTable Cell
So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;
public class ButtonTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1;
private Object[][] rows = new Object[2][1];
private String[] columns = new String[1];
public ButtonTableModel() {
for(int k = 0; k < rows.length; k++) {
JButton button3 = new JButton("222");
button3.setSize(200, 200);
button3.setBackground(Color.red);
button3.addMouseListener(new ColorChanger(button3));
rows[k][0] = button3;
/*button = new JButton("Test Button");
button.setBackground(Color.red);
button.addMouseListener(new ColorChanger(button));
button2 = new JButton("asdf");
button2.setBackground(Color.red);
button2.addMouseListener(new ColorChanger(button2));
rows[0][0] = button;
rows[1][0] = button2;*/
private class ColorChanger implements MouseListener {
private JButton callingButton; //Stores the button that added the Listener
public ColorChanger(JButton pCallingButton) { //Constructs a ColorChanger that stores a given JButton
callingButton = pCallingButton;
public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
if(isGreen(callingButton) == false)
callingButton.setBackground(Color.green);
else
callingButton.setBackground(Color.red);
//The 4 methods below are unused leftovers specified by the MouseListener Interface
public void mouseEntered(MouseEvent arg0) {
public void mouseExited(MouseEvent arg0) {
public void mousePressed(MouseEvent arg0) {
public void mouseReleased(MouseEvent arg0) {
private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
if(pButton.getBackground() == Color.green)
return true;
return false;
public int getColumnCount() { //Returns the number of Columns in a table
return columns.length;
public int getRowCount() { //Returns the number of rows in the table
return rows.length;
public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
return columns[pCollumnIndex];
public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
return rows[pRow][pColumn];
public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
return false;
public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
return getValueAt(0, pColumnIndex).getClass();
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
public class JButtonJTableTest extends JFrame {
private static final long serialVersionUID = 1;
private JTable table;
private TableCellRenderer tableCellRenderer;
private MouseEvent e2;
private Class columnClass;
private JButton button;
private Point mousePos;
private int mouseRow, mouseColumn;
public JButtonJTableTest() {
super("JButton Table Test");
table = new JTable(); //Setup the table, assigning the new renderer and model
tableCellRenderer = table.getDefaultRenderer(JButton.class);
table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
table.setModel(new ButtonTableModel());
table.setGridColor(Color.blue);
table.addMouseListener(new MouseForwarder());
table.setShowGrid(true);
add(table); //Add the table to the content pane
private class MouseForwarder implements MouseListener {
public void mouseClicked(MouseEvent e) {
mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
mouseRow = table.rowAtPoint(mousePos); //Ascertain the mouse's row & column
mouseColumn = table.columnAtPoint(mousePos);
if(mouseRow == -1 || mouseColumn == -1) //Ensure that the column is within the table
return;
columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
return;
button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
button.dispatchEvent(e2); //Have button take action
table.repaint(); //Repaint the table to ensure proper button animation
//The 4 methods below are unused methods from the MouseListener Interface
public void mouseEntered(MouseEvent arg0) {
public void mouseExited(MouseEvent arg0) {
public void mousePressed(MouseEvent arg0) {
public void mouseReleased(MouseEvent arg0) {
public static void main(String[] args) { //Setup and run the window
JButtonJTableTest test = new JButtonJTableTest();
test.setSize(300, 300);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class JButtonRenderer implements TableCellRenderer {
private TableCellRenderer defaultRenderer;
private Component jTableButton;
public JButtonRenderer(TableCellRenderer pRenderer) {
defaultRenderer = pRenderer;
public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
boolean hasFocus, int pRow, int pCollumn) {
try {
jTableButton = (Component)pButton;
return (Component)pButton;
catch(ClassCastException exception) {
return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
hasFocus, pRow, pCollumn);
}This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812
-
Can not show the JCheckBox in JTable cell
I want to place a JCheckBox in one JTable cell, i do as below:
i want the column "d" be a check box which indicates "true" or "false".
String[] columnNames = {"a","b","c","d"};
Object[][] rowData = {{"", "", "", Boolean.FALSE}};
tableModel = new DefaultTableModel(rowData, columnNames);
dataTable = new JTable(tableModel);
dataTable.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
But when i run it, the "d" column show the string "false" or "true", not the check box i wanted.
I do not understand it, can you help me?
Thank you very much!
coral9527Do not use DefaultTableModel, create your own table model and you should implement the method
getColumnClass to display the boolean as checkbox ...
I hope the following colde snippet helps you :
class MyModel extends AbstractTableModel {
private String[] columnNames = {"c1",
"c2"};
public Object[][] data ={{Boolean.valueOf(true),"c1d1"}};
public int getColumnCount() {
//System.out.println("Calling getColumnCount");
return columnNames.length;
public int getRowCount() {
//System.out.println("Calling row count");
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
return true;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col); -
Shading part of a JTable Cell dependent upon the value of the cell
Hi
Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...) to get the x and y position of the cell to draw the rectangle but I still can't make it work.
The code for my renderer as it stands is:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class PercentageRepresentationRenderer extends JLabel implements TableCellRenderer{
double percentageValue;
double rectWidth;
double rectHeight;
JTable table;
int row;
int column;
int x;
int y;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Number)
this.table = table;
this.row = row;
this.column = column;
Number numValue = (Number)value;
percentageValue = numValue.doubleValue();
rectHeight = table.getRowHeight(row);
rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
return this;
public void paintComponent(Graphics g) {
x = table.getCellRect(row, column, false).x;
y = table.getCellRect(row, column, false).y;
setOpaque(false);
Graphics2D g2d = (Graphics2D)g;
g2d.fillRect(x,y, new Double(rectWidth).intValue(), new Double(rectHeight).intValue());
super.paintComponent(g);
}and the following code produces a runnable example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class PercentageTestTable extends JFrame {
public PercentageTestTable()
Object[] columnNames = new Object[]{"A","B"};
Object[][] tableData = new Object[][]{{0.25,0.5},{0.75,1.0}};
DefaultTableModel testModel = new DefaultTableModel(tableData,columnNames);
JTable test = new JTable(testModel);
test.setDefaultRenderer(Object.class, new PercentageRepresentationRenderer());
JScrollPane scroll = new JScrollPane();
scroll.getViewport().add(test);
add(scroll);
public static void main(String[] args)
PercentageTestTable testTable = new PercentageTestTable();
testTable.pack();
testTable.setVisible(true);
testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}If anyone could help or point me in the right direction, I'd appreciate it.
RuanaeThis is an example I published some while ago -
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class Fred120 extends JPanel
static final Object[][] tableData =
{1, new Double(10.0)},
{2, new Double(20.0)},
{3, new Double(50.0)},
{4, new Double(10.0)},
{5, new Double(95.0)},
{6, new Double(60.0)},
static final Object[] headers =
"One",
"Two",
public Fred120() throws Exception
super(new BorderLayout());
final DefaultTableModel model = new DefaultTableModel(tableData, headers);
final JTable table = new JTable(model);
table.getColumnModel().getColumn(1).setCellRenderer( new LocalCellRenderer(120.0));
add(table);
add(table.getTableHeader(), BorderLayout.NORTH);
public class LocalCellRenderer extends DefaultTableCellRenderer
private double v = 0.0;
private double maxV;
private final JPanel renderer = new JPanel(new GridLayout(1,0))
public void paintComponent(Graphics g)
super.paintComponent(g);
g.setColor(Color.CYAN);
int w = (int)(getWidth() * v / maxV + 0.5);
int h = getHeight();
g.fillRect(0, 0, w, h);
g.drawRect(0, 0, w, h);
private LocalCellRenderer(double maxV)
this.maxV = maxV;
renderer.add(this);
renderer.setOpaque(true);
renderer.setBackground(Color.YELLOW);
renderer.setBorder(null);
setOpaque(false);
setHorizontalAlignment(JLabel.CENTER);
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col)
final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (value instanceof Double)
v = ((Double)value).doubleValue();
return renderer;
public static void main(String[] args) throws Exception
final JFrame frame = new JFrame("Fred120");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Fred120());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} -
How to write an element in a JTable Cell
Probably it's a stupid question but I have this problem:
I have a the necessity to build a JTable in which, when I edit a cell and I push a keyboard button, a new Frame opens to edit the content of the cell.
But the problem is how to write something in the JTable cell, before setting its model. Because, I know, setCellAT() method of JTree inserts the value in the model and not in the table view. And repainting doesn't function!
What to do??
ThanksHi there
Depending on your table model you should normally change the "cell value" of the tablemodel.
This could look like:
JTable table = new JTable();
TableModel model = table.getModel();
int rowIndex = 0, columnIndex = 0;
model.setValueAt("This is a test", rowIndex, columnIndex);
The tablemodel should then fire an event to the view (i.e. JTable) and the table should be updated.
Hope this helps you -
How to display images in a Jtable cell-Urgent
Hay all,
Can anybody tell me that can we display images to JTable' cell,If yes the how do we do that(with some code snippet)? Its very urgent .Plz reply as soon as possible.Here is an example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class SimpleTableExample extends JFrame
private JPanel topPanel;
private JTable table;
private JScrollPane scrollPane;
public SimpleTableExample()
setTitle( "Table With Image" );
setSize( 300, 200 );
setBackground( Color.gray );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create columns names
String columnNames[] = { "Col1", "Col2", "Col3" };
// Create some data
Object data[][] =
{ (ImageIcon) new ImageIcon("User.Gif"), (String) "100", (String)"101" },
{ (String)"102", (String)"103", (String)"104" },
{ (String)"105", (String)"106", (String)"107" },
{ (String)"108", (String)"109", (String)"110" },
// Create a new table instance
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
public Class getColumnClass(int column)
return getValueAt(0, column).getClass();
}; // Add the table to a scrolling pane
scrollPane = new JScrollPane( table );
topPanel.add( scrollPane, BorderLayout.CENTER );
public static void main( String args[] )
SimpleTableExample mainFrame = new SimpleTableExample();
mainFrame.setVisible( true );
} -
How can I put ImageIcon object in a JTable cell?
yes, I'mm trying :
ImageIcon icon = new ImageIcon("something.gif")
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] newRow = new Object[5];
newRow[1] = "I don't";
newRow[2] = "know, what";
newRow[3] = "I am doing"
newRow[4] = "wrong"
newRow[0] = icon;
model.addRow(newRow);
but icon doesn't show
Maybe you are looking for
-
Should i delete my photos from iPhoto after I import to aperture
should i delete my photos from iPhoto after I import to aperture? What is the easiest way to do this?
-
Is there a way to find out which carrier an ipone is for?
So my iphone was stolen recently, and cant track it down, I then bought another iphone from a guy who told me it was locked to bell, however when i went to bell to get a new sim and inserted it, it said no sim installed which means its really not a b
-
Dear Experts, Check this simple formula : *if {OITM.LastPurPrc} > 0 then {@BalanceQty} * {OITM.LastPurPrc} else 0 * I am assigning this formula on a report in CR. But it's not retrieving data as it required. Note that {@BalanceQty} formula is working
-
Am pretty new at this, any suggestions would be most appreciated..
-
i WOULD HAVE GLADY PURCHASED ALL OF THE ADOBE PRODUCTS HOWEVER I CAN NOT GET THE STUPID FLASH PLAYER TO RUN. IT IS ALREADY LOADED INTO MY SYSTEM, HAD BEEN SINCE THE LATEST DOWNLOAD CAME OUT. WHY IS THIS SOOOOOOOOOOOOOOOOO DIFFICULT