[test2.java]
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class test2 {
public static void main(String[] args) {
JFrame frame = new JFrame("Table Test");
frame.setPreferredSize(new Dimension(400,200));
frame.setLocation(500,400);
Container contentPane = frame.getContentPane();
String colName[] = {"NAME","AGE","SEX"};
DefaultTableModel model = new DefaultTableModel(colName,0);
JTable table = new JTable(model);
contentPane.add(new JScrollPane(table),BorderLayout.CENTER);
JPanel panel = new JPanel();
JTextField text1 = new JTextField(6);
JTextField text2 = new JTextField(3);
JTextField text3 = new JTextField(2);
JButton button1 = new JButton("add");
JButton button2 = new JButton("del");
panel.add(new JLabel("NAME"));
panel.add(text1);
panel.add(new JLabel("AGE"));
panel.add(text2);
panel.add(new JLabel("SEX"));
panel.add(text3);
panel.add(button1);
panel.add(button2);
contentPane.add(panel,BorderLayout.SOUTH);
button1.addActionListener(new AddActionListener(table,text1,text2,text3));
button2.addActionListener(new RemoveActionListener(table));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
[AddActionListener.java]
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
JTable table;
JTextField text1,text2,text3;
AddActionListener(JTable table, JTextField text1, JTextField text2,JTextField text3) {
this.table = table;
this.text1 = text1;
this.text2 = text2;
this.text3 = text3;
}
/**
* @param args
*/
public void actionPerformed(ActionEvent e){
String arr[] = new String[3];
arr[0] = text1.getText();
arr[1] = text2.getText();
arr[2] = text3.getText();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(arr);
}
[RemoveActionListener.java]
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
JTable table;
RemoveActionListener(JTable table){
this.table = table;
}
public void actionPerformed(ActionEvent e){
int row = table.getSelectedRow();
if ( row == -1)
return;
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.removeRow(row);
}
}
test2 를 실행시키면 요렇게 생긴놈이 출현.. 두둥
추가와 삭제가 가능하네요.
[출처] 뇌를 자극하는 JAVA 프로그래밍
... 음 책에 있는 예문을 그대로 적었는데 문제의 소지가 있을려나?
어휴.. 맨날 자바 공부해야지 해야지 해야지 하면서 아직까지 안 하는건 뭥미 ㅠ.ㅠ
댓글