Jtable, use different alignment for each ROW - java

I have created a table and need to align every second row to the right, and every other row to default.
I understand how to align the rows. This is my default renderer
final DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
final DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);

You'll have to tweak the renderer a little and override its getTableCellRendererComponent method. Something like:
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (r % 2 == 0) {
setHorizontalAlignment(SwingConstants.LEFT);
}
else {
setHorizontalAlignment(SwingConstants.RIGHT);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
Although creating your own proper class that extends DefaultTableCellRenderer and does this would be a better approach.

See Table Row Rendering.
This will allow you to change the alignment in one place even if your table uses multiple renderers and without creating a custom renderer.

Related

How to color Jtable cell when renderer is applied

Hi i am working on jtable and i have to work with cell renderer in such a way that a am applying CurrencyRender in particular column. Also i am apply coloring ion each row. Everything going perfect but when i apply currencyRenderer in my numenric column, it lost the background color. This could be either due to adding cellrenderer of currency . Please suggest what should i do to color column with currency renderer .Here i my code
this.installAllignment(this.tblDemandView.getColumnModel().getColumn(numAmount), SwingConstants.RIGHT);
this.tblDemandView.getTableHeader().setReorderingAllowed(false);
this.tblDemandView.getTableHeader().setResizingAllowed(true);
tblDemandView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
NumberFormat _formatf = NumberFormat.getNumberInstance();
_formatf.setMinimumFractionDigits(2);
_formatf.setMaximumFractionDigits(2);
MyCurrencyRenderer _rendererf = new MyCurrencyRenderer(_formatf);
TableColumnModel _model = tblDemandView.getColumnModel();
TableColumn _columnPu=_model.getColumn(_model.getColumnIndex("Amount"));
_columnPur.setCellRenderer(_rendererf);
private void installAllignment(TableColumn tableColumn, final int alignmentCode) {
tableColumn.setCellRenderer(new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component myself =
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(alignmentCode);
DefaultTableModel model = (DefaultTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
DefaultTableCellRenderer() {
if (row == table.getRowCount() - 1) {
Insets insets = new Insets(1, 0, 0, 0);
// setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
return myself;
}
});
}
Your code doesn't make a lot of sense. You don't do anything with the model, c or insets variables.
But changing the renderer is really pretty trivial. Subclass the TableColumn and override getTableCellRenderer. In the body call the super method to generate the default renderer component and then set the background before returning it.
Alternatively you can implement your own TableCellRenderer and then call setTableCellRenderer on the column rather than subclassing.
Both approaches work fine and are useful in different situations.
Everything going perfect but when i apply currencyRenderer in my numenric column, it lost the background color.
I don't know if you are talking about losing the selection background color, or some other color you use for custom rendering.
Try using Table Row Rendering instead of cell rendering. This approach override the prepareRenderer(...) method of the table to do custom coloring.
You may also want to check out Table Format Renderers in the same blog. It show how to create custom renderer easily.
By the way the code in your renderer makes no sense to me:
Component myself = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(alignmentCode);
DefaultTableModel model = (DefaultTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
I have no idea why you would be invoking the getTableCellRendererComponent(...) method twice.

How to make a row in JTable with 367 cells where only the first one has text and the rest have colors

I am working on a color based database program that shows bookings inside an accommodation based on color. the problem I've been having is that the table has 367 columns (the name of the accommodation and then all days of a year.) the problem I've been having is that I can't figure out how to make the first column of the row display a string and the rest a color.
I made a basic renderer that should display colors but I don't know how to use it.
public class MyRenderer extends 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 (! table.isRowSelected(row))
{
if(row == 2 && column == 2)
c.setBackground(new java.awt.Color(0, 0, 255));
else
c.setBackground(table.getBackground());
}
return c;
}
}
how would I integrate this with a JTable?
PS I have a header I want to show but the rows should be empty to begin with. then when a button is pressed it should add a row. this last button I can make myself I just need help with the cellrenderer
At the moment my JTable is initialized like this: JTable table = new JTable();
Does anybody have any tips?
I suppose there is two state for a day, booked or not. So the value is boolean. You can set renderers by class types. For example:
table.setDefaultRenderer(Boolean.class, new MyRenderer());
With that, your renderer will be uses only if value is a boolean.
public class MyRenderer extends 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(value)
c.setBackground(/*Color for booked days*/ );
else
c.setBackground(table.getBackground());
return c;
}
}

How to change the background color of each second row?

I try to change the background color of each second row. The problem is that only first COLUMN is affected. Why?
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
});
Using the renderer approach you need to write a custom renderer for every data type in the table. So if you have String, Data, Integer, Boolean you would need to write 4 custom renderers.
See Table Row Rendering for an approach that will allow you to write the code once no matter haw many data types you have in the table. This approach overrides the preparerrenderer(...) method of the JTable.
As stated in Concepts: Editors and Renderers section of How to Use Tables tutorial, if you din not specify a renderer for a particular column then the table invokes the table model's getColumnClass method to get a default renderer for the column type.
If you have overridden getColumnClass method then your approach might not work as expected. For instance:
DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2"}, 0) {
#Override
public Class<?> getColumnClass(int columnIndex) {
Class columnClass = Object.class;
switch(columnIndex) {
case 0: columnClass = String.class; break;
case 1: columnClass = Boolean.class; break;
}
return columnClass;
}
};
Then doing this:
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {// your code here});
Won't work for the second column since the getColumnClass method will return Boolean.class and there's a default cell renderer for that class (JCheckBox).
In your case I would suggest you override JTable.prepareRenderer() method instead to set rows background color independently of the renderer type (JLabel, JCheckBox, or even custom renderers):
JTable table = new JTable(model) {
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return c;
}
};
Okay, scrap all of what I just wrote.
Attempt #2:
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
return this;
}
});
You need to be returning the current object, not the reference of the super() call.

Changing colour of specific cell in a JTable

I'm trying to change the colour of one or more particular cells in a column in my JTable. The answers I have seen on here all refer to this particular method;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component y = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
y.setBackground(new Color(255,0,0));
return y;
}
But the problem is I do not understand in any way how this works, in my other class I have a Jtable of strings and I want to change the colour of certain cells according to their string value, however the solutions i find only allow me to change the colour of an entire column of cells in the jtable and not a specific one.
I have a Jtable of strings and I want to change the colour of certain cells according to their string value
The same renderer is used for all cells so you need to reset the background every time.
You will need an if condition in your custom renderer code. Something like:
if (!isSelected)
if (value.equals(...))
y.setBackground(new Color(255,0,0));
else
y.setBackground(table.getBackground())
You can use DefaultTableCellRenderer to color alternate row from JTable.
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected){
c.setBackground(Color.YELLOW);
}else{
if (row%2 == 0){
c.setBackground(Color.WHITE);
}
else {
c.setBackground(Color.LIGHT_GRAY);
} }
//Add below code here
return c;
}
});
If you want to color your row using the value of a particular row then you can use something like this. Add these line to above
if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
if(value.toString().equals("OK")){//Here `OK` is the value of row
c.setBackground(Color.GREEN);
}
}

Jtable align text both on left and right in the same line

Trying to achieve this on Jtable.
I was trying to align two words like one on left side and another on right side but in the same line.
String html="<html><div style='float:left;width:50%;'>left</div><div style='float:right;width:50%;'>right</div></html>";
Object rowData[][] = { { html, "Column2-data"}};
unfortunately it didn't work. I tried with p tag and font tag as well.
Please help me on how can I achieve this using HTML tags.
You can create your own table cell renderer to center the text in your JTable
public class CenterCellRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JLabel renderedLabel = (JLabel) super
.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
renderedLabel.setHorizontalAlignment(JLabel.CENTER);
return renderedLabel;
}
}
To use this table cell renderer for the entire table:
TableCellRenderer renderer = new CenterCellRenderer();
table.setDefaultRenderer(Object.class, renderer);
To define a column specific renderer, you need to define a JTable subclass that overrides the getCellRenderer method
table = new JTable(...) {
public TableCellRenderer getCellRenderer(int row, int column) {
if (column == 2) {
return renderer;
}
// else...
return super.getCellRenderer(row, column);
}
};
Now that I've thought about your question a bit more, I'd put the text in two columns. If necessary, you can right align the text in the second column using a right justify cell renderer similar to the one I created for centering text.

Categories