如何将标签放入我创建的内部框架中?

How can I get my labels into the inner frame I have created?

我接到了一项任务,我需要创建一个工具来分析文本字段,然后通过单击按钮输出有关所述文本正文的一些统计数据。我似乎已经建立了大部分基本框架,但我正在努力在我的 JPanel 中获取我的两个标签,即 averageLength 和 totalWords,以及在我输入正文的下方获取 JPanel。任何帮助将非常感激。代码在这里:

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

public class TextStatisticsPanel extends JPanel
{

//Field for block of text
private JTextArea userText;
//Button to calculate Statistics
private JButton stats;
//Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;

public TextStatisticsPanel(){

//creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);

//create button
stats = new JButton("Update Text Statistics");
//Listener for button
stats.addActionListener(new ButtonListener());

//Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));

statPanel.setOpaque(false);



//Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension (350, 400));
scroller.setBorder(BorderFactory.createTitledBorder  ("Enter the text below"));
//Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
totalWords = new JLabel("The total number of words: ");

//add GUI
add(statPanel);
add(scroller);
add(averageLength);
add(totalWords);
setBackground(new java.awt.Color(202, 225, 255));
setPreferredSize(new Dimension (400, 600));
add(stats);

}

// When button is pressed do :
private class ButtonListener implements ActionListener{

public void actionPerformed(ActionEvent event)
{

    if (event.getSource() == stats){
        //Call statUpdate Method
        statUpdate();

    }
}

// Create statUpdate Method
private void statUpdate() 
{
    //Grab text user inputed
    String text = userText.getText();
    //Split the text by each space to find the number of words
    String[] words = text.split(" ");

    //Calculation for average
    float average = (text.length() - words.length)/words.length;
    //
    averageLength.setText(String.valueOf(average));
    totalWords.setText(String.valueOf(words.length));

    System.out.println(averageLength);
    System.out.println(totalWords);



}
}


}

好的,可以尝试使用 MCVE,这是相关代码的一部分,但是我仍然无法找出问题的根源。

我的第二个面板的代码是:

JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));

statPanel.setOpaque(false);

所以根据我的理解,这是我在我的应用程序中创建第二个面板。然而,问题是它被放置在一个看似随机的位置,并且没有环绕我希望位于该面板内的两个标签,我不确定如何解决这个问题。

主要class代码:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JFrame;

public class TextStatistics {

public static void main(String[] args) {
    JFrame frame = new JFrame("Text Statistics Tool");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    TextStatisticsPanel panel = new TextStatisticsPanel();
    frame.getContentPane().add(panel);

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

}

提供一个可视化示例来展示我认为是问题所在以及我遇到的问题

Problem Visualised

这是我整理的 GUI。

这些是我所做的主要更改。

  1. 我将 JFrame 代码放在一个 Runnable 中,这样我就可以通过调用 SwingUtilities invokeLater 方法来启动 Swing 应用程序。 invokeLater 方法确保在 Event Dispatch thread 上创建和更新 Swing 组件。 Oracle 和我要求每个人都在事件调度线程上启动他们的 Swing 应用程序。

  2. 我在您的 TextStatisticsPanel class 中定义了几个新的 JPanel,并使用了两个 Swing layout managers、BorderLayout 和 BoxLayout。研究上一句中的link。通过学习,我的意思是至少花两到三周的时间每天 8 小时来吸收 Swing 布局管理器的所有来龙去脉。

  3. 我添加了 JTextFields 来保存计算值。这就是 JTextFields 的用途。

  4. 我修复了你的 statUpdate 方法中的整数除法。

这是代码。我将所有内容放在一个文件中,这样上传起来会更容易。您应该将 classes 放在单独的文件中。

package com.ggl.testing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class TextStatistics {

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Text Statistics Tool");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                TextStatisticsPanel panel = new TextStatistics().new TextStatisticsPanel();
                frame.add(panel);

                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    public class TextStatisticsPanel extends JPanel {
        private static final long serialVersionUID = 9049744714586970558L;
        // Field for block of text
        private JTextArea userText;
        // Button to calculate Statistics
        private JButton stats;
        // Label for where statistics are shown and statistics
        private JLabel averageLength, totalWords;
        private JTextField averageLengthField, totalWordsField;

        public TextStatisticsPanel() {

            // creating the area for user text with wrapped text
            userText = new JTextArea();
            userText.setWrapStyleWord(true);
            userText.setLineWrap(true);

            // create button
            stats = new JButton("Update Text Statistics");
            stats.setAlignmentX(JButton.CENTER_ALIGNMENT);
            // Listener for button
            stats.addActionListener(new ButtonListener());

            // Tilted border creater
            JPanel statPanel = new JPanel();
            statPanel.setBorder(BorderFactory
                    .createTitledBorder("Text Statistics"));
            statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.PAGE_AXIS));
            statPanel.setOpaque(false);

            // Create Scroller
            JScrollPane scroller = new JScrollPane(userText);
            scroller.setPreferredSize(new Dimension(350, 400));
            scroller.setBorder(BorderFactory
                    .createTitledBorder("Enter the text below"));

            // Add the statistics labels
            averageLength = new JLabel("The average length of the words: ");
            averageLength.setOpaque(false);

            averageLengthField = new JTextField(10);
            averageLengthField.setEditable(false);
            averageLengthField.setOpaque(false);

            totalWords = new JLabel("The total number of words: ");
            totalWords.setOpaque(false);

            totalWordsField = new JTextField(10);
            totalWordsField.setEditable(false);
            totalWordsField.setOpaque(false);

            // add GUI
            setLayout(new BorderLayout());

            statPanel.add(stats);
            statPanel.add(Box.createVerticalStrut(10));

            JPanel lengthPanel = new JPanel();
            lengthPanel.setOpaque(false);
            lengthPanel.add(averageLength);
            lengthPanel.add(averageLengthField);
            statPanel.add(lengthPanel);
            statPanel.add(Box.createVerticalStrut(10));

            JPanel wordsPanel = new JPanel();
            wordsPanel.setOpaque(false);
            wordsPanel.add(totalWords);
            wordsPanel.add(totalWordsField);
            statPanel.add(wordsPanel);

            add(statPanel, BorderLayout.SOUTH);
            add(scroller, BorderLayout.CENTER);
            setBackground(new java.awt.Color(202, 225, 255));
        }

        // When button is pressed do :
        private class ButtonListener implements ActionListener {

            public void actionPerformed(ActionEvent event) {

                if (event.getSource() == stats) {
                    // Call statUpdate Method
                    statUpdate();
                }
            }

            // Create statUpdate Method
            private void statUpdate() {
                // Grab text user inputed
                String text = userText.getText();
                // Split the text by each space to find the number of words
                String[] words = text.split(" ");

                // Calculation for average
                float average = ((float) text.length() - words.length)
                        / words.length;
                //
                averageLengthField.setText(String.valueOf(average));
                totalWordsField.setText(String.valueOf(words.length));
            }
        }
    }

}