CellRenderer - 使多个单元格变粗

时间:2014-03-21 12:49:55

标签: java swing fonts jtable tablecellrenderer

我想将多个单元格加粗,我有一个arraylist,单元格名称应该是粗体但似乎不起作用。带有我想要粗体的单元格的Arraylist称为bibNumbers,到目前为止尝试将arralist转换为数组并将if语句放入循环并将循环结果转换为粗体变量

//编辑

添加了示例,所以现在id希望第2列中的所有0和1都是粗体。

import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

public class as extends JFrame {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private ArrayList<String> ShadowBibNumber;
/**
 * Launch the application.
 */
public static void main(String[] args) {

    as frame = new as();
    frame.setVisible(true);
}

/**
 * Create the frame.
 */
public as() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));

    ShadowBibNumber = new ArrayList<String>();
    ShadowBibNumber.add("0");
    ShadowBibNumber.add("1");
    JLabel lblNewLabel = new JLabel("New label");
    contentPane.add(lblNewLabel, BorderLayout.NORTH);
    DefaultTableModel tableModel = new DefaultTableModel();
    tableModel.addColumn("column 0");
    tableModel.addColumn("column 1");
    tableModel.addColumn("column 2");
    tableModel.addColumn("column 3");
    tableModel.addColumn("column 4");

    new JScrollPane(table);

    table = new JTable(tableModel);

    table.setEnabled(false);

    table.setPreferredScrollableViewportSize(new Dimension(200, 100));
    JScrollPane scrollPaneForTable = new JScrollPane(table);
    contentPane.add(scrollPaneForTable, BorderLayout.CENTER);

    for (int i = 0; i < 20; ++i) {
        tableModel
                .addRow(new Object[] { i, i, i, i, i });

    }

    table.getColumn("column 2").setCellRenderer(new boldRenderer());


}

class boldRenderer extends DefaultTableCellRenderer {

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

        for (Object x: ShadowBibNumber) {
            if (table.getValueAt(row, 2).equals(x)) {
                cellComponent.setFont(cellComponent.getFont().deriveFont(
                        Font.BOLD));

            } else {
                cellComponent.setFont(cellComponent.getFont().deriveFont(
                        Font.PLAIN));
            }
        }
            return cellComponent;

    }
} }

0 个答案:

没有答案