允许用户在jTextField中输入并使用打印机打印JFrame

时间:2017-02-16 19:42:31

标签: java jframe jpanel jbutton jtextfield

我在这里遇到麻烦。我希望用户在JTextField中输入他们的名字,然后自动将整个JFrame打印到连接的打印机。请参阅GUI的附图。想法是让用户输入他们的名字,然后名称将以二进制代码出现。之后,将打印“姓名徽章”。

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

这是成功执行的文本到二进制转换代码,但是我在上面的代码中插入它时遇到了麻烦。

    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);
} 

这是我的完整代码。我已经有了ActionListener。任何人都可以玩这个,看看它是否可以修改,以获得我正在寻找的结果?有没有人需要进一步澄清我的问题?

    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                   

}

这是GUI的图像:

GUI image

1 个答案:

答案 0 :(得分:0)

从提供的图像中我假设您想要在用户点击“打印”按钮时阅读JTextField的内容。

所以您需要做的就是为其添加ActionListener

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'
    }

});

在最后时刻编辑

你想知道如何将java中的某些东西打印成像纸一样的东西。我很久以前就这样做了,我担心我不能简单易懂地解释它(我记得它无论如何都是主题)。不过,您可以查看Oracle's Guide to print Java2D。这可能是一个好的开始。