使用热键增加 JTable 中的字体大小

Increase font size in JTable using hotkey

随着年龄的增长,我在OSX中越来越多地使用Ctrl-+来增加字体大小各种 windows(浏览器、编辑器等)。但是,在 JTable 的自定义应用程序中,它当然不起作用。

如何将此功能添加到我自己的 Swing JTable 中?

我希望它 increase/decrease 我在 JTable 中已有的任何字体,并适当调整列宽。

我对如何编写代码(添加热键、​​采用当前字体、增加大小、设置新字体、使无效)有一个大致的了解,但不知道如何将它应用到我已有的许多表中。也不是如何正确调整列宽。

我应该创建一个新的基础 class 还是添加某种插件?其他想法?

这个解决方案有点粗糙,但它演示了如何使用 ctrl +ctrl -:[= 实现放大和缩小13=]

public class FontTable extends JPanel {

    JTable table;

    FontTable() {

        Object[][] data = {{"aaa", "122", "_____"}, {",,,,,", ",,,", ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"}};
        Object[] names = {"C1", "C2", "C3"};
        table = new JTable(data, names);

        InputMap im = table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        im.put(KeyStroke.getKeyStroke('=', InputEvent.CTRL_DOWN_MASK), "zoom in");
        im.put(KeyStroke.getKeyStroke('-', InputEvent.CTRL_DOWN_MASK), "zoom out");
        table.getActionMap().put("zoom in", new ZoomAction(true));
        table.getActionMap().put("zoom out", new ZoomAction(false));

        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    class ZoomAction extends AbstractAction {

        boolean in;

        ZoomAction(boolean in) {

            this.in = in;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            Font oldFont = table.getFont();
            float size = oldFont.getSize() + (in ? +2 : -2);
            table.setFont(oldFont.deriveFont(size));

            for (int row = 0; row < table.getRowCount(); row++) {
                int rowHeight = table.getRowHeight(row);

                for (int col = 0; col < table.getColumnCount(); col++) {
                    Component comp = table.prepareRenderer(table.getCellRenderer(row, col), row, col);
                    TableColumn column = table.getColumnModel().getColumn(col);
                    int colWidth = column.getWidth();

                    rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
                    colWidth = comp.getPreferredSize().width;

                    column.setPreferredWidth(colWidth);
                }
                table.setRowHeight(row, rowHeight);
            }
        }
    }
}

我参考了Camick's answer。把它放在某个框架中进行测试。

至于向后实现它,您可以子 class JTable 并添加此新功能,然后用新的 class 替换现有功能,或者做一些更棘手的事情在接口中嵌套 classes 并实现该接口。