gpt4 book ai didi

java - 根据正值或负值渲染 jtable 单元格前景

转载 作者:行者123 更新时间:2023-12-01 17:03:29 25 4
gpt4 key购买 nike

我不知道应该如何处理这个问题,我想要做的是当值大于 0 时这些 P&L 单元格前景为绿色,如果小于 0 则为红色。我知道我需要以某种方式使用 tablecellrenderer我只是不知道如何开始。

enter image description here

这是表格设置:

tbl_positions = new WebTable(posdata, posHeaders)
{
public Component prepareRenderer(TableCellRenderer renderer,
int rowIndex, int vColIndex) {
Component c = super.prepareRenderer(renderer, rowIndex,
vColIndex);
if (rowIndex % 2 == 0 && !isCellSelected(rowIndex, vColIndex))
{
c.setBackground((new Color(216, 216, 216)));
}
else
{
if(!isCellSelected(rowIndex, vColIndex))
{
if(rowIndex != 21)
c.setBackground(getBackground());
else
c.setBackground((new Color(216, 249, 255)));
}
else
{
c.setBackground((new Color(0, 128, 255)));
}
}

if(vColIndex == 5 || vColIndex == 6 )
{
Integer intValue = (Integer) getValueAt(rowIndex, vColIndex);
c.setForeground(getColor(intValue));
}
else
{
c.setForeground(getForeground());
}

return c;
}

private Color getColor(Integer intValue)
{
Color color = null;
if (intValue > 0) {
color = Color.GREEN;
} else if (intValue < 0) {
color = Color.RED;
} else {
color = getForeground();
}
return color;
}
};

现在可以运行了:

enter image description here

最佳答案

对于像设置前景这样简单的事情,您不需要自定义渲染器。您只需重写 JTableprepareRenderer 即可。类似的东西

JTable table = new JTable(model) {
@Override
public Component prepareRenderer(TableCellRenderer renderer,
int row, int col) {

Component c = super.prepareRenderer(renderer, row, col);
if (col == PL_COLUMN) {
Integer intValue = (Integer) getValueAt(row, col);
c.setForeground(getColor(intValue));
} else {
c.setForeground(getForeground());
}
return c;
}

private Color getColor(int intValue) {
Color color = null;
if (intValue > 0) {
color = Color.GREEN;
} else if (intValue < 0) {
color = Color.RED;
} else {
color = getForeground();
}
return color;
}
};

花点时间看一下How to Use Tables: Editors and Renderers有关自定义渲染的更多信息

<小时/>

更新:完整演示

import java.awt.Color;
import java.awt.Component;
import java.util.Random;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class TestTableRenderer {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
NikeSaysJustDoIt();
}
});
}

private static void NikeSaysJustDoIt() {
Random random = new Random();
Object[][] data = new Object[30][7];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = (random.nextInt(65536) - 32768);
}
}
String[] cols = new String[] { "col", "col", "col", "col", "col", "col", "col" };
DefaultTableModel model = new DefaultTableModel(data, cols);
JTable table = new JTable(model) {
@Override
public Component prepareRenderer(TableCellRenderer renderer,
int row, int col) {

Component c = super.prepareRenderer(renderer, row, col);
if (col == 5 || col == 6) {
Integer intValue = (Integer) getValueAt(row, col);
c.setForeground(getColor(intValue));
} else {
c.setForeground(getForeground());
}
return c;
}

private Color getColor(int intValue) {
Color color = null;
if (intValue > 0) {
color = Color.GREEN;
} else if (intValue < 0) {
color = Color.RED;
} else {
color = getForeground();
}
return color;
}
};
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
}

enter image description here

<小时/>

更新 2:最后一行使用所有 double 值和 NumberFormat。

我留下了一堆注释,可以帮助您理解代码。请注意,您可能需要格式化程序。您拥有的图像显示为不同的格式。一种有货币符号,一种没有。另外,您的一些值是整数,一些是小数。因此,您很可能需要两个格式化程序才能按照您想要的方式获得它。

enter image description here

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableFormatRenderDemo {

public TableFormatRenderDemo() {
JFrame frame = new JFrame();
frame.add(new JScrollPane(createTable()));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

/*
* We are using all double values. We leave the rendering to
* the renderer. The NumberFormat is used to format the text.
*/
private JTable createTable() {
Object[][] data = new Object[][] {
{ "AUD", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ "CAD", 0.0, 0.0, 0.0, 0.0, 45.00, -0.35 },
{ "CHF", 0.897, -1, 0.896, 0.0, -120.00, 0.00 },
{ "CHK", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ "Total", null, null, null, null, 20125.00, 0.00 } };
String[] cols = { "col 1", "col 2", "col 3", "col 4", "col 5", "col 6",
"col 7" };
DefaultTableModel model = new DefaultTableModel(data, cols);
JTable table = new JTable(model) {
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
};
// Set the custom renerer
table.setDefaultRenderer(Object.class, new NumberFormatRenderer());
return table;
}

private NumberFormat getFormatter() {
NumberFormat formatter = NumberFormat.getCurrencyInstance();
DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) formatter)
.getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol("$");
((DecimalFormat) formatter)
.setDecimalFormatSymbols(decimalFormatSymbols);
return formatter;
}

/**
* Custom renderer we use for the table
*/
private class NumberFormatRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 5152961981995932787L;
private static final int PL_USD_COL = 5;
private static final int DAILY_PL_COL = 6;
// TODO We may want to have a setter for this formatter
private final NumberFormat formatter = getFormatter();

private final Color POSITIVE_COLOR = new Color(65, 185, 62);
private final Color NEGATIVE_COLOR = Color.RED;
private final Color LAST_ROW_COLOR = Color.CYAN;
private final Color ALT_ROW_COLOR = Color.LIGHT_GRAY;

public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);

renderAlternateBackground(row, table.getBackground(), table.getRowCount());
renderForeground(row, column, table.getForeground(),
table.getRowCount(), value);

// Formats the last row with the given NumberFormat
if (row == table.getRowCount() - 1 && column != 0 && value != null) {
setText(formatter.format((Double) value));
}

// Centers the text
setHorizontalAlignment(CENTER);

return this;
}

/**
* Renders the foreground. Render only if column is one of
* the predefined "PL" columns, using the helper method
* <code>getColor</code> to determine the color to render based on the
* <code>value</code>.
*
* @param row
* @param col
* @param tableForeground
* @param rowCount
* @param value
*/
private void renderForeground(int row, int col, Color tableForeground,
int rowCount, Object value) {
if (col == PL_USD_COL || col == DAILY_PL_COL) {
setForeground(getColor((Double) value, tableForeground));
} else {
setForeground(tableForeground);
}
}

/**
* Helper method for the <code>renderForeground</code> method. Returns
* a <code>Color</code> base on the value.
* @param value
* @param tableForeground
* @return
*/
private Color getColor(double value, Color tableForeground) {
Color color = null;
if (value > 0) {
color = POSITIVE_COLOR;
} else if (value < 0) {
color = NEGATIVE_COLOR;
} else {
color = tableForeground;
}
return color;
}

/**
* Rendered alternate background color. Check for odd rows numbers.
* The last row is rendered as the select <code>LAST_ROW_COLOR</code> color.
* @param row
* @param tableBackground
* @param rowCount
*/
private void renderAlternateBackground(int row, Color tableBackground,
int rowCount) {
if (row % 2 != 0) {
setBackground(ALT_ROW_COLOR);
} else if (row == (rowCount - 1)) {
setBackground(LAST_ROW_COLOR);
} else {
setBackground(tableBackground);
}
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TableFormatRenderDemo();
}
});
}
}

关于java - 根据正值或负值渲染 jtable 单元格前景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26534515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com