ひな形(削除ボタンとスクロールバーが付いた長いテーブル) †
package com.snail.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public final class TableExam extends JFrame implements ActionListener {
private static final long serialVersionUID = 8317897946759086742L;
private ReadOnlyTable table;
private JButton delButton = new JButton("削除");
public TableExam() {
// テーブル作成
Vector<String> colIndex = new Vector<String>();
Vector<Vector> row = new Vector<Vector>();
for (int colNum = 0; colNum < 2; colNum++) {
colIndex.add(colNum + "列");
}
for (int rowNum = 0; rowNum < 10000; rowNum++) {
Vector<String> col = new Vector<String>();
for (int colNum = 0; colNum < colIndex.size(); colNum++) {
col.add(rowNum + "行" + colNum + "列");
}
row.add(col);
}
table = new ReadOnlyTable(row, colIndex);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(200, 300));
this.getContentPane().add(scrollPane, BorderLayout.NORTH);
// 削除ボタン
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(delButton);
this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
delButton.addActionListener(this);
}
public static void main(String[] args) {
JFrame jFrame = new TableExam();
jFrame.setBounds(10, 10, 300, 500);
jFrame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
int[] selectedRows = table.getSelectedRows();
int delRows = 0;
for (int cnt = 0; cnt < selectedRows.length; cnt++) {
System.out.println("DEL:" +
table.getValueAt(selectedRows[cnt] - delRows, 0));
DefaultTableModel tblModel = (DefaultTableModel) table.getModel();
tblModel.removeRow(selectedRows[cnt] - delRows);
delRows++;
}
}
}
class ReadOnlyTable extends JTable {
private static final long serialVersionUID = 5036129394555899969L;
public ReadOnlyTable(Vector row, Vector col) {
super(row, col);
this.getTableHeader().setReorderingAllowed(false); //列の入れ替えを禁止
}
public boolean isCellEditable(int rowIndex, int colmunIndex) {
return false; // 編集は禁止
}
public Component prepareRenderer(TableCellRenderer renderer, int row,
int column) {
Component c = super.prepareRenderer(renderer, row, column);
// 一列名は青、二列名は赤で表示
switch (column) {
case 0:
c.setForeground(Color.BLUE);
break;
case 1:
c.setForeground(Color.RED);
break;
default:
c.setForeground(Color.BLACK);
}
return c;
}
}
実行結果 †
参考文献 †
- てんぷらメモ,http://terai.xrea.jp/FrontPage.html
Java#GUI