Desktop Java 8 – part 4 – print table from window of application

In last 2 parts of this tutorial I described how create table in Java. In this section You find out about print this table.

First create table based on table from last part of tutorial.

package doraprojects;

import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class SimpleTable 
{
    
public static final int WIDTH_WINDOW = 400;
public static final int HEIGHT_WINDOW = 200;

    public static void main(String[] args) 
    {
        
    EventQueue.invokeLater(new Runnable(){
     public void run()
     {    
        JFrame f = new JFrame("My window");
        f.setSize(WIDTH_WINDOW, HEIGHT_WINDOW); 
        f.getContentPane().setBackground(Color.white);
       
           String[] columns = { "ID","Name","product","price in $" };  
           Object[][] data = { {1234,"John","pencil",10},
                               {4382,"Mirian","pen",11}, 
                               {2345,"Katy","chair",253}, 
                               {6334,"Agnes","table",456}, 
                               {1177,"Stanley","flower",25} }; 
            
         JTable table = new JTable(data, columns);

         table.getColumnModel().getColumn(0).setPreferredWidth(80);
         table.getColumnModel().getColumn(1).setPreferredWidth(100);
         table.getColumnModel().getColumn(2).setPreferredWidth(150);
         table.getColumnModel().getColumn(3).setPreferredWidth(100);
         
         table.setAutoCreateRowSorter(true);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         JScrollPane scroll = new JScrollPane(table);
         
         f.add(scroll);

         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.setVisible(true);
        
      }
        }); 
   }
}

The code above create simple table. Imagine that user would like to print data contained in this table. How do it? It is easy, because JTable component from Java 1.5 has print method. It displays the printing dialog and allow You print this table.
In this application code You may add button with Print label and add it to the frame.
JButton b = new JButton("Print");
f.add(b);

Because your frame has