1个回答
展开全部
import java.io.BufferedWriter; import java.io.FileWriter; import javax.swing.JFrame; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.JScrollPane; import javax.swing.JButton; import javax.swing.JPanel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class Demo2 extends JFrame { private String[]header = new String[]{"姓名","性别","年龄"}; private String[][]data = new String[][] { {"张三","男","20"}, {"李四","男","25"}, {"王五","女","18"} }; private DefaultTableModel dtm = new DefaultTableModel(data,header); private JTable table = new JTable(dtm); private JScrollPane sp = new JScrollPane(table); private JButton but = new JButton("保存"); public Demo2() { but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { BufferedWriter br = new BufferedWriter(new FileWriter("a.txt")); for(int i=0;i<dtm.getRowCount();i++) { for(int j=0;j<dtm.getColumnCount();j++) { br.write(dtm.getValueAt(i, j).toString()+"\t"); } br.newLine(); } br.close(); JOptionPane.showMessageDialog(null,"保存成功"); } catch(Exception ex) { ex.printStackTrace(); } } }); JPanel pan = new JPanel(); pan.add(but); this.getContentPane().add(pan,"South"); this.getContentPane().add(sp); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400,300); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[]args) { new Demo2(); } }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询