1

如何在java中更改表格格式?

现在,我有左表,但我希望我的表看起来像右表。

图片

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class Farby extends JTable {
    public Farby(String[][] data, String[] fields) {
        super(data, fields);
    }

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component c = super.prepareRenderer(renderer, row, column);
        c.setBackground(row % 2 == 0 ? getBackground() : Color.getHSBColor(250, 250, 128));
        return c;
    }

    public static void main(String[] args) {
        String[] fields = {"So long String", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
        String[][] a2 = new String[12][12];
        for (int i = 0; i < a2.length; i++) {
            for (int j = 0; j < a2[0].length; j++) {
                a2[i][j] = i + j + "";
            }
        }
        JFrame frame = new JFrame("Help");
        Farby table = new Farby(a2, fields);
        JScrollPane pane = new JScrollPane(table);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(pane, BorderLayout.CENTER);
    //    frame.add(pane);

        frame.setSize(800, 400);
    //    frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
4

1 回答 1

3

你需要类似的东西

 table.getColumnModel().getColumn(1).setPreferredWidth(15);

这取决于您是否希望用户能够更改宽度。您可以在循环中调用上述内容来设置除第一个之外的所有内容。

于 2013-04-12T16:15:25.197 回答