Java JTable print

Description

Java JTable print

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Main extends JPanel {

   public Main() {
      setLayout(new BorderLayout(5, 5));
      String[][] data = { /*from  w w w . j  av a  2  s .  co  m*/
            { "", "", "1", "8", "8", "9", "7" }, 
            { "", "", "2", "7", "8", "8", "8" },
            { "", "", "3", "8", "8", "9", "6" }, 
            { "", "", "4", "8", "8", "9", "8" },
            { "", "", "5", "8", "8", "9", "8" } 
          };
      String[] colHeaders = { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
      final JTable timeSheet = new JTable(data, colHeaders);

      JScrollPane sp = new JScrollPane(timeSheet);

      add(sp, BorderLayout.CENTER);

      JButton printButton = new JButton("Print");
      add(printButton, BorderLayout.SOUTH);
      printButton.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               timeSheet.print();
            } catch (PrinterException ex) {
               ex.printStackTrace();
            }
         }
      });
   }

   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
}



PreviousNext

Related