1

我正在调用一个返回字符串(来自网页的编辑文本)的方法,并且我想将该字符串打印到我的 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;

}
4

2 回答 2

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

   }
}
于 2013-02-26T20:55:44.643 回答
0

我敢打赌你的输入处理程序被多次调用。文本可以设置为正文,然后打印,然后由于某种原因被设置回空。通过添加在您的 system.out.println 语句中对此进行测试

System.out.println("outputStart: " + pagebody + " :END");

然后你就可以知道你的输入处理程序运行了多少次。

于 2013-02-26T21:17:25.277 回答