//Example1c.java
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;
public class Example1c
{
//data
Object[] colNames={"name","material","size","color","note"};
Object[][] rowData={
{"A01","cloth","large","white","soft"},
{"K01","thread","thin","red","strong"},
{"U01","paper","middle","yellow","cheap"},
{"S01","string","middle","black","quality"},
};
JTable t= new JTable(rowData, colNames);
//main
public static void main(String args[]){
Example1c sample = new Example1c();
}
//constructor
public Example1c(){
//make frame
final JFrame f=new JFrame("MenuBar");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
//menu bar
JMenuBar mb = new JMenuBar();
JMenu mFile = new JMenu("File");
JMenuItem iSaveAs = new JMenuItem("Save As ..");
JMenuItem iExit = new JMenuItem("Exit");
mFile.add(iSaveAs);
mFile.addSeparator();
mFile.add(iExit);
mb.add(mFile);
f.getRootPane().setJMenuBar(mb);
//add table
t.setRowHeight(20);
t.setGridColor(Color.gray);
JScrollPane sp=new JScrollPane();
sp.getViewport().setView(t);
sp.setPreferredSize(new Dimension(300, 120));
JPanel p=new JPanel();
p.add(sp);
f.getContentPane().add(p,BorderLayout.CENTER);
//show frame
f.setLocation(10, 10);
f.setBounds(50,50,320,185);
f.setVisible(true);
//actionlistener at exit click
iExit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {System.exit(0);}
});
iSaveAs.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc=new JFileChooser(System.getProperty("user.dir"));
//show dialog
int fd = fc.showSaveDialog(f);
try{
if(fd==JFileChooser.APPROVE_OPTION){
FileOutputStream fo=new FileOutputStream(fc.getSelectedFile());
PrintStream ps=new PrintStream(fo);
ps.println(t.getValueAt(0,0)+"\t"+t.getValueAt(0,1)+"\t"+t.getValueAt(0,2)+"\t"+t.getValueAt(0,3)+"\t"+t.getValueAt(0,4));
ps.println(t.getValueAt(1,0)+"\t"+t.getValueAt(1,1)+"\t"+t.getValueAt(1,2)+"\t"+t.getValueAt(1,3)+"\t"+t.getValueAt(1,4));
ps.println(t.getValueAt(2,0)+"\t"+t.getValueAt(2,1)+"\t"+t.getValueAt(2,2)+"\t"+t.getValueAt(2,3)+"\t"+t.getValueAt(2,4));
ps.println(t.getValueAt(3,0)+"\t"+t.getValueAt(3,1)+"\t"+t.getValueAt(3,2)+"\t"+t.getValueAt(3,3)+"\t"+t.getValueAt(3,4));
ps.close();
fo.close();
}
}catch(Exception ex){}
}
}
);
}
}