为什么我的文字不会打印到我的JTextArea?

时间:2013-02-26 20:47:25

标签: java swing variables jtextarea

我正在调用一个返回字符串的方法(来自网页的已编辑文本),我想将该字符串打印到我的JTextArea上。我知道我发送到我的JTextArea的字符串是正确的,因为它将正确打印到命令行,但不会打印到JTextArea。在将它添加到TextArea时,它一定是我做错了。任何帮助将不胜感激。

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

public class BrowserPanel extends JPanel {

private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;



public BrowserPanel(JTextField myTextField, BrowserPageReader model,
        BrowserFrame frame)
{
    myFrame = frame;
    myModel = model;
    textField = myTextField;
    textField.addActionListener(new InputHandler());

    /*JScrollPane areaScrollPane = new JScrollPane(textArea);
    areaScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    areaScrollPane.setPreferredSize(new Dimension(250,250));*/
    textArea = new JTextArea(20,40);
    textArea.setEditable(false);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    JScrollPane scroll = new JScrollPane(textArea);

    add(scroll);
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

}
private class InputHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
         urlText = textField.getText();  
         //textArea.append(urlText);

         myModel.setURL(urlText);
         pageTitle = myModel.getTitle();
         myFrame.setTitle(pageTitle);
        pageBody = myModel.getBody();
        textArea.setText(pageBody); 
         System.out.println(pageBody); //This prints out exactly what Im wanting
                                       //  Its just a test             
         textArea.repaint();
    }
}
}

我猜我可能需要在paintComponent中添加一些内容,因为我的TextArea位于附加到Panel的scrollPane中。我真的不知道出了什么问题。如果我放textArea.setText("blah");它会做它应该做的事情。我发送的变量是一个非常大的字符串,它是一个完整的网页。这可能是问题吗?使用代码,textArea保持空白,我希望它显示正确打印到命令行。帮助!

编辑这是我的其余代码

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

public class BrowserFrame extends JFrame{

public BrowserFrame()
{
    BrowserPageReader myModel = new BrowserPageReader();
    setTitle("My Browser");
    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension screenSize =kit.getScreenSize();
    setSize(screenSize.width/2,screenSize.height-500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    JTextField textField = new JTextField(20);
    BrowserPanel myPanel = new BrowserPanel(textField,myModel,this);
    contentPane.add(myPanel);
    contentPane.add(textField,BorderLayout.PAGE_START);
    setVisible(true);

}
}





 import javax.swing.*;
import java.io.*;
import java.net.*;

public class BrowserPageReader {

private URL myURL;
//private String webURL;
private String totalWebContent;
private String htmlString;
private String contentToPrint = " ";
private String urlPath;
private String urlHost;
private String pageTitle;
private String pageBody;
private String formattedBody;

public void setURL (String webURL)
{
   try{
        myURL = new URL(webURL);
        urlPath = myURL.getPath();
        urlHost = myURL.getHost();

    }
    catch(MalformedURLException e)
    {
        JOptionPane.showMessageDialog(null,"URL is incorrectly formatted");
    }
}

public void retrieveContent()
{
    try{
        Socket socket = new Socket(urlHost,80);
        PrintWriter out = new PrintWriter(socket.getOutputStream());
        BufferedReader in = new
                BufferedReader(new InputStreamReader(socket.getInputStream()));
        out.print("GET " + urlPath + " HTTP/1.1\n");
        out.print("Host: "+ urlHost + "\n");
        out.print("\n");
        out.flush();
        while((totalWebContent = in.readLine()) != null)
        {
            //System.out.println(totalWebContent);
            htmlString = htmlString + totalWebContent;
            //System.out.println(contentToPrint);
        }
        //System.out.println("htmlString\n" + htmlString);
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

public String getTitle()
{
       retrieveContent();
      //System.out.println(htmlString);
      pageTitle = htmlString.substring(htmlString.indexOf("<title>")+ 7,
              htmlString.indexOf("</title>")); 
      return pageTitle;
}

public String getBody()
{
    String toDelete;
    String edited;
    retrieveContent();

    pageBody = htmlString.substring(htmlString.indexOf("<body")+5,
            htmlString.indexOf("</body>"));
    toDelete = pageBody.substring(0,pageBody.indexOf('<'));
    edited = pageBody.replace(toDelete,"");
    pageBody = edited
    formattedBody = pageBody.replaceAll("<[^>]*>", "");
    //System.out.println(formattedBody);
    return formattedBody;

}

2 个答案:

答案 0 :(得分:4)

由于您发布的代码不是SSCCE,这是一个我们可以编译,运行和测试的小型自包含程序,我认为我们不会在没有猜测的情况下回答这个问题。所以我的猜测:你正在添加文本的JTextArea与JFrame中显示的不一样。

为了能够自信地回答这个问题,我们需要SSCCE,特别是代码显示您在上面创建类的位置以及将其添加到显示的JFrame的位置。

例如,如果我使用模拟BrowserFrame JFrame和BrowserPageReader模型类创建一个小SSCCE,一切似乎都可以正常工作:

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

public class BrowserPanel extends JPanel {

   private JTextField textField;
   private String urlText;
   private JTextArea textArea;
   private BrowserPageReader myModel;
   private String pageContent;
   private BrowserFrame myFrame;
   private String pageTitle;
   private String pageBody;

   public BrowserPanel(JTextField myTextField, BrowserPageReader model,
         BrowserFrame frame) {
      myFrame = frame;
      myModel = model;
      textField = myTextField;
      textField.addActionListener(new InputHandler());

      /*
       * JScrollPane areaScrollPane = new JScrollPane(textArea);
       * areaScrollPane.setVerticalScrollBarPolicy(
       * JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
       * 
       * areaScrollPane.setPreferredSize(new Dimension(250,250));
       */
      textArea = new JTextArea(20, 40);
      textArea.setEditable(false);
      textArea.setWrapStyleWord(true);
      textArea.setLineWrap(true);
      JScrollPane scroll = new JScrollPane(textArea);

      add(scroll);
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);

   }

   private class InputHandler implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         urlText = textField.getText();
         // textArea.append(urlText);

         myModel.setURL(urlText);
         pageTitle = myModel.getTitle();
         myFrame.setTitle(pageTitle);
         pageBody = myModel.getBody();
         textArea.setText(pageBody);
         System.out.println(pageBody); // This prints out exactly what Im
                                       // wanting
                                       // Its just a test
         textArea.repaint();
      }
   }

   private static void createAndShowGui() {
      BrowserFrame frame = new BrowserFrame();
      JTextField textField = new JTextField(10);
      BrowserPageReader myModel = new BrowserPageReader();
      BrowserPanel mainPanel = new BrowserPanel(textField, myModel, frame);

      frame.add(textField, BorderLayout.NORTH);
      frame.add(mainPanel, BorderLayout.CENTER);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class BrowserFrame extends JFrame {

}

class BrowserPageReader {

   public void setURL(String urlText) {
      // does nothing for now. for testing purposes.
   }

   public String getBody() {
      return "body"; // for testing purposes
   }

   public String getTitle() {
      return "title"; // for testing purposes
   }

}

由于我的代码“有效”,它证明错误不在您上面发布的代码中。

您的工作是发布正常工作的类似代码,而不是演示您的问题。我猜你如果你努力创建这样一个程序,你就会发现错误,你会看到你可能有两个BrowserPanel,一个显示,一个没有显示但是正在获取它的文本在处理程序中进行了更改,您将能够在没有我们直接帮助的情况下解决您的错误。


修改
SwingWorker,例如

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;

public class BrowserPanel extends JPanel {

   private JTextField textField;
   private String urlText;
   private JTextArea textArea;
   private BrowserPageReader myModel;
   private String pageContent;
   private BrowserFrame myFrame;
   private String pageTitle;
   private String pageBody;

   public BrowserPanel(JTextField myTextField, BrowserPageReader model,
         BrowserFrame frame) {
      myFrame = frame;
      myModel = model;
      textField = myTextField;
      textField.addActionListener(new InputHandler());

      /*
       * JScrollPane areaScrollPane = new JScrollPane(textArea);
       * areaScrollPane.setVerticalScrollBarPolicy(
       * JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
       * 
       * areaScrollPane.setPreferredSize(new Dimension(250,250));
       */
      textArea = new JTextArea(20, 40);
      textArea.setEditable(false);
      textArea.setWrapStyleWord(true);
      textArea.setLineWrap(true);
      JScrollPane scroll = new JScrollPane(textArea);

      add(scroll);
   }

   private class InputHandler implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         urlText = textField.getText();
         // textArea.append(urlText);
         System.out.println(urlText);

         myModel.setURL(urlText);

         myModel.getContent(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
               if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                  pageTitle = myModel.getTitle();
                  myFrame.setTitle(pageTitle);
                  pageBody = myModel.getBody();
                  textArea.setText(pageBody);
                  System.out.println(pageBody);
               }
            }
         });
         // textArea.repaint();
      }
   }

   private static void createAndShowGui() {
      BrowserFrame frame = new BrowserFrame();
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class BrowserFrame extends JFrame {

   public BrowserFrame() {
      BrowserPageReader myModel = new BrowserPageReader();
      setTitle("My Browser");
      Toolkit kit = Toolkit.getDefaultToolkit();
      Dimension screenSize = kit.getScreenSize();
      setSize(screenSize.width / 2, screenSize.height - 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container contentPane = getContentPane();
      JTextField textField = new JTextField(20);
      BrowserPanel myPanel = new BrowserPanel(textField, myModel, this);
      contentPane.add(myPanel);
      contentPane.add(textField, BorderLayout.PAGE_START);
      setVisible(true);

   }
}

class BrowserPageReader {

   private URL myURL;
   // private String webURL;
   private String totalWebContent;
   private String htmlString;
   private String contentToPrint = " ";
   private String urlPath;
   private String urlHost;
   private String pageTitle;
   private String pageBody;
   private String formattedBody;

   public void setURL(String webURL) {
      try {
         myURL = new URL(webURL);
         urlPath = myURL.getPath();
         urlHost = myURL.getHost();

      } catch (MalformedURLException e) {
         JOptionPane.showMessageDialog(null, "URL is incorrectly formatted");
      }
   }

   public void getContent(PropertyChangeListener listener) {
      RetrieveWorker worker = new RetrieveWorker();
      worker.addPropertyChangeListener(listener);
      worker.execute();
   }

   private void retrieveContent() {
      try {
         Socket socket = new Socket(urlHost, 80);
         PrintWriter out = new PrintWriter(socket.getOutputStream());
         BufferedReader in = new BufferedReader(new InputStreamReader(
               socket.getInputStream()));
         out.print("GET " + urlPath + " HTTP/1.1\n");
         out.print("Host: " + urlHost + "\n");
         out.print("\n");
         out.flush();
         while ((totalWebContent = in.readLine()) != null) {
            // System.out.println(totalWebContent);
            htmlString = htmlString + totalWebContent;
            // System.out.println(contentToPrint);
         }
         // System.out.println("htmlString\n" + htmlString);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public String getTitle() {
      // !! retrieveContent();
      System.out.println(htmlString);
      pageTitle = htmlString.substring(htmlString.indexOf("<title>") + 7,
            htmlString.indexOf("</title>"));
      return pageTitle;
   }

   public String getBody() {
      String toDelete;
      String edited;
      // !! retrieveContent();

      pageBody = htmlString.substring(htmlString.indexOf("<body") + 5,
            htmlString.indexOf("</body>"));
      toDelete = pageBody.substring(0, pageBody.indexOf('<'));
      edited = pageBody.replace(toDelete, "");
      pageBody = edited;
      formattedBody = pageBody.replaceAll("<[^>]*>", "");
      // System.out.println(formattedBody);
      return formattedBody;

   }

   private class RetrieveWorker extends SwingWorker<Void, Void> {
      @Override
      protected Void doInBackground() throws Exception {
         retrieveContent();
         return null;
      }

   }
}

答案 1 :(得分:0)

我打赌你的输入处理程序被多次调用。文本可以设置为正文,然后打印,然后由于某种原因设置为空。通过添加

在system.out.println语句中对此进行测试
System.out.println("outputStart: " + pagebody + " :END");

然后,您将能够判断输入处理程序运行了多少次。