1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| /*
* TableLayoutDemo.java
*/
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableLayoutDemo extends JFrame {
private TableLayout tableLayout;
private String[] columnNames;
private Random r = new Random();
public TableLayoutDemo() {
super("TableLayout Demo");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 300);
setLocationRelativeTo(null);
//create empty TableLayout:
tableLayout = new TableLayout();
//fill the TableLayout:
tableLayout.addColumns("Question", "Reponses");
tableLayout.addRow(new JLabel("Genre?"), createTable(1));
tableLayout.addRow(new JLabel("Pays?"), createTable(2));
tableLayout.addRow(new JLabel("Etat civil?"), createTable(3));
TableColumn column = tableLayout.getColumnModel().getColumn(0);
column.setMinWidth(60);
column.setMaxWidth(280);
getContentPane().add(new JScrollPane(tableLayout), BorderLayout.CENTER);
}
private JComponent createTable(final int type) {
final String[] columnNames1 = new String[]{"Homme", "Femme"};
final String[] columnNames2 = new String[]{"France", "Belgique", "Suisse", "autre"};
final String[] columnNames3 = new String[]{"celibataire", "marie", "autre"};
int columns = 0;
if (type == 1) {
columns = columnNames1.length;
columnNames = columnNames1;
} else if (type == 2) {
columns = columnNames2.length;
columnNames = columnNames2;
} else {
columns = columnNames3.length;
columnNames = columnNames3;
}
DefaultTableModel model = new DefaultTableModel(0, columns) {
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return Integer.class;
}
};
Integer[] rowData = new Integer[columnNames.length];
for (int i = 0; i < rowData.length; i++) {
rowData[i] = r.nextInt(100);
}
model.addRow(rowData);
JTable table = new JTable(model);
table.setSelectionBackground(Color.WHITE);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane jScrollPane = new JScrollPane(table);
jScrollPane.setPreferredSize(new Dimension(200, 34));
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
return jScrollPane;
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TableLayoutDemo().setVisible(true);
}
});
}
} |
Partager