1

我正在摆弄 JTable,我想制作一个表格,其中字母 AP 作为行名,数字 1-24 作为列名(它们是什么数据类型都没有关系)。这些行名和列名是在表内还是作为外轴(无论哪个更简单)都没有关系。

我目前的尝试是String[]为行名和列名命名 a,并String[][]用实际内容命名 a。但我不知道如何将其合并为创建 JTable 的有效格式。我当前的代码(不起作用)如下:

    // Create table
    String[] columnNames = {"", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
                              "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
                             };

    String[] rowNames = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"};

    String[][] compoundNames = new String[25][16];

    Object[][] plateData = {rowNames, compoundNames};

    table = new JTable(plateData, columnNames);
    table.setBorder(new LineBorder(new Color(0, 0, 0)));
    table.setBounds(10, 11, 564, 440);
    contentPane.add(table);

建议的解决方案不必遵循这个概念思想。如前所述,最简单的方法来制作我需要的东西,将不胜感激。

4

2 回答 2

1
  • String[][] compoundNames = new String[25][16];应该是String[][] compoundNames = new String[16][25];columnNames 和 的编号元素rowNames

  • 基本信息需要阅读 Oracle 教程如何使用表

在此处输入图像描述

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.TableModel;

public class TableWithTimer {

    private JFrame frame = new JFrame();
    private JScrollPane scroll = new JScrollPane();
    private JTable myTable;
    private String[] columnNames = {"", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
        "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"};
    private String[] rowNames = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
        "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", "Z"};
    private Object[][] compoundNames = new String[26][25];
    private int count = 1;
    private javax.swing.Timer timer = null;

    public TableWithTimer() {
        myTable = new JTable(compoundNames, columnNames);
        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        myTable.setPreferredScrollableViewportSize(new Dimension(400, 300));
        myTable.setShowHorizontalLines(true);
        myTable.setShowVerticalLines(true);
        scroll.setViewportView(myTable);
        frame.add(scroll, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
        start();
    }

    private void start() {
        timer = new javax.swing.Timer(2500, updateCol());
        timer.start();
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("updating row " + (count + 1));
                TableModel model = myTable.getModel();
                int row = model.getRowCount() - 1;// -1 == leave the cell empty at [0, 0]
                for (int j = 0; j < row; j++) {
                    myTable.changeSelection(row, 0, false, false);
                    Object value = rowNames[j];
                    model.setValueAt(value, count, 0);
                    count++;
                    if (count >= myTable.getRowCount()) {
                        myTable.changeSelection(0, 0, false, false);
                        timer.stop();
                        System.out.println("update cycle completed");
                        myTable.clearSelection();
                    }
                }
            }
        };
    }

    public static void main(String args[]) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                //System.out.println(info.getName());
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        TableWithTimer tableWithTimer = new TableWithTimer();
    }
}
于 2013-07-31T10:58:52.017 回答
1

您应该对字母值使用行标题。这是一个使用行标题的示例:

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

public class TableRowHeader extends JList implements TableModelListener
{
    private JTable table;

    @SuppressWarnings("unchecked")
    public TableRowHeader(JTable table)
    {
        this.table = table;

        setAutoscrolls( false );
        setCellRenderer(new RowHeaderRenderer());
        setFixedCellHeight(table.getRowHeight());
        setFixedCellWidth(50);
        setFocusable( false );
        setModel( new TableListModel() );
        setOpaque( false );
        setSelectionModel( table.getSelectionModel() );
        table.getModel().addTableModelListener( this );
    }

    public void tableChanged(TableModelEvent e)
    {
        if (e.getType() == TableModelEvent.INSERT
        ||  e.getType() == TableModelEvent.DELETE)
        {
            repaint();
        }
    }

    /*
     *  Use the table to implement the ListModel
     */
    class TableListModel extends AbstractListModel
    {
        public int getSize()
        {
            return table.getRowCount();
        }

        public Object getElementAt(int index)
        {
            return String.valueOf(index + 1);
        }
    }

    /*
     *  Use the table row header properties to render each cell
     */
    class RowHeaderRenderer extends DefaultListCellRenderer
    {
        RowHeaderRenderer()
        {
            setHorizontalAlignment(CENTER);
            setOpaque(true);
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            setFont(table.getTableHeader().getFont());
            setBackground(table.getTableHeader().getBackground());
            setForeground(table.getTableHeader().getForeground());
        }

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

            if (isSelected)
            {
                setBackground( table.getSelectionBackground() );
            }
            else
            {
                setBackground( table.getTableHeader().getBackground() );
            }

            setText( (value == null) ? "" : value.toString() );

            return this;
        }
    }
    private static void createAndShowUI()
    {

        final JTable table = new JTable( 1000, 256 );
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        JScrollPane scrollPane = new JScrollPane( table );
        scrollPane.setRowHeaderView( new TableRowHeader( table) );

        JFrame frame = new JFrame("Row Header Test");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

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

在您的情况下,您将不需要自定义 ListModel。您只需将值 AP 添加到 JList。

于 2013-07-31T18:24:50.373 回答