如何向表中添加垂直标题?

pdtvr36n  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(574)

我有这个表,我想做一个标题,就像从0到10,但垂直,从a到j(下图)

另外我想知道的是,如果数字大于10,我如何改变正方形的颜色。

xkrw2x1b

xkrw2x1b1#

您可以添加任何组件作为滚动窗格的行标题视图。
在这种情况下,您可以将jlist与自定义呈现器一起使用:

import java.awt.*;
import javax.swing.*;

public class ListRowHeader extends JPanel
{
    public ListRowHeader()
    {
        JTable table = new JTable(10, 10);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );

        String[] letters = {"A", "B", "C", "D","E", "F", "G", "H", "I", "J"};

        JList<String> list = new JList<>( letters );
        list.setFixedCellWidth(50);
        list.setFixedCellHeight( table.getRowHeight() );
        list.setCellRenderer( new RowHeaderRenderer() );
        scrollPane.setRowHeaderView( list );
    }

    private static class RowHeaderRenderer extends DefaultListCellRenderer
    {
        public RowHeaderRenderer()
        {
            setHorizontalAlignment(JLabel.CENTER);
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            setFont(UIManager.getFont("TableHeader.font"));
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            setBackground(UIManager.getColor("TableHeader.background"));

            return this;
        }
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("ListRowHeader");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ListRowHeader(), BorderLayout.LINE_START);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}

相关问题