2013-07-13 6 views
1

JTextArea 줄 번호를 줄 바꿈 된 텍스트를 포함 할 싶어요. 그리고 멋진 샘플 코드가 있습니다 Here ThreadJTextArea의 줄 수를 계산하는 방법은 줄 바꿈을 포함 하시겠습니까?

하지만 Dynamic JTextArea를 사용하여 수정하려고합니다. 그러나 줄 번호 계산이 잘못되었습니다. 여기

나에 의해 수정 된 코드입니다 :

package fandi.demo; 

import java.awt.font.FontRenderContext; 
import java.awt.font.LineBreakMeasurer; 
import java.text.AttributedCharacterIterator; 
import java.text.AttributedString; 
import javax.swing.JTextArea; 
import javax.swing.event.DocumentEvent; 
import javax.swing.event.DocumentListener; 

public class JTextAreaCountModified extends javax.swing.JFrame { 

    public JTextAreaCountModified() { 
     initComponents(); 
     setLocationRelativeTo(null); 

     txtResult.getDocument().addDocumentListener(new DocumentListener() { 

      @Override 
      public void insertUpdate(DocumentEvent e) { 
       if(txtResult.getText().length() > 0) { 
        lblCountLine.setText(String.valueOf(countLines(txtResult))); 
       } else { 
        lblCountLine.setText("0"); 
       } 
      } 

      @Override 
      public void removeUpdate(DocumentEvent e) { 
       if(txtResult.getText().length() > 0) { 
        lblCountLine.setText(String.valueOf(countLines(txtResult))); 
       }else { 
        lblCountLine.setText("0"); 
       } 
      } 

      @Override 
      public void changedUpdate(DocumentEvent e) { 
       if(txtResult.getText().length() > 0) { 
        lblCountLine.setText(String.valueOf(countLines(txtResult))); 
       }else { 
        lblCountLine.setText("0"); 
       } 
      } 
     }); 
    } 

    // COUNTING LINE GOES HERE... 
    public static int countLines(JTextArea textArea) { 
     AttributedString text = new AttributedString(textArea.getText()); 
     FontRenderContext frc = textArea.getFontMetrics(textArea.getFont()).getFontRenderContext(); 
     AttributedCharacterIterator charIt = text.getIterator(); 
     LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIt, frc); 
     float formatWidth = (float) textArea.getSize().width; 
     lineMeasurer.setPosition(charIt.getBeginIndex()); 

     int noLines = 0; 
     while (lineMeasurer.getPosition() < charIt.getEndIndex()) { 
      lineMeasurer.nextLayout(formatWidth); 
      noLines++; 
     } 

     int lineEnter = textArea.getLineCount(); 
     int countLine = noLines + lineEnter; 

     return countLine-1; 
    } 
    // END OF COUNTING METHOD 

    /** 
    * 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() { 

     jLabel1 = new javax.swing.JLabel(); 
     jLabel2 = new javax.swing.JLabel(); 
     jScrollPane1 = new javax.swing.JScrollPane(); 
     txtResult = new javax.swing.JTextArea(); 
     jLabel3 = new javax.swing.JLabel(); 
     lblCountLine = new javax.swing.JLabel(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
     setTitle("JTextArea Line Counting include Wrap"); 
     setResizable(false); 

     jLabel1.setText("Enter paragraph"); 

     jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N 
     jLabel2.setForeground(new java.awt.Color(255, 0, 0)); 
     jLabel2.setText("20 line limit."); 

     txtResult.setColumns(20); 
     txtResult.setLineWrap(true); 
     txtResult.setRows(5); 
     txtResult.setWrapStyleWord(true); 
     jScrollPane1.setViewportView(txtResult); 

     jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N 
     jLabel3.setText("Information : "); 

     lblCountLine.setText("..."); 

     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(jLabel3) 
         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
         .addComponent(lblCountLine) 
         .addGap(0, 0, Short.MAX_VALUE)) 
        .addGroup(layout.createSequentialGroup() 
         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE) 
          .addGroup(layout.createSequentialGroup() 
           .addComponent(jLabel1) 
           .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
           .addComponent(jLabel2) 
           .addGap(0, 0, Short.MAX_VALUE))) 
         .addContainerGap()))) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(jLabel1) 
        .addComponent(jLabel2)) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addGap(18, 18, 18) 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
        .addComponent(jLabel3) 
        .addComponent(lblCountLine)) 
       .addContainerGap(13, Short.MAX_VALUE)) 
     ); 

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

    /** 
    * @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(JTextAreaCountModified.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(JTextAreaCountModified.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(JTextAreaCountModified.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(JTextAreaCountModified.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 JTextAreaCountModified().setVisible(true); 
      } 
     }); 
    } 
    // Variables declaration - do not modify//GEN-BEGIN:variables 
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JLabel jLabel2; 
    private javax.swing.JLabel jLabel3; 
    private javax.swing.JScrollPane jScrollPane1; 
    private javax.swing.JLabel lblCountLine; 
    private javax.swing.JTextArea txtResult; 
    // End of variables declaration//GEN-END:variables 
} 

이 도와주세요, 당신에게 :) 감사합니다

+1

* 잘못 설명해주세요. 설명해 주시겠습니까? –

+0

죄송합니다, 예를 들어, 행의 수는 10이되어야하지만 계산은 11이되어야합니다. 그리고 문장의 중간에 한 번 더, 항상 새로운 행으로 감지됩니다. 위 코드를 사용해보십시오. 전에 감사드립니다 :) – fanjavaid

+1

테스트 할 시간이 없지만 JTextArea 그것을 할 수있는 getLineCount 메서드가 있습니다. 줄 바꿈 된 줄을 계산하지 않는 경우 다음과 같이 getColumns 메서드를 사용할 수 있습니다. textArea.getText(). length()/textArea.getColumns(). 너무 간단하고 쉽습니다. –

답변

2
  • 이 다른 두 가지 방법이 있습니다,하지만,
  • 라인 내부 루프를 사용

.

import java.awt.BorderLayout; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 
import javax.swing.SwingUtilities; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.Element; 

public class ResizeJTextArea { 

    private JFrame frame = new JFrame(); 
    private JScrollPane scrollPane = new JScrollPane(); 
    private JTextArea textArea = new JTextArea(15, 15); 
    private JButton button = new JButton("change"); 
    private Font newFont = new Font("Courier", Font.PLAIN, 10); 

    public ResizeJTextArea() { 
     textArea.setText("This is just a line of text, " 
       + "This is just a line of text, This is just a line of text, " 
       + "This is just a line of text,\nThis is just a line of text," 
       + "This is just a line of text, This is just a line of text," 
       + "\nThis is just a line of text,This is just a line of text, " 
       + "This is just a line of text,\nThis is just a line of text," 
       + "This is just a line of text, This is just a line of text," 
       + "\nThis is just a line of text, This is just a line of text," 
       + "\nThis is just a line of text,"); 
     textArea.setLineWrap(true); 
     textArea.setWrapStyleWord(true); 
     textArea.setFont(newFont); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       textArea.setFont(textArea.getFont().deriveFont(20f)); 
       frame.pack(); 
      } 
     }); 
     scrollPane.setViewportView(textArea); 
     frame.add(scrollPane); 
     frame.add(button, BorderLayout.SOUTH); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocation(100, 100); 
     frame.pack(); 
     frame.setVisible(true); 
     Element paragraph = textArea.getDocument().getDefaultRootElement(); 
     int contentCount = paragraph.getElementCount(); 
     for (int i = 0; i < contentCount; i++) { 
      Element e = paragraph.getElement(i); 
      int rangeStart = e.getStartOffset(); 
      int rangeEnd = e.getEndOffset(); 
      String line; 
      try { 
       line = textArea.getText(rangeStart, rangeEnd - rangeStart); 
       System.out.println(line); 
      } catch (BadLocationException ex) { 
       Logger.getLogger(ResizeJTextArea.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       ResizeJTextArea fs = new ResizeJTextArea(); 
      } 
     }); 
    } 
} 
1

최고는 textarea.getLineCount()입니다.

그래서 그 최고의 나는

INT countLine = this.getLineCount()

생각;

관련 문제