Add Image in JTable without using renderer - java

I need to add image in Jtable cell without using TableCellRenderer.If i Use the following code means it display the name (string) in that particular cell instead of image.how to do this?.
ImageIcon Icon= new ImageIcon("Blank.gif");
table.setValueAt(Icon,1,0);
using renderer
class FRM_FLXD_ICON_ASSGN extends DefaultTableCellRenderer {
ImageIcon Icon;
public Component getTableCellRendererComponent(
JTable table, Object value, boolean selected, boolean focus,
int row, int col) {
if(selected == true){
Icon=new ImageIcon(getClass().getResource("Pointer.gif"));
}
else{
Icon=new ImageIcon(getClass().getResource("Blank.gif"));
}
this.setIcon(Icon);
return this;
}
}

JTable know Icon/ImageIcon Object, then you can add Icon/ImageIcon directly to the JTable, example

Related

how to set jLabel into jTable cell and fetch image data from mysql database?

I have saved blob data into mysql database and now I want to retrieve image into a jlabel. This jlabel will be inside jtable cell. I have tried this way and image does not show from database. How can I do that, need some suggestion. Thanks in advance.
public class Renderer extends DefaultTableCellRenderer {
JLabel lbl = new JLabel("Photo");
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
lbl.setIcon(new ImageIcon(this.getClass().getResource("/cancel.png")));
return lbl;
}
public JLabel setImage(JTable table, JLabel lblImage) {
lblImage = (JLabel) getTableCellRendererComponent(table, lblImage, getFocusTraversalKeysEnabled(),
isFocusOwner(), ERROR, ABORT);
return lblImage;
}
}

how to use custom cell rendering in jtable for the below needs? [duplicate]

I would like to make an editable table and then check the data to make sure its valid. Im not sure how to change the color of just one cell. I would like to get a cell, for example (0,0) and color the foreground to red. I have read the other posts on SO as well as Oracle about the custom ColorRenderer, but i just don't get how i would use this.
Thanks.
Say that the cell you would like to render with a different color represents a status (I'll take Rejected and Approved as examples). I'd then implement a method in my table model called getStatus(int row) which returns the status for any given row.
Then, when that is in place, I'd go about creating a cell renderer responsible for rendering the column which the cell belongs to. The cell renderer would be something in the lines of the below code.
public class StatusColumnCellRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
//Cells are by default rendered as a JLabel.
JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
//Get the status for the current row.
CustomTableModel tableModel = (CustomTableModel) table.getModel();
if (tableModel.getStatus(row) == CustomTableModel.APPROVED) {
l.setBackground(Color.GREEN);
} else {
l.setBackground(Color.RED);
}
//Return the JLabel which renders the cell.
return l;
}
Then, when the renderer is in place, simply "apply" the renderer to the table with the following piece of code:
Table.getColumnModel().getColumn(columnIndex).setCellRenderer(new StatusColumnCellRenderer());
With regard to making a cell editable, simply implement the isCellEditable(int rowIndex, int columnIndex) method in your table model. You also need to implement the method
setValueAt(Object value, int rowIndex, int columnIndex) if you would like to keep the value which the user provides (which i assume you do!).
I would like to make an editable table and then check the data to make sure its valid.
Another approach would be to edit the data before it is saved to the table model to prevent invalid data from being entered.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableEdit extends JFrame
{
TableEdit()
{
JTable table = new JTable(5,5);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollpane = new JScrollPane(table);
getContentPane().add(scrollpane);
// Use a custom editor
TableCellEditor fce = new FiveCharacterEditor();
table.setDefaultEditor(Object.class, fce);
}
class FiveCharacterEditor extends DefaultCellEditor
{
FiveCharacterEditor()
{
super( new JTextField() );
}
public boolean stopCellEditing()
{
try
{
String editingValue = (String)getCellEditorValue();
if(editingValue.length() != 5)
{
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.red));
textField.selectAll();
textField.requestFocusInWindow();
JOptionPane.showMessageDialog(
null,
"Please enter string with 5 letters.",
"Alert!",JOptionPane.ERROR_MESSAGE);
return false;
}
}
catch(ClassCastException exception)
{
return false;
}
return super.stopCellEditing();
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
Component c = super.getTableCellEditorComponent(
table, value, isSelected, row, column);
((JComponent)c).setBorder(new LineBorder(Color.black));
return c;
}
}
public static void main(String [] args)
{
JFrame frame = new TableEdit();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I believe the correct way to do colouring in a table is via a ColorHighlighter. The table renderers have problems to render different colours in the same column.
Here is an example of how to use highlighters. In this case it is for highlighting a cell that is not editable.
public class IsCellEditablePredicate implements HighlightPredicate {
private JXTable table;
public IsCellEditablePredicate (final JXTable table) {
this.table = table;
}
#Override
public boolean isHighlighted(Component component, ComponentAdapter componentAdapter) {
return !table.isCellEditable(componentAdapter.row,
componentAdapter.column);
}
}
and then in your code for setuping the table you add the highlighter and its colour parameters:
ColorHighlighter grayHighlighter = new ColorHighlighter(new IsCellEditablePredicate(table));
grayHighlighter.setBackground(Color.LIGHT_GRAY);
grayHighlighter.setForeground(table.getForeground());
grayHighlighter.setSelectedBackground(table.getSelectionBackground().darker());
grayHighlighter.setSelectedForeground(table.getSelectionForeground().darker());
table.setHighlighters(grayHighlighter);
This is the simplest way to color a particular Column or cell in a jTable.
First just create a simple class of CustomRenderer
class CustomRenderer extends DefaultTableCellRenderer <br />
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setForeground(Color.blue); >
return c;
}
}
This code gets the column of cell to render
TableColumn col = tblExamHistoryAll.getColumnModel().getColumn(5);
DefaultTableModel model3 = (DefaultTableModel)tblExamHistoryAll.getModel();
col.setCellRenderer(new CustomRenderer());
This is to clear all previous rows from your table. If you do not want them just remove these lines
model3.getDataVector().removeAllElements();
model3.fireTableDataChanged();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int col) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
int control = row;
control = control % 2;
control = (control == 0) ? 1 : 0;
if (control == 1) {
c.setBackground(Color.green);
} else {
c.setBackground(Color.cyan);
}
return c;
}
The most straightforward way is to write a simple TableCellRenderer by extending the DefaultTableCellRenderer and overwriting the getTableCellRendererComponent method to setBackground( Color.RED ). For example:
final JTable table = new JTable(...);
table.setCellRenderer( new DefaultTableCellRenderer() {
public Component getTableCellRenderer(JTable table, Object value, ...) {
super.getTableCellRenderer(...);
if ( value should be highlighted ) {
setBackground( Color.RED );
}
return this;
}
});
You can extend DefaultTableCellRenderer, override getTableCellRendererComponent and call something like
if (myConditions) setBackground(myColor);
before returning "this" when conditions apply but it has a very annoying side-effect of changing the default back-color due to the way DefaultTableCellRenderer.setBackGround is coded.
The trick I found was to entirely duplicate the code of DefaultTableCellRenderer in a class named HackedDefaultTableCellRenderer, add a method that calls directly the Component's setBackground implementation:
public void setComponentBackground(Color c) {
super.setBackground(c);
}
then derive my customized rendered from this hacked class instead of from DefaultTableCellRenderer, and finally call setComponentBackground instead of setBackground in my customized getTableCellRendererComponent.
The drawback is that this HackedDefaultTableCellRenderer relies on a snapshot of DefaultTableCellRenderer.

Scrolling inside a JTable cell in Swing

I have a table each cell contains a image. if the image size is more than row height, I have added JScrollPane. Now when I run the application, scroll is visible in each cell but I'm not able to scroll it.
How can I do it?
Below is the code I'm using to add scroll pane.
Any sample code will be appreciated.
private final JTable table = new JTable(model)
{
#Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column)
{
Component c = super.prepareRenderer(tcr, row, column);
if(isRowSelected(row))
{
c.setForeground(getSelectionForeground());
c.setBackground(getSelectionBackground());
}
else{
c.setForeground(getForeground());
c.setBackground((row%2==0)?evenColor:getBackground());
}
JScrollPane _pane=new JScrollPane(c);
table.setRowHeight(100);
return _pane;
}
};
Right click on your jscrollpane
Properties
HOrizontal scrollbarpolicy = always
Vertical scrollbarpolicy = always
To be able to scroll
Right Click on Jtable
Autocreatecolumnfrommodel =false(deactivaded)
In order to be able to set the focus on the cell (so you can use the inside scroll pane), you can get it through "edit mode":
Create a custom cell editor:
public class MyCustomCellEditor extends AbstractCellEditor implements TableCellEditor{
#Override
public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
JScrollPane your_custom_panel=new JScrollPane();
return your_custom_panel; // your _pane
}
#Override
public Object getCellEditorValue() {
return null;
}
Set it on your table:
table.setDefaultEditor(MyCustomCellValueType.class,new MyCustomCellEditor());
Now you only need to manage how to enter in "edit mode" and you should be able to scroll inside the cell.

Showing the JComboBox selected item text only without the Icon?

I have a JComboBox that its renderer is a JLabel with an Icon for each item in the combo list :
class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object comboItemObject,
int comboItemIndex,
boolean isSelected,
boolean cellHasFocus) {
String comboItemTitle = (String)comboItemObject;
setText( comboItemTitle );
setIcon( new ImageIcon( getClass().getResource( "/images/myIcon.png" ) ) );
return this;
}
}
When i select an item from the comboBox i just want to show the selected item text in the comboBox, and not the item icon also. Is there a way i can do that ?
In the rendering code you can check the index. Something like:
if (index == -1)
{
setText(...);
}
else
{
setText(...);
setIcon(...);
}
Also, you should not be reading the image in the rendering code since code is called frequently.
then you have to override isSelected, and extends JLabel is useless, because renderer by defalult returns JLabel as Component
To get the text in the combobox; a one liner code is all you need.
Create a variable, as I have called mine Combotext
then get the SelectedItem from the JComboBox.
ComboText = jComboBox.getSelectedItem();

Pass events in custom JTable

Hi I have a class called ColorChooser (in the net.java.dev.colorchooser.ColorChooser package)
This is a custom component used to select colors. What I want is to display a JTable with ColorChoosers in the second column. So I created my own TableCellRenderer and it works:
#SuppressWarnings("serial")
class ColorChooserTableRenderer extends DefaultTableCellRenderer {
public static List<ColorChooser> colors;
public ColorChooserTableRenderer(int rows) {
colors = new ArrayList<ColorChooser>(rows);
for (int i = 0; i<rows ; i ++) {
colors.add(new ColorChooser());
}
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return colors.get(row);
}
}
I register this in my table :
JTable t = new JTable(5,3);
t.getColumn(t.getColumnName(1)).setCellRenderer(new ColorChooserTableRenderer(5));
The display is good. It even displays the tool tip of the ColorChoosers when i hover my mouse over one of them. The problem is that the ColorChoosers do not receive MouseEvents.
Normally when you press and hold the mouse on a ColorChooser, you get a pop up window that you can use to select a color. When in the JTable the ColorChooser component does not receive the mouse event.
Any solutions?
Edit: The question can be easily modified to this:
Can you please give me a small example of a table containing JButtons in the second column that actually work? You know, buttons that can be pressed?
This sounds vaguely familiar as I have been using table cell renderers for other purposes.
My understanding is that TableCellRenderer is only used to render the component; a component does not actually exist at each of the cells.
So you'd probably have to somehow forward mouse events from the JTable itself to the ColorChooser.
edit: p.s., see my question -- also for custom table cell rendering, you only need 1 instance of the component itself for the entire column, if the column is rendered with the same logic. Don't store persistent state in the TableCellRenderer, store it in the TableModel instead, and use that state immediately prior to rendering when you handle the call to getTableCellRendererComponent().
A renderer only paints the component on the screen and does not allow for interaction. What you need is to also implement a TableCellEditor. It is recommend that you inherit the AbstractCellEditor and you'll save some work. Check out the java tutorial for tables.
Example:
public class MyTableCellRenderer implements TableCellRenderer
{
private JButton button = new JButton("Press Me");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return button;
}
}
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor
{
private JButton button;
public MyTableCellEditor()
{
button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("buttonPressed");
}
});
}
public Object getCellEditorValue() {
return null;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return button;
}
}

Categories

Resources