简体   繁体   中英

Why is my JTextArea inside JScrollPane not scrolling

I have been searching all over the web for the answer to why is my textarea not scrolling in a JScrollPane? The JScrollPane knob adjusts its size based on the amount of lines in the textarea. It looks like its working but I cant scroll it. Any suggestions would be greatly appreciated!

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.text.DecimalFormat;
//import java.util.regex.Pattern;


import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
//import javax.swing.SwingWorker;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;

public class Output_Window extends JFrame implements Runnable {

    public boolean keepRefreshing = true;

    private JTextArea chosen_settings;
    public JTextArea package_status;
    private JTextArea program_status;
    private JTextArea efficiency;
    private JTextArea emptyPackages;
    private JTextArea skipped_cases;

    private JTextArea package_status_title;
    private JTextArea program_status_title;
    private JTextArea efficiency_title;
    private JTextArea chosen_settings_title;
    private JTextArea emptyPackagesTitle;
    private JTextArea skipped_cases_title;

    private JScrollPane emptyPackageScroll;
    private JScrollPane skipped_cases_scroll;

    private Font titleFont = new Font("Arial", Font.BOLD, 14);

//  private SwingWorker<Boolean, Integer> worker = null;

    private JPanel panel = new JPanel(new GridBagLayout());

    private long startTime = System.nanoTime();
    private long previousTime = System.nanoTime();
    private long currentTime = System.nanoTime();
    private long elapsedTime;
    private long totalTime = 0;

    private long packageStart;
    private long packageElapsed;
    private static boolean start = false;

    private long packageAverageTime = 0;
    private long totalPackageTime = 0;
    private int numPackages = 0;

    private double totalEmpty = 0;
    private double emptyPercentage = 0;
    private boolean first = true;

    private int skippedCases = 0;

//  private long estimatedTimeRemaining = 0;
    private static double totalPackages = 0;

    private int sec_TT = 0;
    private int min_TT = 0;
    private int hour_TT = 0;
    private int day_TT = 0;

    private int sec_PT = 0;
    private int min_PT = 0;
    private int hour_PT = 0;
    private int day_PT = 0;

    private int sec_PAT = 0;
    private int min_PAT = 0;
    private int hour_PAT = 0;
    private int day_PAT = 0;

//  private Pattern pattern;
    private String text = "";
    private String text2 = "";

    Thread windowThread;

    /**
     * Window for displaying output
     */

    private static final long serialVersionUID = 2462095488215034654L;

    public Output_Window() {
        setPreferredSize(new Dimension(1200, 900));  
//      setSize(new Dimension(1200, 900));  
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        GridBagConstraints c = new GridBagConstraints();
        setResizable(false);
        setTitle("Athena Test Automation Tool");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

           //center it on the screen 


        String dir = System.getProperty("user.dir");
        ImageIcon icon = new ImageIcon(dir + "\\AthenaIcon.png");
        setIconImage(icon.getImage());

        init();

        c.weighty = 1;
        c.weightx = 1;
        c.insets = new Insets(10, 10, 10, 10);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.NORTHWEST;
        panel.add(chosen_settings_title, c);

        c.gridx = 0;
        c.gridy = 1;

        panel.add(chosen_settings, c);

        c.gridx = 0;
        c.gridwidth = 1;
        c.gridy = 2;
        panel.add(program_status_title, c);

        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 1;
//      c.fill = GridBagConstraints.NONE;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(program_status, c);


        c.gridx = 0;
        c.gridy = 4;
        c.gridwidth = 1;
        panel.add(package_status_title, c);

        c.gridx = 0;
        c.gridy = 5;
        c.gridwidth = 1;
        panel.add(package_status, c);

        c.gridx = 1;
        c.gridy = 1;
        c.gridwidth = 1;
        c.anchor = GridBagConstraints.NORTHEAST;
        panel.add(efficiency, c);

        c.gridx = 1;
        c.gridy = 0;
        panel.add(efficiency_title, c);

        c.gridx = 1;
        c.gridy = 4;
        panel.add(emptyPackagesTitle, c);

        c.gridx = 1;
        c.gridy = 5;
        panel.add(emptyPackageScroll, c);

        c.gridx = 1;
        c.gridy = 2;
        panel.add(skipped_cases_title, c);

        c.gridx = 1;
        c.gridy = 3;
        panel.add(skipped_cases_scroll, c);

        panel.setBackground(Color.WHITE);

        add(panel);
        pack();
        setVisible(true);
        setLocationRelativeTo(null);

        //panel.update(panel.getGraphics());

        windowThread = new Thread(this);
        windowThread.setPriority(Thread.MAX_PRIORITY);
        windowThread.start();
    }
    public void init() {

        chosen_settings = new JTextArea();
        chosen_settings.setEditable(false);
        chosen_settings.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        chosen_settings.setMargin(new Insets(0, 10, 0, 0)); 

        program_status = new JTextArea();
        program_status.setEditable(false);
        program_status.setLineWrap(true);
        program_status.setWrapStyleWord(true);
        program_status.setPreferredSize(new Dimension(700, 280));
        program_status.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        package_status = new JTextArea();
        package_status.setEditable(false);
        package_status.setLineWrap(true);
        package_status.setWrapStyleWord(true);
        package_status.setPreferredSize(new Dimension(700, 290));
        package_status.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        efficiency = new JTextArea();
        efficiency.setEditable(false);
        efficiency.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        //ignore this textarea
        skipped_cases = new JTextArea();
        skipped_cases.setEditable(false);
        skipped_cases.setLineWrap(true);
        skipped_cases.setWrapStyleWord(true);
        skipped_cases.setPreferredSize(new Dimension(50, 280));

        emptyPackages = new JTextArea(10,10);
        emptyPackages.setEditable(false);
        emptyPackages.setLineWrap(true);
        emptyPackages.setWrapStyleWord(true);
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");

        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");

        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");

        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");

        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");
        emptyPackages.append("TESTING\n");

//      emptyPackages.setPreferredSize(new Dimension(50, 290));
//      emptyPackages.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

        DefaultCaret caret = (DefaultCaret) emptyPackages.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        emptyPackagesTitle = new JTextArea();
        emptyPackagesTitle.setEditable(false);

        package_status_title = new JTextArea();
        package_status_title.setEditable(false);

        program_status_title = new JTextArea();
        program_status_title.setEditable(false);

        chosen_settings_title = new JTextArea();
        chosen_settings_title.setEditable(false);

        efficiency_title = new JTextArea();
        efficiency_title.setEditable(false);

        skipped_cases_title = new JTextArea();
        skipped_cases_title.setEditable(false);

        chosen_settings_title.setFont(titleFont);
        chosen_settings_title.append("Chosen Locations and Environment:");
        chosen_settings.append("Chosen Target Network Location: " + Athena_Test_Automation_Framework.targetNetworkDirectory);
        chosen_settings.append("\nChosen Application Server: "+ Athena_Test_Automation_Framework.chosenAthenaApplicationServer);
        chosen_settings.append("\nChosen DB Server: " + Athena_Test_Automation_Framework.chosenAthenaDatabaseServer);
        chosen_settings.append("\nType of Environment: " + Athena_Test_Automation_Framework.chosenAthenaEnvironment);
        if(Athena_Test_Automation_Framework.chosenNetworkStorageLocation.length() != 0){
            chosen_settings.append("\nNetwork Storage Location: " + Athena_Test_Automation_Framework.chosenNetworkStorageLocation);
        }else{
            chosen_settings.append("\nNetwork Storage Location: N/A");
        }

        emptyPackagesTitle.setFont(titleFont);
        emptyPackagesTitle.append("Empty Distribution Packages:   (Total: 0/0  --  %0.0)");


        program_status_title.setFont(titleFont);
        program_status_title.append("Program Status:");

        package_status_title.setFont(titleFont);
        package_status_title.append("Package Status:      Processing Package... N/A");

        skipped_cases_title.setFont(titleFont);
        skipped_cases_title.append("Skipped TestCases: (Total: 0)");

        efficiency_title.setFont(titleFont);
        efficiency_title.append("Time Status:");
        efficiency.append("Total Time: 0:0:0:0");
        efficiency.append("\nCurrent Package Time: 0:0:0:0");
        efficiency.append("\nAverage Package Time: 0:0:0:0");
        //efficiency.append("\nEstimated Time Remaining: 0:0:0:0");
        efficiency.append("\n\n");

        emptyPackageScroll = new JScrollPane(emptyPackages);
        emptyPackageScroll.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        emptyPackageScroll.setSize(new Dimension(50,290));

        skipped_cases_scroll = new JScrollPane(skipped_cases);
        skipped_cases_scroll.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
        skipped_cases_scroll.setPreferredSize(new Dimension(50,280));

    }

    /**
     * Updates text of JTextArea
     * 
     * @param text
     * @param addBreak
     *            TODO
     */

    public void updateWindow(String text, boolean addBreak, int place) {
        String textToAppend = text;

        if (addBreak) {
            textToAppend = textToAppend + "\n";
        }
        if (place == 0) {
            package_status.append(textToAppend);
        } else if(place == 1) {
            program_status.append(textToAppend);
        }else if(place == 2) {
            skipped_cases.append(textToAppend);
            replaceLineInWindow("Total: " + (skippedCases++), "Total: " + skippedCases, 2);
        }else if(place == 5){
            emptyPackages.append(textToAppend);
            double oldPercentage = emptyPercentage;
            DecimalFormat twoDForm = new DecimalFormat("##.##");
            emptyPercentage = Double.valueOf(twoDForm.format(((++totalEmpty)/totalPackages)*100));
            if(first){
                first = false;
                replaceLineInWindow("Total: 0/0  --  %" + oldPercentage, "Total: " + (int)(totalEmpty) + "  --  %" + emptyPercentage, 5);
            }else{
                replaceLineInWindow("Total: " + (int)(totalEmpty-1) + "  --  %" + oldPercentage, "Total: " + (int)(totalEmpty) + "  --  %" + emptyPercentage, 5);
            }
        }
    }
    /**
     * Replaces line of text in JTextArea
     * 
     * @param text
     * @param text2
     */

    public void replaceLineInWindow(String text, String text2, int place) {

        if (place == 0) {
            String textFromArea = package_status.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            package_status.setText(textFromArea2);
        } else if(place == 1) {
            String textFromArea = program_status.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            program_status.setText(textFromArea2);
        } else if(place == 2){
            String textFromArea = skipped_cases_title.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            skipped_cases_title.setText(textFromArea2);
        } else if(place == 3){
            String textFromArea = chosen_settings.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            chosen_settings.setText(textFromArea2);
        } else if(place == 4){
            String textFromArea = package_status_title.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            package_status_title.setText(textFromArea2);
        } else if(place == 5){
            String textFromArea = emptyPackagesTitle.getText();
            String textFromArea2 = textFromArea.replace(text, text2);
            emptyPackagesTitle.setText(textFromArea2);
        }

    }

    public void restartTextArea(int textarea) {
        if (textarea == 0) {
            package_status.setText("");
        } else {
            program_status.setText("");
        }
    }

    /**
     * Updates text of JTextArea
     * 
     * @param text
     */

    public void updateEfficiency() {
        //starts a new package clock 0:0:0:0
        String textFromArea2;

        currentTime = System.nanoTime();
        elapsedTime = (currentTime - previousTime)/1000000000;

        if(start){

            start = false;
            packageStart = System.nanoTime();
            totalPackageTime += packageElapsed;
            if(numPackages != 0){
                packageAverageTime = totalPackageTime / numPackages;
            }
            if(numPackages < totalPackages){
                numPackages++;
            }


            if(numPackages == 1){
                replaceLineInWindow("N/A", numPackages + "/" + (int)totalPackages, 4);
            }else{
                replaceLineInWindow((numPackages-1) + "/", numPackages + "/", 4);
            }

            min_PAT = 0;
            hour_PAT = 0;
            day_PAT = 0;
            min_PT = 0;
            hour_PT = 0;
            day_PT = 0;

            sec_PAT = (int) packageAverageTime;
            while (sec_PAT > 60) {
                sec_PAT -= 60;
                min_PAT++;
                if (min_PAT > 60) {
                    hour_PAT++;
                    min_PAT = 0;
                } else if (hour_PAT > 24) {
                    day_PAT++;
                    hour_PAT = 0;
                }
            }
        }

        if(elapsedTime >= 1){
            previousTime = currentTime;
            totalTime = (currentTime - startTime) / 1000000000;
            String textFromArea = efficiency.getText();
            sec_TT = (int) totalTime % 60;
            if (sec_TT == 0) {
                min_TT++;
            } else if (min_TT % 60 == 0 && min_TT != 0) {
                hour_TT++;
                min_TT = 0;
            } else if (hour_TT % 24 == 0 && hour_TT != 0) {
                day_TT++;
                hour_TT = 0;
            }

            if(numPackages != 0){
                packageElapsed = (currentTime - packageStart) / 1000000000;
                sec_PT = (int) packageElapsed % 60;
                if (sec_PT == 0 && packageElapsed != 0) {
                    min_PT++;
                } else if (min_PT % 60 == 0 && min_PT != 0) {
                    hour_PT++;
                    min_PT = 0;
                } else if (hour_PT % 24 == 0 && hour_PT != 0) {
                    day_PT++;
                    hour_PT = 0;
                }
            }

            textFromArea2 = textFromArea.replaceAll("Total Time: [0-9:]+", "Total Time: " + day_TT + ":"    + hour_TT + ":" + min_TT + ":" + sec_TT);
            textFromArea2 = textFromArea2.replaceAll("Current Package Time: [0-9:]+", "Current Package Time: " + day_PT + ":" + hour_PT + ":" + min_PT + ":" + sec_PT);
            textFromArea2 = textFromArea2.replaceAll("Average Package Time: [0-9:]+", "Average Package Time: " + day_PAT + ":" + hour_PAT + ":" + min_PAT + ":" + sec_PAT); 
            efficiency.setText(textFromArea2);  
        }
    }
    /**
     * Continuously updates text of JTextArea
     * call whenever updateOutput() or replaceLineInWindow() is called
     * 
     * @param text
     */
    public void updateDots(){
        text = package_status_title.getText();
        if(text.contains("Processing Package   ")){
            text2 = text.replace("Processing Package   ", "Processing Package.  ");
        }else if(text.contains("Processing Package.  ")){
            text2 = text.replace("Processing Package.  ", "Processing Package.. ");
        }else if(text.contains("Processing Package.. ")){
            text2 = text.replace("Processing Package.. ", "Processing Package...");
        }else if(text.contains("Processing Package...")){
            text2 = text.replace("Processing Package...", "Processing Package   ");
        }else{
            text2 = text;
        }
        package_status_title.setText(text2);

        try {
            String lineText;
            String lineText2;
            int line = package_status.getLineCount() - 2;
            if(line == 10){
                line = 8;
            }
            int lineStart = package_status.getLineStartOffset(line);
            int lineEnd = package_status.getLineEndOffset(line);
            lineText = package_status.getText(lineStart, lineEnd - lineStart);
            if(lineText.contains(".  ")){
                lineText2 = lineText.replace(".  ", ".. "); 
                package_status.replaceRange(lineText2, lineStart, lineEnd);
            }else if(lineText.contains(".. ")){
                lineText2 = lineText.replace(".. ", "...");
                package_status.replaceRange(lineText2, lineStart, lineEnd);
            }else if(lineText.contains("...")){
                lineText2 = lineText.replace("...", ".  ");
                package_status.replaceRange(lineText2, lineStart, lineEnd);
            }

        } catch (BadLocationException e) {
            e.printStackTrace();
        }

    }

    public static void setPackageStart() {
        start = true;
    }

    public static void setTotalPackages(int num) {
        totalPackages = num;
    }

    public void run() {

        long previousTime = System.nanoTime();
        long currentTime = System.nanoTime();
        long elapsedTime = (currentTime - previousTime) /1000000000;

        while (keepRefreshing) {
            currentTime = System.nanoTime();
            elapsedTime = (currentTime - previousTime) /1000000000;
//          updateEfficiency();                 
            if(elapsedTime >= 1){
                previousTime = currentTime;
//              if(numPackages != 0){
//                  updateDots();
//              }
                if(panel == null){
                    keepRefreshing = false;
                }else{
                    panel.revalidate();
                    panel.update(panel.getGraphics());
                    panel.repaint();


                }

            }

        }

    }
}

You've preset the preferredSize of the text areas, this means that, form the perspective the JScrollPane , they will never by anything other then the preferredSize you've specified.

Instead, set the rows and columns properties of the JTextArea s and allow the component itself to continue calculating its own preferredSize based on its needs

Don't do...

panel.update(panel.getGraphics());

In Swing, you don't control the paint process and you should never have a need to call update or paint directly and should never rely on getGraphics

Also, as a general rule, Swing is not Thread safe, this means that you should never create or modify any UI component from outside the context of the Event Dispatching Thread. You might consider using a SwingWorker instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM