Java - table - change table format

纵饮孤独 提交于 2020-01-05 07:35:09

问题


how can I change table format in java?

Now, I have left table, but I want my table looks like right table.

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

回答1:


you need something similar to

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

it depends on if you want users to be able to change the width or not. you can call the above in a loop to set all but the first one.



来源:https://stackoverflow.com/questions/15976128/java-table-change-table-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!