2014-09-19 52 views
0

我想在java中创建一个字符计数器,并且我的代码工作中有我的核心部分。但是,我的GUI有问题。当我在我的JTextArea字段中按Enter时,它将扩展它,但它不会扩展我的GUI。这导致我的textfield垂直扩展到它覆盖我所有的按钮和字符数的地方。我如何使我的GUI与我的JTextArea一起展开?谢谢 :)。GUI不能与JTextArea一起扩展

注意:对图片的超链接道歉,我对这个网站仍然陌生,所以我没有足够的信誉来上传图片。

这是它的外观,在我的文本区域一行文本(与GUI效果很好)

enter image description here

这是它的外观与文本的多行(或只是少数在我的文字区 “进入” 按键)(不带GUI很好地工作)

enter image description here

我的代码:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 

public class characterCounterTwov4{ 
    //creates a new Jframe to put our frame objets in 
    JFrame frame = new JFrame(); 

    //creates a text field JTextArea frame object 
    JTextArea txtField = new JTextArea(); 

    //stores the string of the the jtextfield into a variable text 
    String text = txtField.getText(); 

    //creates a text field that is uneditable with the word "characters" 
    String charString = "Characters: "; 
    JTextField charField = new JTextField(charString, 25); 

    //string that will be used in a text field to display the # of chars 
    String charCount = Integer.toString(text.length()); 

    //Text field that displays charCount 
    JTextField charFieldTwo = new JTextField(charCount, 10);  

public characterCounterTwov4(){ 

    //disables the charField from being editable. 
    charField.setEditable(false); 

    //calculate button 
    JButton calcButton = new JButton("Calculate"); 
    calcButton.addActionListener(new ActionListener(){ 
     public void actionPerformed(java.awt.event.ActionEvent event) 
     { 
      System.out.println("button pressed"); 

      //stores the string of the the jtextfield into a variable text 
      text = txtField.getText(); 

      //string that will be used in a text field to display the # of chars 
      String charCount = Integer.toString(text.length()); 

      //Text field that displays charCount 
      charFieldTwo.setText(charCount); 
     } 
    }); 

    /*******************/ 
    /* Frame Setup */ 
    /*******************/ 

    //sets the layout of the frame 
    frame.setLayout(new BorderLayout()); 

    //add's elements to the frame 
    frame.add(txtField, BorderLayout.NORTH); 
    frame.add(charField, BorderLayout.CENTER); 
    frame.add(charFieldTwo, BorderLayout.SOUTH); 
    frame.add(calcButton, BorderLayout.EAST); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    frame.pack(); 
    frame.setVisible(true); 
} 

public static void main(String[] args){ 
    new characterCounterTwov4(); 
    System.out.println("End of program. Should not get here"); 
} 
} 

回答