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

时间:2016-03-08 00:31:50

标签: java swing jpanel jbutton jtextarea

我已经获得了一项任务,我需要创建一个分析文本字段的工具,然后通过单击按钮输出关于所述文本主体的一些统计信息。我似乎已经拥有了大部分的基本框架,但我正在努力获得我的两个标签,即我的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);

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

主类代码:

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

1 个答案:

答案 0 :(得分:1)

这是我放在一起的GUI。

Test Statistics Tool

这些是我所做的重大改变。

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

  2. 我在TextStatisticsPanel类中定义了几个新的JPanel,并使用了两个Swing layout managers,BorderLayout和BoxLayout。研究上一句中的链接。通过研究,我的意思是花费至少两到三周的8小时工作日来吸收Swing布局经理的所有细节。

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

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

  5. 这是代码。我将所有内容放在一个文件中,以便上传更容易。您应该将这些类放在单独的文件中。

    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));
                }
            }
        }
    
    }