Java中swing之JTabel
对JTabel的增加一行、删除一行、获取所选中的表格的值、增加一列的操作。
操作过程:
1.实例化一个DefaultTableModel对象,将表格中所要显示的内容传给该对象
2.实例化JTable,并接受DefaultTableModel对象
3.实例化一个JScrollPane对象,并接受JTabel对象
4.然后将这个JScrollPane对象添加到frame容器中显示即可。
DefaultTableModel model = new DefaultTableModel(objects,title);//步骤一
JTable table = new JTable(model);//步骤二
JScrollPane scrollPane = new JScrollPane(table);//步骤三
frame.add(scrollPane);//步骤四
对表格的增、删除、获取值,是通过DefaultTableMode的对象对其操作的。
该对象中的方法有:
addRow:增加一行
removeRow:删除一行
getValueAt:获取所选中表格的值
addColumn:增加一列
以下便是对表格l的增加一行、删除一行、获取所选中的表格的值、增加一列操作的代码。
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.table.DefaultTableModel;
public class tabel extends JFrame implements ActionListener{
JTable table;
JScrollPane scrollPane;
DefaultTableModel model;
Object[][] objects = new Object[10][7];
String[] title = {"1","2","3","4","5","6","7"};
public tabel() {
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < objects[i].length; j++) {
objects[i][j] = i+j;
}
}//为表格增加内容
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 693, 582);
setLayout(null);//设置所继承父类JFrame的属性
JButton btnNewButton = new JButton("增加一行");
btnNewButton.setBounds(10, 42, 145, 23);
btnNewButton.addActionListener(this);
add(btnNewButton);
JButton btnNewButton_1 = new JButton("删除该行");
btnNewButton_1.addActionListener(this);
btnNewButton_1.setBounds(10, 131, 145, 23);
add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("获取所选中表格的值");
btnNewButton_2.addActionListener(this);
btnNewButton_2.setBounds(10, 222, 145, 23);
add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("增加一列");
btnNewButton_3.setBounds(10, 312, 145, 23);
btnNewButton_3.addActionListener(this);
add(btnNewButton_3);
model = new DefaultTableModel(objects,title);
table = new JTable(model);
//table.setRowHeight(40);//设置表格显示的行高,可不设置
scrollPane = new JScrollPane(table);
scrollPane.setBounds(180, 10, 489, 509);
add(scrollPane);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
if (actionCommand.equals("增加一行")){
model.addRow(new Object[1]);
}else if (actionCommand.equals("删除该行")){
try{
model.removeRow(table.getSelectedRow());
}catch (Exception w){
JOptionPane.showMessageDialog(this,"请选中一行");
}
}else if (actionCommand.equals("获取所选中表格的值")){
Object valueAt = model.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
JOptionPane.showMessageDialog(this,"选中表格的值为"+valueAt);
}else if (actionCommand.equals("增加一列")){
model.addColumn("新增列");
}
}
public static void main(String[] args) {
tabel frame = new tabel();
}
}