问题
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