如何从另一个类刷新您的JTextPane

Cam*_*son 0 java swing multithreading jtextpane jscrollpane

我知道这个问题已经问过几次了。我试图从另一个类刷新我的JTextPane,当我从主类中刷新它时,它可以工作,但其他任何类都不能。我听说您需要使用线程来执行此操作,但是我尚未真正看到有人实现它。我在下面尽可能简单地提供了我的代码。有3个班级。谢谢!

以下是其外观的输出:http : //imgur.com/fQVDFPk

______________________________________________________
public class frame extends JPanel implements Runnable {

public TextBox textbox = new TextBox();

        Thread t1 = new Thread(new TextBox());

    public void run(){

    }
    public frame(){     

        t1.start();
        textField();

    }
public void textField(){
    add(textbox.sp);          
}

}

___________________________________________________

//bunch of imports

public class TextBox implements Runnable {

        JTextPane field = new JTextPane();
        JScrollPane sp = new JScrollPane(field);
        String name ="This is your message!!\n\n Message \n\n Message";
        public void run(){    

        try{
            Thread.sleep(2000);
                   System.out.println("hello thread");                                                             
            }catch(Exception e){}
         }            

    public TextBox(){
        field.setText("Welcome to Stack Overflow!!\n");  
        Message();
        }
    public void Message(){
                Style style = field.addStyle("I'm a Style", null);
                            StyledDocument doc = field.getStyledDocument();
                            StyleConstants.setForeground(style, Color.BLACK);
                            field.setCaretPosition(field.getText().length());                                    
                            try { doc.insertString(doc.getLength(), GetText(),style); }
                                    catch (BadLocationException e){} 
   Color color=new Color(255,255,255); 
   field.setBackground(color);  
   sp.setBounds(100, 335, 350, 100);
   field.setEditable(false);
   sp.setAutoscrolls(true);
    }
    public String GetText ( )
    {
        return name;
    }
    public void SetText (String PassedText)
    {
        name = PassedText;           
    }
}
Run Code Online (Sandbox Code Playgroud)

//我创建了一个新类来演示更改文档时要执行的操作。


public class ChangePane {
     public TextBox textbox = new TextBox();
    ChangePane(){

    Style style = textbox.field.addStyle("I'm a Style", null);

    StyledDocument doc = textbox.field.getStyledDocument();

    try {doc.insertString(doc.getLength(), "TESTING     ADDITION",style);}catch(BadLocationException e){}

    textbox.Message();
    }

}
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

我正在尝试从另一个类刷新我的JTextPane,

至于更新另一个类中的字段,您应该给保存该字段的类一个公共方法,其他类可以调用该方法来更改该字段的状态。例如,如果您想允许另一个类更改内的文本,则为您JTextField的类提供类似以下的方法:

public void setMyTextFieldText(String text) {
    myTextField.setText(text);

    // or if a JTextPane by inserting text into its Document here
}
Run Code Online (Sandbox Code Playgroud)

这与Swing或GUI无关,而与基本Java和面向对象的编码都无关。我相信,对于JTextPane,您需要做更多的事情,而不仅仅是setText,但是我并没有太多使用它们。

当我从我的主要班级开始学习时,它可以工作,但其他班级却没有。我听说您需要使用线程来执行此操作,但是我尚未真正看到有人实现它。我在下面尽可能简单地提供了我的代码。

如果您要从作为主Swing线程的EDT(事件分发线程)更改Swing GUI,则会出现线程问题。如果发生这种情况,那么是的,您应该将Swing调用放入Runnable并放入Swing事件队列,从而将Swing调用排队到Swing事件线程上:

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    // your swing calls go here
  }
});
Run Code Online (Sandbox Code Playgroud)

编辑1
注意,您的此方法无用:

// you should rename this setText(String passedText)
public void SetText (String PassedText)
{
    name = PassedText;           
    // you need to change your JTextPane's Document in here *****
}
Run Code Online (Sandbox Code Playgroud)

它所做的只是更改名称字符串字段所引用的文本,但这不会更改任何显示的文本。您将必须通过调用JTextPane方法,将文本插入JTextPane的Document中来更改JTextPane文本。


编辑2
请了解并使用Java命名约定,以免混淆可能希望了解您的代码并为您提供帮助的人们。类名应以大写字母开头,变量名和字段名以小写字母开头。您的命名似乎是向后的。


编辑3
您知道这里有两个完全独立的TextBox对象:

public TextBox textbox = new TextBox();
Thread t1 = new Thread(new TextBox());
Run Code Online (Sandbox Code Playgroud)

更改一个状态将不会影响另一状态。

同样,为什么要让您的组件类实现Runnable,然后将其放入线程中。那没有什么意义。要了解Swing线程,请阅读Swing中的并发


编辑4 sscce
的示例:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;
import javax.swing.text.*;

public class TextBoxTest {
   private JPanel mainPanel = new JPanel();
   private MyTextBox myTextBox = new MyTextBox();
   private JTextArea textArea = new JTextArea(20, 30);

   @SuppressWarnings("serial")
   public TextBoxTest() {
      JScrollPane scrollPane = new JScrollPane(textArea);
      scrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("JTextArea"),
            scrollPane.getBorder()));

      JPanel centerPanel = new JPanel(new GridLayout(1, 0));
      centerPanel.add(myTextBox.getMainComponent());
      centerPanel.add(scrollPane);

      JPanel bottomPanel = new JPanel();
      bottomPanel.add(new JButton(new AbstractAction("Submit Text") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_S);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               myTextBox.setText(textArea.getText());
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }
      }));
      bottomPanel.add(new JButton(new AbstractAction("Append Text") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_A);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               myTextBox.appendText(textArea.getText() + "\n");
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }
      }));      
      bottomPanel.add(new JButton(new AbstractAction("Append Red Text") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_R);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               myTextBox.appendTextInRed(textArea.getText() + "\n");
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }
      }));

      mainPanel.setLayout(new BorderLayout());
      mainPanel.add(centerPanel, BorderLayout.CENTER);
      mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      TextBoxTest textBoxTester = new TextBoxTest();

      JFrame frame = new JFrame("TextBoxTest");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(textBoxTester.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

class MyTextBox {
   private JTextPane textPane = new JTextPane();
   private JScrollPane scrollPane = new JScrollPane(textPane);
   private String name = "This is your message!! Message  Message "
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!! Message  Message "
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n";
   private StyledDocument doc = textPane.getStyledDocument();

   public MyTextBox() {
      addStylesToDocument(doc);
      textPane.setEditable(false);
      textPane.setFocusable(false);
      try {
         doc.insertString(0, name, doc.getStyle("regular"));
      } catch (BadLocationException e) {
         e.printStackTrace();
      }

      scrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("JTextPane"),
            scrollPane.getBorder()));
   }

   private void addStylesToDocument(StyledDocument doc2) {
      Style def = StyleContext.getDefaultStyleContext().getStyle(
            StyleContext.DEFAULT_STYLE);

      Style regular = doc.addStyle("regular", def);
      StyleConstants.setFontFamily(def, "SansSerif");
      StyleConstants.setFontSize(regular, 16);

      Style s = doc.addStyle("red", regular);
      StyleConstants.setForeground(s, Color.red);

   }

   public JScrollPane getMainComponent() {
      return scrollPane;
   }

   public void setText(String text) throws BadLocationException {
      doc.remove(0, doc.getLength());
      doc.insertString(0, text, doc.getStyle("regular"));
   }

   public void appendText(String text) throws BadLocationException {
      doc.insertString(doc.getLength(), text, doc.getStyle("regular"));
   }

   public void appendTextInRed(String text) throws BadLocationException {
      doc.insertString(doc.getLength(), text, doc.getStyle("red"));
   }

}
Run Code Online (Sandbox Code Playgroud)

编辑5
要从另一个线程发送数据,正如我在其他地方提到的,只需将代码包装到Runnable中,然后通过将其排队到EDT上SwingUtilities.invokeLater(myRunnable)

例如,我可以为MyTextBox类提供执行所有这些操作的方法,任何外部类都可以调用它:

public void appendTextOffEdt(final String text) {
  // first make sure that we're in fact off of the EDT
  if (SwingUtilities.isEventDispatchThread()) {
     try {
        appendTextInRedBold(text);
     } catch (BadLocationException e) {
        e.printStackTrace();
     }
  } else {
     SwingUtilities.invokeLater(new Runnable() {
        public void run() {
           try {
              appendTextInRedBold(text);
           } catch (BadLocationException e) {
              e.printStackTrace();
           }
        }
     });
  }
}
Run Code Online (Sandbox Code Playgroud)

例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;
import javax.swing.text.*;

public class TextBoxTest {
   private JPanel mainPanel = new JPanel();
   private MyTextBox myTextBox = new MyTextBox();
   private JTextArea textArea = new JTextArea(20, 30);
   private SendTextOffEdt sendTextOffEdt = new SendTextOffEdt(myTextBox);

   @SuppressWarnings("serial")
   public TextBoxTest() {
      JScrollPane scrollPane = new JScrollPane(textArea);
      scrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("JTextArea"),
            scrollPane.getBorder()));

      JPanel centerPanel = new JPanel(new GridLayout(1, 0));
      centerPanel.add(myTextBox.getMainComponent());
      centerPanel.add(scrollPane);

      JPanel bottomPanel = new JPanel();

      new Thread(sendTextOffEdt).start();

      bottomPanel.add(new JButton(new AbstractAction("Append Text") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_A);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               myTextBox.appendText(textArea.getText() + "\n");
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }
      }));
      bottomPanel.add(new JButton(new AbstractAction("Append Blue Text") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_B);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            try {
               myTextBox.appendTextInBlue(textArea.getText() + "\n");
            } catch (BadLocationException e1) {
               e1.printStackTrace();
            }
         }
      }));
      bottomPanel.add(new JButton(new AbstractAction("Exit") {
         {
            putValue(MNEMONIC_KEY, KeyEvent.VK_X);
         }

         @Override
         public void actionPerformed(ActionEvent e) {
            Window win = SwingUtilities.getWindowAncestor(mainPanel);
            win.dispose();
         }
      }));

      mainPanel.setLayout(new BorderLayout());
      mainPanel.add(centerPanel, BorderLayout.CENTER);
      mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      TextBoxTest textBoxTester = new TextBoxTest();

      JFrame frame = new JFrame("TextBoxTest");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(textBoxTester.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

class SendTextOffEdt implements Runnable {
   private static final long SLEEP_TIME = 3000;
   private static final String TEXT = "Sent off of EDT\n";
   private MyTextBox myTextBox;

   public SendTextOffEdt(MyTextBox myTextBox) {
      this.myTextBox = myTextBox;
   }

   @Override
   public void run() {
      while (true) {
         myTextBox.appendTextOffEdt(TEXT);
         try {
            Thread.sleep(SLEEP_TIME);
         } catch (InterruptedException e) {
         }
      }
   }
}

class MyTextBox {
   public static final String REGULAR = "regular";
   public static final String BLUE = "blue";
   public static final String RED_BOLD = "red bold";
   private JTextPane textPane = new JTextPane();
   private JScrollPane scrollPane = new JScrollPane(textPane);
   private String name = "This is your message!! Message  Message "
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!! Message  Message "
         + "This is your message!!\n\n Message \n\n Message \n\n"
         + "This is your message!!\n\n Message \n\n Message \n\n";
   private StyledDocument doc = textPane.getStyledDocument();

   public MyTextBox() {
      addStylesToDocument(doc);
      textPane.setEditable(false);
      textPane.setFocusable(false);
      try {
         doc.insertString(0, name, doc.getStyle("regular"));
      } catch (BadLocationException e) {
         e.printStackTrace();
      }

      scrollPane.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("JTextPane"),
            scrollPane.getBorder()));
   }

   private void addStylesToDocument(StyledDocument doc2) {
      Style def = StyleContext.getDefaultStyleContext().getStyle(
            StyleContext.DEFAULT_STYLE);

      Style regular = doc.addStyle(REGULAR, def);
      StyleConstants.setFontFamily(def, "SansSerif");
      StyleConstants.setFontSize(regular, 16);

      Style s = doc.addStyle(BLUE, regular);
      StyleConstants.setForeground(s, Color.blue);

      s = doc.addStyle(RED_BOLD, regular);
      StyleConstants.setBold(s, true);
      StyleConstants.setForeground(s, Color.red);

   }

   public JScrollPane getMainComponent() {
      return scrollPane;
   }

   public void setText(String text) throws BadLocationException {
      doc.remove(0, doc.getLength());
      doc.insertString(0, text, doc.getStyle(REGULAR));
   }

   public void appendText(String text) throws BadLocationException {
      doc.insertString(doc.getLength(), text, doc.getStyle(REGULAR));
   }

   public void appendTextInBlue(String text) throws BadLocationException {
      doc.insertString(doc.getLength(), text, doc.getStyle(BLUE));
   }

   public void appendTextInRedBold(String text) throws BadLocationException {
      doc.insertString(doc.getLength(), text, doc.getStyle(RED_BOLD));
   }

   public void appendTextOffEdt(final String text) {
      // first make sure that we're in fact off of the EDT
      if (SwingUtilities.isEventDispatchThread()) {
         try {
            appendTextInRedBold(text);
         } catch (BadLocationException e) {
            e.printStackTrace();
         }
      } else {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               try {
                  appendTextInRedBold(text);
               } catch (BadLocationException e) {
                  e.printStackTrace();
               }
            }
         });
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

至于教程: