3

编辑:[已解决]:似乎每次我尝试增加和减少字体大小时都会调用 CustomTableCellRenderer 的 getTableCellRendererComponent 。

所以我更新了我的代码来处理这个方法本身的字体大小。我正在使用一个静态变量来跟踪当前的字体大小(这是因为这个值会影响当前在我的 UI 中显示的所有表格的字体大小

我已经更新了代码来解决这个问题。欢迎对此提出任何意见/反馈。再次感谢!


我要解决的问题是基于单击不同的 JLabel 动态更改(即增加/减少)JTable 中的字体大小

我有一个面板,其中包含两个标签(用于增加/减少字体大小)和一个 JTable。我在这个表上附加了一个自定义的 TableCellRenderer。

创建表的代码如下:

JTable table = new JTable(data, tableHeader){
    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row,
            int column) {
        Component component = super.prepareRenderer(renderer, row, column);
        int rendererWidth = component.getPreferredSize().width;
        TableColumn tableColumn = getColumnModel().getColumn(column);
        tableColumn.setPreferredWidth(Math.max(rendererWidth +
                getIntercellSpacing().width + 10,
                tableColumn.getPreferredWidth()));
        return  component;
    }

};
table.setPreferredScrollableViewportSize(new Dimension(5000, 200));
table.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setDefaultRenderer(table.getColumnClass(0), new CustomTableCellRenderer());

自定义 TableCellRenderer 实现如下:

public class CustomTableCellRenderer extends DefaultTableCellRenderer {

    private Font customFont;

    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);

        customFont = component.getFont();
        customFont = new Font(customFont.getName(), customFont.getStyle(), MainUI.DEFAULT_TABLE_FONT_SIZE);
        component.setFont(customFont);

        if (value.toString().matches("(?i:.*error.*)")) {
            c.setForeground(Color.RED);
        } else {
            c.setForeground(Color.BLACK);
        }
        return c;
    }

    public void increaseFontSize(){
        MainUI.DEFAULT_TABLE_FONT_SIZE = getFont().getSize() + 1;
    }

    public void decreaseFontSize(){
        MainUI.DEFAULT_TABLE_FONT_SIZE = getFont().getSize() + 1;
    }

}

对于按钮,我附加了一个鼠标侦听器和 mouseClicked 事件,我正在尝试执行以下操作来实现该功能:

if(table.getDefaultRenderer(table.getColumnClass(0)) instanceof CustomTableCellRenderer){
    CustomTableCellRenderer tableCellRenderer = (CustomTableCellRenderer) table.getDefaultRenderer(table.getColumnClass(0));
    tableCellRenderer.increaseFontSize();
    table.repaint();            
}

但是我看表没有变化。我究竟做错了什么?以及如何实现所需的功能?

任何意见/建议将不胜感激。谢谢!

4

1 回答 1

4
  • 基本上你必须设置 JTable#setFont()

  • 在渲染器中你可以增加 FontSize 取决于

    a) TableCell 中的值

    b) 行或列索引

    c) isSelected 和 hasFocus

  • 在渲染器中最好覆盖 isSelected 和 hasFocus

  • 对于没有更改 TabelModel 和 ColumnModel 的 JTable,可以仅使用 prepareRender(我的观点是我喜欢 prepareRenderer)

编辑

我将更改 JTable#setFont(),而不是将其增加到 Renderer,然后将更改的字体应用于行、列或选择

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.TextAttribute;
import java.util.Map;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.table.*;

public class TablePrepareRenderer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TablePrepareRenderer() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) /*{

                private static final long serialVersionUID = 1L;
                private Border outside = new MatteBorder(1, 0, 1, 0, Color.red);
                private Border inside = new EmptyBorder(0, 1, 0, 1);
                private Border highlight = new CompoundBorder(outside, inside);

                @Override
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component comp = super.prepareRenderer(renderer, row, column);
                JComponent jc = (JComponent) comp;
                Map attributes = (table.getFont()).getAttributes();
                //attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
                attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
                if (!isRowSelected(row)) {
                comp.setForeground(Color.black);
                comp.setBackground(row % 2 == 0 ? Color.white : Color.orange);
                int modelRow = convertRowIndexToModel(row);
                String type = (String) getModel().getValueAt(modelRow, 0);
                if (type.equals("Sell")) {
                comp.setFont(new Font(attributes));
                comp.setForeground(Color.red);
                } else {
                comp.setFont(table.getFont());
                }
                } else {
                comp.setFont(table.getFont());
                }
                jc.setBorder(BorderFactory.createCompoundBorder(jc.getBorder(), BorderFactory.createEmptyBorder(0, 0, 0, 5)));
                return comp;
                }
                }*/;
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton increase = new JButton("+");
        increase.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Font font = table.getFont();
                font = font.deriveFont((float) (font.getSize2D() * 1.10));
                table.setFont(font);
            }
        });
        add(increase, BorderLayout.EAST);
        JButton decrease = new JButton("-");
        decrease.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Font font = table.getFont();
                font = font.deriveFont((float) (font.getSize2D() * .90));
                table.setFont(font);
            }
        });
        add(decrease, BorderLayout.WEST);
    }

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

            @Override
            public void run() {
                TablePrepareRenderer frame = new TablePrepareRenderer();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
于 2012-06-21T20:42:23.383 回答