com.ihhira.projects.badgemaker.MainWindow.java Source code

Java tutorial

Introduction

Here is the source code for com.ihhira.projects.badgemaker.MainWindow.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ihhira.projects.badgemaker;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.stage.FileChooser;
import javax.swing.JFileChooser;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 *
 * @author ihhira
 */
public class MainWindow extends javax.swing.JFrame implements Printable {

    private ArrayList<Row> rows = new ArrayList<>();
    int currentPos;
    private File curDir = new File("img.txt");

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        sampleBadge = new com.ihhira.projects.badgemaker.Badge();
        bLoad = new javax.swing.JButton();
        bNext = new javax.swing.JButton();
        bPrev = new javax.swing.JButton();
        bPrint = new javax.swing.JButton();
        currentBadgeIndex = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Badge Maker");

        bLoad.setText("Load Data");
        bLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bLoadActionPerformed(evt);
            }
        });

        bNext.setText(">");
        bNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNextActionPerformed(evt);
            }
        });

        bPrev.setText("<");
        bPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPrevActionPerformed(evt);
            }
        });

        bPrint.setText("print");
        bPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPrintActionPerformed(evt);
            }
        });

        currentBadgeIndex.setText("0");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSeparator1)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(sampleBadge, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup().addComponent(bLoad)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bPrev)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(currentBadgeIndex, javax.swing.GroupLayout.PREFERRED_SIZE, 46,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bNext)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bPrint)))
                        .addContainerGap(15, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(sampleBadge, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(bLoad).addComponent(bNext).addComponent(bPrev).addComponent(bPrint)
                                .addComponent(currentBadgeIndex))
                        .addGap(18, 18, 18)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bLoadActionPerformed
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    loadData();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }//GEN-LAST:event_bLoadActionPerformed

    private void bPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPrevActionPerformed
        if (currentPos > 0) {
            showData(currentPos - 1);
        }
    }//GEN-LAST:event_bPrevActionPerformed

    private void bNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNextActionPerformed
        if (currentPos < rows.size() - 1) {
            showData(currentPos + 1);
        }
    }//GEN-LAST:event_bNextActionPerformed

    private void bPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPrintActionPerformed
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(this);
        boolean ok = job.printDialog();
        if (ok) {
            try {
                job.print();
            } catch (PrinterException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_bPrintActionPerformed

    private void loadData() throws IOException, EncryptedDocumentException, InvalidFormatException {

        JFileChooser fileChooser = new JFileChooser(curDir);
        int ok = fileChooser.showOpenDialog(this);
        if (ok != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File selectedFile = fileChooser.getSelectedFile();
        curDir = selectedFile.getParentFile();

        //        File selectedFile = new File("jugbd-meetup5-attendee-list.xlsx");

        Workbook wb = WorkbookFactory.create(selectedFile);
        Sheet sheet = wb.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        ArrayList<Row> rows = new ArrayList<>();
        while (rowIterator.hasNext()) {
            rows.add(rowIterator.next());
        }
        this.rows = rows;
        if (rows.size() > 0) {
            showData(0);
        }
    }

    void showData(int pos) {
        if (pos < 0 || pos >= rows.size()) {
            return;
        }
        currentPos = pos;

        currentBadgeIndex.setText(currentPos + "/" + rows.size());

        Row row = rows.get(pos);
        sampleBadge.setData(row);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bLoad;
    private javax.swing.JButton bNext;
    private javax.swing.JButton bPrev;
    private javax.swing.JButton bPrint;
    private javax.swing.JLabel currentBadgeIndex;
    private javax.swing.JSeparator jSeparator1;
    private com.ihhira.projects.badgemaker.Badge sampleBadge;
    // End of variables declaration//GEN-END:variables

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        System.out.println("Printing page - " + pageIndex);
        Dimension d = sampleBadge.getSize();
        Graphics2D g = (Graphics2D) graphics;

        int printingIndex = pageIndex * 4;
        if (printingIndex >= rows.size()) {
            return NO_SUCH_PAGE;
        }

        double width = pageFormat.getWidth();
        double height = pageFormat.getHeight();

        showData(printingIndex);
        sampleBadge.printAll(g);

        g.translate(width / 2, 0);
        showData(printingIndex + 1);
        sampleBadge.printAll(g);

        g.translate(0, height / 2);
        showData(printingIndex + 2);
        sampleBadge.printAll(g);

        g.translate(-width / 2, 0);
        showData(printingIndex + 3);
        sampleBadge.printAll(g);

        g.translate(0, -height / 2);

        return PAGE_EXISTS;
    }
}