通过GUI输入的文本换行符

时间:2014-05-23 13:08:01

标签: java swing input graphics interface

我正在尝试构建一个程序,通过GUI,接收带有换行符的输入文本,将其拆分为行,然后是空格,并为每个字符串执行“特殊”操作。问题是2:

  1. 我无法将换行符输入到输入字段中;
  2. 我不知道如何将换行符输入输出。
  3. 我该怎么做?我的代码是:

    /*
     * 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.
     */
    
    /**
     *
     * @author michelegorini
     */
    import java.util.Scanner;
    public class HakkaTranslator extends javax.swing.JFrame {
    
        /**
         * Creates new form HakkaTranslator
         */
        public HakkaTranslator() {
            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">                          
        private void initComponents() {
    
            inputField = new javax.swing.JTextField();
            translateButton = new javax.swing.JButton();
            pinyinField = new javax.swing.JLabel();
            hakkaCharField = new javax.swing.JLabel();
            mandCharField = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            translateButton.setText("Translate");
            translateButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    translateButtonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(mandCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(translateButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(inputField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(pinyinField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap())
            );
    
            layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
    
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(translateButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(pinyinField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(inputField, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(mandCharField))
                    .addContainerGap(177, Short.MAX_VALUE))
            );
    
            layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
    
            pack();
        }// </editor-fold>                        
    
        private void translateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
            // TODO add your handling code here:
            Scanner kLFeed = new Scanner(inputField.getText()).useDelimiter("\n");
            Scanner kSp;
            do{
                kSp = new Scanner(kLFeed.next());
                while(kSp.hasNext()){
                    translate(kSp.next());
                }
                translate("<br/>");
            } while(kLFeed.hasNext());
        }                                               
    
        private void translate(String word) {
            pinyinField.setText(pinyinField.getText() + word);
        }
        /**
         * @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(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HakkaTranslator().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JLabel hakkaCharField;
        private javax.swing.JTextField inputField;
        private javax.swing.JLabel mandCharField;
        private javax.swing.JLabel pinyinField;
        private javax.swing.JButton translateButton;
        // End of variables declaration                   
    
    }
    

    此刻。

    更新 考虑到答案和评论,我来到了:

    /*
     * 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.
     */
    
    /**
     *
     * @author michelegorini
     */
    import java.util.Scanner;
    public class HakkaTranslator extends javax.swing.JFrame {
    
        /**
         * Creates new form HakkaTranslator
         */
        public HakkaTranslator() {
            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() {
    
            inputField = new javax.swing.JTextArea();
            translateButton = new javax.swing.JButton();
            pinyinField = new javax.swing.JLabel();
            hakkaCharField = new javax.swing.JLabel();
            mandCharField = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            translateButton.setText("Translate");
            translateButton.addActionListener(new java.awt.event.ActionListener() {
    
                @Override
                public void actionPerformed(java.awt.event.ActionEvent e) {
    
                    inpText = inputField.getText();
                    String[] lines = inpText.split(System.lineSeparator());
                    String[][] words = new String[lines.length][20];
                    for(int i=0;i<lines.length;i++){
                        words[i] = lines[i].split(" ");
                    }
                    for(int i=0;i<lines.length;i++){
                        for(int j = 0;j<words[i].length;j++){
                            translate(words[i][j]);
                        }
                        translate(System.lineSeparator());
                    }
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(mandCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(translateButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(inputField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(pinyinField, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap())
            );
    
            layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
    
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(translateButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(pinyinField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(inputField, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(hakkaCharField, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(mandCharField))
                    .addContainerGap(177, Short.MAX_VALUE))
            );
    
            layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {hakkaCharField, inputField, mandCharField, pinyinField});
    
            pack();
        }// </editor-fold>//GEN-END:initComponents
    
        private void translate(String word) {
            pinyinField.setText(pinyinField.getText() + word + " ");
        }
        /**
         * @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(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(HakkaTranslator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HakkaTranslator().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JLabel hakkaCharField;
        private javax.swing.JTextArea inputField;
        private javax.swing.JLabel mandCharField;
        private javax.swing.JLabel pinyinField;
        private javax.swing.JButton translateButton;
        // End of variables declaration//GEN-END:variables
        String inpText;
    }
    

    一个问题仍然存在:即使使用System.lineSeparator(),输出中的换行也不会出现。我该如何解决?我如何避免每次javax.swing

1 个答案:

答案 0 :(得分:1)

这是如何将文本区域的文本读取为字符串的示例。

public class GetterText extends JFrame {

    JTextArea ta = new JTextArea();
    String taText;

    GetterText() {

        JButton getText = new JButton("GetText");
        getText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                taText = ta.getText();
                System.out.println(taText);
            }
        });

        getContentPane().add(getText, BorderLayout.LINE_START);
        getContentPane().add(new JScrollPane(ta));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {

        new GetterText();
    }
}

您可以使用taText.split(" ")分隔空格,taText.split("\\n")分割线条。