JTable - DefaultTableCellRenderer - getCurrencyInstance() - java

I want to change the format of column 2 (Columna 2) to currency format of all the data, I am trying with this, but it does not do anything.
Could you help me?
These are my data:
I want the data to come out like this:
With this code I am trying:
public class CurrencyCellRenderer extends DefaultTableCellRenderer {
#Override
public final Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
final Component result = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
if (value instanceof Number) {
setHorizontalAlignment(JLabel.CENTER);
setText(defaultFormat.format(value));
} else {
setText("NO");
}
return result;
}
}
jTable1.getColumnModel().getColumn(2).setCellRenderer(new CurrencyCellRenderer());
It does not do anything, could you help me?
Thanks!!!

You need to create result after changing value's value. Creating result before, will just return the same old data.
e.g.,
private class CurrencyCellRenderer extends DefaultTableCellRenderer {
#Override
public final Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null) {
value = 0.0;
}
value = myFormat.format(value);
final Component result = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
return result;
}
}
My MCVE for proof of concept:
import java.awt.BorderLayout;
import java.awt.Component;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class CurrencyTable extends JPanel {
private static final String[] TABLE_HEADERS = { "Text", "Value" };
private static final Object[][] DATA = { { "Foo", 1.1 }, { "Bar", 2.2 }, { "Bax", 3.3 } };
private DefaultTableModel tableModel = new DefaultTableModel(DATA, TABLE_HEADERS);
private JTable table = new JTable(tableModel);
private NumberFormat myFormat = NumberFormat.getCurrencyInstance(Locale.FRANCE);
public CurrencyTable() {
table.getColumnModel().getColumn(1).setCellRenderer(new CurrencyCellRenderer());
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
private class CurrencyCellRenderer extends DefaultTableCellRenderer {
#Override
public final Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null) {
value = 0.0;
}
value = myFormat.format(value);
final Component result = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
return result;
}
}
private static void createAndShowGui() {
CurrencyTable mainPanel = new CurrencyTable();
JFrame frame = new JFrame("CurrencyTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Ok, i have the solution:
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
public class MyRenderer extends JLabel implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int col) {
DefaultTableCellRenderer renderer
= new DefaultTableCellRenderer();
Component c = renderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, col);
String s = "";
if (col == 2) {
double d = Double.parseDouble( String.valueOf(value)) ;
s = defaultFormat.format(d);
c = renderer.getTableCellRendererComponent(table, s,
isSelected, hasFocus, row, col);
((JLabel) c).setHorizontalAlignment(SwingConstants.RIGHT);
}
return c;
}
}
jTable1.getColumnModel().getColumn(2).setCellRenderer(new MyRenderer());
Image here
Thanks for all guys!

Related

JTable how can i create custom column renderer

static class DateRenderer extends DefaultTableCellRenderer {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
public DateRenderer() { super(); }
public void setValue(Object value) {
if (formatter==null) {
formatter = DateFormat.getDateInstance();
}
setText((value == null) ? "" : formatter.format(value));
}
}
I use this code to render dates. I found it as this but now i need something else. I have a column with numbers as this (1234.56). I want to render the numbers as (1234.56 TL). But i am kinda beginner so i can't find the way to do it.
TableColumnModel m = table.getColumnModel();
m.getColumn(5).setCellRenderer(new TableRendererExample());
class TableRendererExample extends DefaultTableCellRenderer {
#Override
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);
if (column == 5) {
setText(value.toString()+" TL");
}
return this;
}
}
This code works fine for answer.

Highlight a specifi row JTable

I know there are previous topics for a similar problem but even with it I wasn't able to resolve my problem.
So the thing is, when I add a new empty row to my JTable I want to highlight it in gray. So it works for the first one but when I try to add a second row, the second will be white...
I tried to debbug but without success, I didn't find my mistake.
Here is the class to highlight a row :
class GrayWhiteRenderer extends DefaultTableCellRenderer {
private int rowToColored;
GrayWhiteRenderer(int rowToColored) {
this.rowToColored = rowToColored;
Color color = UIManager.getColor ( "table.row" );
}
#Override
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);
if (UIManager.getColor ( "table.row" )==Color.GRAY) {
c.setBackground(Color.GRAY.brighter());
}
else if(row == rowToColored) {
c.setBackground(Color.GRAY.brighter());
} else {
c.setBackground(Color.WHITE);
}
return c;
}
}
I store the index of all new row in rowToAdd at the begining of it (for exemple : [19, 20, 21, -1, -1, ...]. -1 is to know when I have to stop looking if I have to highlight more) :
while(rowToAdd[k]!=-1) {
System.out.println("rowToAdd[k] : "+rowToAdd[k]);
dataTable.setDefaultRenderer(Object.class, new GrayWhiteRenderer(rowToAdd[k]));
k++;
}
And here is a class to test it :
package Graphic;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
class Test implements Runnable, ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Test());
}
JTable table;
#Override
public void run() {
JFrame frame = new JFrame("Custom Cell Renderer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable(new DefaultTableModel(0, 2) {
#Override
public Class<?> getColumnClass(int c) {
return Object.class;
}
});
class GrayWhiteRenderer extends DefaultTableCellRenderer {
private int rowToColored;
GrayWhiteRenderer(int rowToColored) {
this.rowToColored = rowToColored;
}
#Override
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);
if (UIManager.getColor ( "table.row" )==Color.GRAY) {
c.setBackground(Color.GRAY.brighter());
}
else if(row == rowToColored) {
c.setBackground(Color.GRAY.brighter());
} else {
c.setBackground(Color.WHITE);
}
return c;
}
}
table.setDefaultRenderer(Object.class, new GrayWhiteRenderer(table.getRowCount()));
table.setTableHeader(null);
JButton btn = new JButton("Add Row");
btn.addActionListener(this);
JToolBar bar = new JToolBar();
bar.setFloatable(false);
bar.add(btn);
JPanel content = new JPanel(new BorderLayout());
content.add(bar, BorderLayout.NORTH);
content.add(new JScrollPane(table), BorderLayout.CENTER);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
int nextRow = table.getRowCount();
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[] { "" + nextRow, "" + nextRow });
for(int i=0; i<model.getColumnCount(); i++) {
table.setDefaultRenderer(Object.class, new GrayWhiteRenderer(i));
}
}
}
So, I've fixed your example. Here is your code with my comments
#Override
public void actionPerformed(ActionEvent ae) {
int nextRow = table.getRowCount();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[] {"" + nextRow, "" + nextRow});
// the correct row is: nextRow. No loop required here.
table.setDefaultRenderer(Object.class, new GrayWhiteRenderer(nextRow));
}
I would also correct your renderer to provide selection highlight
class GrayWhiteRenderer extends DefaultTableCellRenderer {
private int rowToColored;
GrayWhiteRenderer(int rowToColored) {
this.rowToColored = rowToColored;
}
#Override
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);
// As I know there is no value is registered for "table.row" in UIManager
// so I've skipped the first condition
if (row == rowToColored) {
c.setBackground(Color.GRAY.brighter());
} else {
// use correct color depended on whether the cell is selected or not!
c.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
}
return c;
}
}

Checkboxes in a JTabel column instead of boolean values using CellRenderer

I am adding a cell renderer to one of my column. Which is intended to return checkbox instead of boolean values. By doing below stuff I can able to get the checkboxes on passing boolean values but I am unable to check/uncheck the boxes.
It works fine if I override the getColumnClass() of DataTableModel.
But I need it with renderers
public class CustomRenderer
{
Table table = new JTable();
public DefaultTableModel getDtmInsurance()
{
if (dtmInsurance == null)
{
String[] columns = { "LIC ID", "Delete" };
dtmInsurance = new DefaultTableModel(columns, 0)
{
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column)
{
if (column == 1)
return true;
return false;
}
};
dtmInsurance.setColumnIdentifiers(columns);
table.setModel(dtmInsurance);
Object[] addInsurance = { "0", false };
dtmInsurance.addRow(addInsurance);
}
table.getColumnModel().getColumn(1).setCellRenderer(new MyRenderer());
return dtmInsurance;
}
class MyRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column)
{
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
if (obj instanceof Boolean)
{
return check;
}
return cell;
}
}
}
Now, you could go through the exercise of implementating your own renderer and editor OR you could let the table API do it for you.
You could just add
#Override
public Class<?> getColumnClass(int columnIndex) {
Class type = String.class;
switch (columnIndex) {
case 0:
type = Integer.class;
break;
case 1:
type = Boolean.class;
break;
}
return type;
}
To your dtmInsurance implementation and get
for free.
Otherwise you should have a look at Concepts: Editors and Renderers and Using Other Editors for more details about making it yourself :P
A custom editor might look something like...
public class MyBooleanEditor extends AbstractCellEditor implements TableCellEditor {
private JCheckBox check = new JCheckBox();
#Override
public Object getCellEditorValue() {
return check.isSelected();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof Boolean) {
check.setSelected((Boolean)value);
}
return check;
}
}
Which you would be able to use similarly to...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
public class CustomRenderer extends JPanel {
private JTable table = new JTable();
private DefaultTableModel dtmInsurance;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CustomRenderer());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public CustomRenderer() {
setLayout(new BorderLayout());
table.setModel(getDtmInsurance());
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellEditor(new MyBooleanEditor());
column.setCellRenderer(new MyBooleanRenderer());
add(new JScrollPane(table));
}
public DefaultTableModel getDtmInsurance() {
if (dtmInsurance == null) {
String[] columns = {"LIC ID", "Delete"};
dtmInsurance = new DefaultTableModel(columns, 0) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
if (column == 1) {
return true;
}
return false;
}
};
dtmInsurance.setColumnIdentifiers(columns);
table.setModel(dtmInsurance);
Object[] addInsurance = {"0", false};
dtmInsurance.addRow(addInsurance);
}
return dtmInsurance;
}
class MyBooleanRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, obj, isSelected, hasFocus, row, column);
if (obj instanceof Boolean) {
return check;
}
return cell;
}
}
public class MyBooleanEditor extends AbstractCellEditor implements TableCellEditor {
private JCheckBox check = new JCheckBox();
#Override
public Object getCellEditorValue() {
return check.isSelected();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof Boolean) {
check.setSelected((Boolean)value);
}
return check;
}
}
}
But if I have 10 rows in my table, the checkbox which i selected first as soon as starting the program, only for that checkbox I can able to check/uncheck. Not for all
You cell renderer doesn't update the state of the checkbox each time it's called, it's just return a empty checkbox.
Something more like...
class MyBooleanRenderer implements TableCellRenderer {
private static final long serialVersionUID = 1L;
JCheckBox check = new JCheckBox();
#Override
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
check.setSelected(false);
if (obj instanceof Boolean) {
check.setSelected((Boolean)obj);
}
if (isSelected) {
check.setForeground(table.getSelectionForeground());
check.setBackground(table.getSelectionBackground());
} else {
check.setForeground(table.getForeground());
check.setBackground(table.getBackground());
}
return check;
}
}
Seems to work

Component cannot find symbol error Java

public class cellRender extends DefaultTableCellRenderer
{
#Override
public Component getTableCellRendererComponent(JTable tblPackage, Object value, boolean isSelected, boolean hasocus, int row, int col)
{
Component c = super.getTableCellRendererComponent(tblPackage, value, isSelected, hasocus, row, col);
if(tblPackage.getColumnModel().getColumn(col).getIdentifier().equals("Package Status"))
{
if(value.toString().equals("ACTIVE"))
{
c.setBackground(Color.GREEN);
}
}
return this;
}
}
The symbol shows that it cannot find the symbol...what's the problem with that?
I assume you're talking about a compile time error but I don't have one. This class
compiles fine (and I didn't make any changes to your code except adding import
statements). So check if you have all import statements correct.
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class cellRender extends DefaultTableCellRenderer
{
#Override
public Component getTableCellRendererComponent(JTable tblPackage, Object value, boolean isSelected, boolean hasocus, int row, int col)
{
Component c = super.getTableCellRendererComponent(tblPackage, value, isSelected, hasocus, row, col);
if(tblPackage.getColumnModel().getColumn(col).getIdentifier().equals("Package Status"))
{
if(value.toString().equals("ACTIVE"))
{
c.setBackground(Color.GREEN);
}
}
return this;
}
}
In your return statement it should be the component so use the below:
return c;
In your code
return this;
this statement is wrong. Because this refers to the current object and you need to return the component.
So you need to replace this by c like
return c;
EDIT:
Try this I am not sure about this but...
tblPackage.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
#Override
public Component getTableCellRendererComponent(JTable tblPackage, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(tblPackage, value, isSelected, hasFocus, row, col);
if(tblPackage.getColumnModel().getColumn(col).getIdentifier().equals("Package Status"))
{
if(value.toString().equals("ACTIVE"))
{
c.setBackground(Color.GREEN);
}
}
return c;
}
});

How to change the color of particular cell in JXTreeTable dynamically

I am using JXTreeTable for making treetable structure now I want to change the color of specific cell dynamically. How can I change the color of cell?
I found this code to change the color, but this is not working.
Here is Code:
leftTree.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
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);
if(Integer.parseInt(rowvalue[0])==row && column==0) {
c.setBackground(Color.red);
}
return c;
}
});
Use highlighters.
addHighlighter(new ColorHighlighter());
If the cell contains text with the name of the color then it would be possible to modify the value.
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
public class MainClass extends JFrame {
ColorName colors[] = { new ColorName("Red"), new ColorName("Green"), new ColorName("Blue"),
new ColorName("Black"), new ColorName("White") };
public MainClass() {
super("Table With DefaultCellEditor Example");
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable table = new JTable(new AbstractTableModel() {
ColorName data[] = { colors[0], colors[1], colors[2], colors[3], colors[4], colors[0],
colors[1], colors[2], colors[3], colors[4] };
public int getColumnCount() {
return 3;
}
public int getRowCount() {
return 10;
}
public Object getValueAt(int r, int c) {
switch (c) {
case 0:
return (r + 1) + ".";
case 1:
return "Some pithy quote #" + r;
case 2:
return data[r];
}
return "Bad Column";
}
public Class getColumnClass(int c) {
if (c == 2)
return ColorName.class;
return String.class;
}
public boolean isCellEditable(int r, int c) {
return c == 2;
}
public void setValueAt(Object value, int r, int c) {
data[r] = (ColorName) value;
}
});
table.setDefaultEditor(ColorName.class, new DefaultCellEditor(new JComboBox(colors)));
table.setDefaultRenderer(ColorName.class, new TableCellRenderer());
table.setRowHeight(20);
getContentPane().add(new JScrollPane(table));
}
public static void main(String args[]) {
MainClass ex = new MainClass();
ex.setVisible(true);
}
public class ColorName {
String cname;
public ColorName(String name) {
cname = name;
}
public String toString() {
return cname;
}
}
public class TableCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int col)
{
// get the DefaultCellRenderer to give you the basic component
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
// apply your rules
if (value.toString().equals("Red"))
c.setBackground(Color.RED);
else
c.setBackground(Color.GRAY);
return c;
}
}
}

Categories