简体   繁体   中英

How to use JTextArea and Append

Please Help. When I run this GUI the numbers run off the frame. I know I have to use JTextArea and append but where do I put that in my code. can someone explain to me in simple terms and show me? I want to make it scroll vertically and horizontally and when I do add the JTextArea I get this error: error: cannot find symbol panel.setMessage(message);

import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class prime extends JFrame
{
      public static void main(String[] args)
      {
        prime frame = new prime();
      }

private JTextArea panel;
      private JPanel inPanel;
      private JTextField inField;

      public prime()
      {
          final int width  = 500;
          final int height = 500;
          setSize(width, height);
          setTitle("Find Prime Numbers");

          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          panel = new JTextArea(20, 10);
add(new JScrollPane(panel), "Center");

          inPanel = new JPanel();
          inPanel.add(new JLabel("Enter Your Number", SwingConstants.RIGHT));
          inField = new JTextField(20);
          ActionListener inListener = new TextListener();
          inField.addActionListener(inListener);

          inPanel.add(inField);
          add(inPanel, "South");

          setVisible(true);
      }

      private class TextListener implements ActionListener
      {
          public void actionPerformed(ActionEvent event)
          {
              String message = inField.getText();
              inField.setText("");
              panel.setMessage(message);
          }
      }

  class TextPanel extends JPanel
  {
        private String message;
        private Color  backGroundColor;

        public TextPanel()
        {
            message = "";
            backGroundColor = Color.white;
        }

        public TextPanel(String x, Color background)
        {
            message = x;
            backGroundColor = background;
        }

        public void paintComponent(Graphics g)
        {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          int width  = getWidth();
          int height = getHeight();
          setBackground(backGroundColor);
          g2.setColor(Color.black);
          Font x = new Font("TimesNewRoman", Font.BOLD,20);
          g2.setFont(x);
          FontMetrics fm = g2.getFontMetrics(x);

           g2.drawString(message,50, 50);
                    if(!(message.equals("")))
                    g2.drawString(previousPrime(message),50,78);
        }



        public void setMessage(String message) {
                        if (isPrime(Integer.parseInt(message))){
                            this.message = message + " is a prime number.";
                        }
                        else
                            this.message = message + " is not a prime number.";
          repaint();
                    }

                public boolean isPrime(int num){
                    for(int i = 2; i < num; i++){
                        if (num % i == 0)
                            return false;
                    }
                    if(num < 2)
                        return false;

                    return true;
                }

                public String previousPrime(String message){
                    String totalPrimeNum = "";
                    int finalNum = Integer.parseInt(message.substring(0,message.indexOf(" ")));
                    int count = 0;
                    for(int i = 2; i < finalNum; i++){
                        if(isPrime(i)) {
                            totalPrimeNum += " " + i;
                            count++;
                        }

                        if(count == 10) {
                            totalPrimeNum += "\n";
                            count = 0;
                        }
                    }

                    if (isPrime(Integer.parseInt(message.substring(0,message.indexOf(" ")))))
                        totalPrimeNum += " " + finalNum;
                    System.out.println(totalPrimeNum);
                    return totalPrimeNum;
                }}}

Look at what you have and what you want to achieve. You have a method which can verify if a value is a prime or not, but it does not produce any output. You have a JTextArea which allows you to add content to it.

You have a square peg and a round hole. One of these things needs to change. You have control over the setMessage method, but you don't have control over the JTextArea , this would suggest that the setMessage needs to change. While you could pass the JTextArea to the setMessage method, a better solution would be to change the setMessage to return some kind of meaningful value or simply get rid of it in favor of using the isPrime method instead

Take your TestPane and move the functionality used to calculate and test for a prime number to a new class, for example...

public class PrimeCalculator {

    public boolean isPrime(int num) {
        for (int i = 2; i < num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        if (num < 2) {
            return false;
        }

        return true;
    }

    public String previousPrime(String message) {
        StringBuilder totalPrimeNum = new StringBuilder(128);
        int finalNum = Integer.parseInt(message.substring(0, message.indexOf(" ")));
        int count = 0;
        for (int i = 2; i < finalNum; i++) {
            if (isPrime(i)) {
                totalPrimeNum.append(" ").append(i);
                count++;
            }

            if (count == 10) {
                totalPrimeNum.append("\n");
                count = 0;
            }
        }

        if (isPrime(Integer.parseInt(message.substring(0, message.indexOf(" "))))) {
            totalPrimeNum.append(" ").append(finalNum);
        }
        System.out.println(totalPrimeNum);
        return totalPrimeNum.toString();
    }
}

This now makes no assumptions over what you want to do and simply produces output. You can now use these methods and make decisions about how to use the output, for example...

private class TextListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
        PrimeCalculator calc = new PrimeCalculator();
        String message = inField.getText();
        inField.setText("");
        String text = message + " is not a prime number\n";
        try {
            if (calc.isPrime(Integer.parseInt(message))) {
                text = message + " is a prime number\n";
            }
        } catch (NumberFormatException exp) {
            text = message + " is not a valid integer\n";
        }
        panel.append(message);
        panel.setCaretPosition(panel.getDocument().getLength());
    }
}

Sometimes, you need to rethink your design to support what it is you want to achieve.

The process of verifying and calculating the prime numbers should do just that, they should not do anything else (like update the screen), this way you can decouple the code and re-use it in different ways which you didn't original think of (like outputting to a file or the web)

See How to Use Text Areas and How to Use Scroll Panes for more details

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