GUI不随JTextArea一起扩展

时间:2014-09-19 03:33:57

标签: java swing user-interface

我正在尝试在java中创建一个字符计数器,并且我的代码的核心部分正在运行。但是,我的GUI出现问题。当我在我的JTextArea字段中按Enter键时,它会展开它,但它也不会扩展我的GUI。这导致我的文本域垂直扩展到覆盖我的所有按钮和字符数的位置。如何使我的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");
}
}

1 个答案:

答案 0 :(得分:2)

JTextArea放入JScrollPane

有关详细信息,请参阅How to Use Scroll Panes

通过JTextArea的构造函数指定行和列大小,这将允许您在滚动窗格进行干预并添加滚动条之前指定文本区域的所需可查看区域。

有关详细信息,请参阅JTextArea constructor JTextArea(int rows, int columns)

相关问题