0

I'm having trouble here. I want users in to input their name in the JTextField then automatically print the entire JFrame to the connected printer. Please see the attached image of GUI. The idea is for users to input their first name then the name will appear in binary code. After that "Name Badge" will print.

NameTxt.setText("Enter you first name here");
NameTxt.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        NameTxtActionPerformed(evt);
    }
});

This is the text to binary conversion code, which successfully executes, but I'm having trouble inserting it in the code above.

    public static void main(String[] args) {
    String firstname = "FirstName";
    Scanner input = new Scanner(System.in);
    System.out.println("Enter you first name: ");
    firstname = input.next();
    String result = "Hello, my name is ";
    char[] messChar = firstname.toCharArray();

    for (int i = 0; i < messChar.length; i++) {
    result += Integer.toBinaryString(messChar[i]) + " ";
    }

System.out.println(result);
} 

Here is my complete code. I already have ActionListener. Can anyone play wit this and see if it can be modified to get the result I'm looking for? Does anyone need further clarification of my question?

    package binaryname;

    import javax.swing.*;
    import java.awt.event.*; 
    import java.awt.print.*; 
    import java.awt.*;
    import java.util.Scanner;


    public class binaryname extends javax.swing.JFrame {

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

    /**
    * This method is called from within the constructor to initialize the from.
    * 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">                          
    private void initComponents() {

        toppnl = new javax.swing.JPanel();
        helloblb = new javax.swing.JLabel();
        mnilbl = new javax.swing.JLabel();
        bottompnl = new javax.swing.JPanel();
        PrintNameBtn = new javax.swing.JButton();
        NameTxt = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Binary Code Name");

        toppnl.setBackground(new java.awt.Color(255, 51, 0));

        helloblb.setFont(new java.awt.Font("Comic Sans MS", 1, 68));
        helloblb.setForeground(new java.awt.Color(255, 255, 255));
        helloblb.setText("Hello");

        mnilbl.setFont(new java.awt.Font("Comic Sans MS", 0, 48));
        mnilbl.setForeground(new java.awt.Color(255, 255, 255));
        mnilbl.setText("my name is");

        javax.swing.GroupLayout toppnlLayout = new javax.swing.GroupLayout(toppnl);
        toppnl.setLayout(toppnlLayout);
        toppnlLayout.setHorizontalGroup(
        toppnlLayout.createParallelGroup                 (javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, toppnlLayout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(helloblb, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(211, 211, 211))
        .addGroup(toppnlLayout.createSequentialGroup()
            .addGap(180, 180, 180)
            .addComponent(mnilbl)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    toppnlLayout.setVerticalGroup(
        toppnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, toppnlLayout.createSequentialGroup()
            .addContainerGap()
            .addComponent(helloblb)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(mnilbl, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(37, Short.MAX_VALUE))
    );

    bottompnl.setBackground(new java.awt.Color(255, 51, 0));
    bottompnl.setForeground(new java.awt.Color(255, 51, 0));

    PrintNameBtn.setBackground(new java.awt.Color(255, 204, 204));
    PrintNameBtn.setFont(new java.awt.Font("Arial Rounded MT Bold", 1, 18)); // NOI18N
    PrintNameBtn.setForeground(new java.awt.Color(0, 102, 102));
    PrintNameBtn.setText("PRINT");
    PrintNameBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            PrintNameBtnActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout bottompnlLayout = new javax.swing.GroupLayout(bottompnl);
    bottompnl.setLayout(bottompnlLayout);
    bottompnlLayout.setHorizontalGroup(
        bottompnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(bottompnlLayout.createSequentialGroup()
            .addGap(247, 247, 247)
            .addComponent(PrintNameBtn)
            .addContainerGap(262, Short.MAX_VALUE))
    );
    bottompnlLayout.setVerticalGroup(
        bottompnlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bottompnlLayout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(PrintNameBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    NameTxt.setText("Enter you first name here");
    NameTxt.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            NameTxtActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(toppnl, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(bottompnl, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(NameTxt, javax.swing.GroupLayout.Alignment.TRAILING)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(toppnl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(NameTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bottompnl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    pack();
}// </editor-fold>                        

private void PrintNameBtnActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:
    binaryname s = new binaryname(); 
    s.setVisible(true);
}                                            

private void NameTxtActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(binaryname.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(binaryname.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(binaryname.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(binaryname.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>


    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        new binaryname().setVisible(true);
    });
}

// Variables declaration - do not modify                     
private javax.swing.JTextField NameTxt;
private javax.swing.JButton PrintNameBtn;
private javax.swing.JPanel bottompnl;
private javax.swing.JLabel helloblb;
private javax.swing.JLabel mnilbl;
private javax.swing.JPanel toppnl;
// End of variables declaration                   

}

Here is the image of GUI:

GUI image

Rman
  • 1
  • 2
  • So... Your problem is: "From my handler, how do I get it to print?" – ControlAltDel Feb 16 '17 at 19:53
  • Yeah, just user input then print result. I've tried setPrintJob method, but couldn't figure it out. – Rman Feb 16 '17 at 20:04
  • Check out StandardPrint. Hint: I recommend testing that everything is set up and working correctly using `preview`. This way, you can display the Image out what you're going to print first, before wasting tons of paper. But when you're set, you can hook this up with your PrinterJob, print(), and it should basically do the rest: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/print/ – ControlAltDel Feb 16 '17 at 20:11
  • [For example](http://stackoverflow.com/questions/22058738/print-jlabels-icon-in-a-printer-using-a-button/22059079#22059079) and [example](http://stackoverflow.com/questions/22241711/setting-print-size-of-a-jlabel-and-put-a-jradiobutton-on-the-print/22242658#22242658). I'd encourage you to also have a look at Jasper Reports, while it takes a bit of effort, the results are generally better then trying to print a component – MadProgrammer Feb 16 '17 at 20:44

1 Answers1

0

From the image provided I assume you want to read the content of the JTextField when the user hits the 'PRINT' button.

So all you need to do is to add an ActionListener to it.

JButton button; // your 'PRINT' button
JTextField textField; // your text field

button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        final String usersName = textField.getText();
        // do your magic with 'usersName'
    }

});

Edit in last moment

You want to know how to print something out of java to something analog like paper, too. I did this some very long time ago and I fear I won't be able to explain it short and easy (I remember it's quite at topic anyway). However you can have a look at Oracle's Guide to print Java2D. That might be a good start.

Izruo
  • 2,246
  • 1
  • 11
  • 23
  • Izruo, I've tried that. See my entire code above. I thought this would have been a simple task, but little did I know... – Rman Feb 16 '17 at 20:34