第21章 Swing
程序员文章站
2022-07-14 19:51:31
...
学习 表格设计相关的代码
package twentyone;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
public class tab extends JFrame{
public tab(){
//建立表格
setTitle("表格");
setSize(600,600);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(null);
Container c=getContentPane();
//利用向量 填充内容
String k[]={"A","B","C","D","E","F","G"};
Vector<String> l=new Vector<String>();
for(int i=0;i<k.length;i++){
l.add(k[i]);
}
Vector<Vector<String>> s=new Vector<Vector<String>>();
for(int i = 1; i <=7; i++){
Vector<String> h=new Vector<String>();
for(int j=0;j<k.length;j++){
h.add(k[j]+i);
}
s.add(h);
}
//设计表格样式
final DefaultTableModel dt=new DefaultTableModel(s,l);
final JTable tab=new JTable(dt);
tab.setRowSorter(new TableRowSorter<DefaultTableModel>(dt));
JScrollPane sp=new JScrollPane(tab);
sp.setBounds(100, 50, 400, 400);
c.add(sp);
JTableHeader th=tab.getTableHeader();
th.setBounds(100, 20, 400, 30);
c.add(th);
tab.setRowHeight(30);
tab.setSelectionMode(1);
tab.setSelectionBackground(Color.ORANGE);
tab.setSelectionForeground(Color.BLUE);
tab.setRowSelectionInterval(2, 5);
int e=tab.getSelectedRowCount();
System.out.println(e);
//添加文本框,显示选中行内容
final JTextField x=new JTextField();
final JTextField y=new JTextField();
JLabel a1=new JLabel("A1:");
JLabel b1=new JLabel("B1:");
c.add(x);
c.add(y);
c.add(a1);
c.add(b1);
x.setBounds(100, 500, 60, 40);
y.setBounds(200, 500, 60, 40);
a1.setBounds(70, 500, 20, 40);
b1.setBounds(170, 500, 20, 40);
tab.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
int sr=tab.getSelectedRow();
Object oa=dt.getValueAt(sr, 0);
Object ob=dt.getValueAt(sr, 1);
x.setText(oa.toString());
y.setText(ob.toString());
}
});
//设计添加按钮
final JButton B1=new JButton("添加");
c.add(B1);
B1.setBounds(290, 500, 60, 40);
B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String [] rv={x.getText(),y.getText()};
dt.addRow(rv);
/*int hh=tab.getRowCount()+1;
x.setText("A"+hh);
y.setText("B"+hh);*/
}
});
//设计修改按钮
final JButton B2=new JButton("修改");
c.add(B2);
B2.setBounds(370, 500, 60, 40);
B2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int sr=tab.getSelectedRow();
dt.setValueAt(x.getText(), sr, 0);
dt.setValueAt(y.getText(), sr, 1);
}
});
//设计删除按钮
final JButton B3=new JButton("删除");
c.add(B3);
B3.setBounds(450,500, 60, 40);
B3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int sr=tab.getSelectedRow();
dt.removeRow(sr);
}
});
}
public static void main(String[] args) {
new tab();
}
}
结果: 界面
排序
选中显示
添加功能
修改功能
删除功能