Java 从子类';调用JTextArea.append();丝线
我正在使用WindowBuilder用Java创建一些聊天功能。我的GUI类创建了一个线程,我希望能够从中更新超类的TextArea。我创建线程的原因是我希望能够中断子类中的代码 我的问题是,我不能从子类的线程中附加到超类的TextArea 我试着把代码缩减到最基本的部分:Java 从子类';调用JTextArea.append();丝线,java,multithreading,swing,Java,Multithreading,Swing,我正在使用WindowBuilder用Java创建一些聊天功能。我的GUI类创建了一个线程,我希望能够从中更新超类的TextArea。我创建线程的原因是我希望能够中断子类中的代码 我的问题是,我不能从子类的线程中附加到超类的TextArea 我试着把代码缩减到最基本的部分: import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.SwingUt
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SSCCE {
private JFrame frmRoom;
private final static String newline = "\r\n";
private JTextField textField;
private JScrollPane scrollPane;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SSCCE window = new SSCCE();
window.frmRoom.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SSCCE() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmRoom = new JFrame();
frmRoom.setTitle("Test");
frmRoom.setBounds(100, 100, 450, 300);
frmRoom.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frmRoom.setJMenuBar(menuBar);
JMenu mnButton1 = new JMenu("Button 1");
menuBar.add(mnButton1);
JMenuItem mntmButton2 = new JMenuItem("Button 2");
mntmButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Thread t = new Thread(new SSCCESub());
SwingUtilities.invokeLater(t);
//t.start();
//Neither of the above work.
}
});
mnButton1.add(mntmButton2);
textField = new JTextField();
scrollPane = new JScrollPane();
textArea = new JTextArea();
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
GroupLayout groupLayout = new GroupLayout(frmRoom.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 434, Short.MAX_VALUE)
.addGap(0))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE))
);
frmRoom.getContentPane().setLayout(groupLayout);
}
private void addLineToTextArea(String line) {
System.out.println("Tried calling a superclass method in order to append to the TextArea");
textArea.append(line + newline);
}
private static class SSCCESub extends SSCCE implements Runnable {
public void run() {
super.textArea.append("This won't be visible" + newline); //TODO This is what my question is about.
super.addLineToTextArea("This won't be visible");
System.out.println("This should be visible");
return;
}
}
}
简单的回答是:不要使用继承来促进子对象和父对象之间的通信。这不是继承的目的,也不是它的工作方式(正如您所发现的)。而是使用组合——使用构造函数或方法参数将object1的实例传递到object2,并调用公共方法来传递信息 因此,您的第二个类可以有一个构造函数,它接受一个SSCCE参数,允许您传入它,然后设置一个SSCCE字段,这可以允许您调用当前SSCCE对象的公共方法
接下来,一旦您解决了这个问题,您的代码就会违反Swing线程规则——您应该只在Swing事件线程上修改Swing组件。请阅读 更详细的答案来了 例如,假设您想用套接字钩住Swing GUI,以实现简单的聊天通信。我们可以创建一个新的GUI类,比如称为SSCCE2,类似
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.*;
@SuppressWarnings("serial")
public class SSCCE2 extends JPanel {
private static final int GAP = 4;
private Action submitAction = new SubmitAction("Submit");
private JTextField textField = new JTextField(40);
private JTextArea textArea = new JTextArea(20, 40);
private JButton submitButton = new JButton(submitAction);
private PrintWriter printWriter = null;
private ChatWorker chatWorker = null;
public SSCCE2(Socket socket) throws IOException {
printWriter = new PrintWriter(socket.getOutputStream());
chatWorker = new ChatWorker(this, socket);
chatWorker.execute();
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textField.setAction(submitAction);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(textField);
bottomPanel.add(submitButton);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(scrollPane);
add(bottomPanel, BorderLayout.PAGE_END);
}
// Action (acts as an ActionListener) that gets text from
// JTextField and puts it into JTextArea
// And also sends it via PrintWriter to the Socket
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textField.selectAll();
// send this to the socket for chatting....
if (printWriter != null) {
printWriter.println(text);
}
textArea.append(text);
textArea.append("\n");
}
}
// public method to allow outside objects to append to the JTextArea
public void append(String text) {
textArea.append(text);
textArea.append("\n");
}
}
使用公共方法,比如public void append(String text)
,允许外部类附加到JTextArea,然后我们将在需要的地方传递一个实例,这里:chatWorker=new chatWorker(这个,socket)代码>通过传入此
。然后我们的聊天人员可以调用公共方法:
import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;
import javax.swing.SwingWorker;
//better if the threading is done with a SwingWorker
//to not run afoul of Swing threading rules
public class ChatWorker extends SwingWorker<Void, String> {
private SSCCE2 sscce2 = null;
private Scanner scanner = null;
public ChatWorker(SSCCE2 sscce2, Socket socket) throws IOException {
this.sscce2 = sscce2; // get the instance and assign to field
scanner = new Scanner(socket.getInputStream());
}
@Override
protected Void doInBackground() throws Exception {
// this is called in a background thread
while (scanner.hasNextLine()) {
publish(scanner.nextLine());
}
return null;
}
@Override
protected void process(List<String> chunks) {
// this is called on the Swing event thread
for (String text : chunks) {
sscce2.append(text); // append the texts as they come in
}
}
}
import java.io.IOException;
导入java.net.Socket;
导入java.util.List;
导入java.util.Scanner;
导入javax.swing.SwingWorker;
//最好是由SwingWorker完成线程
//不要违反Swing线程规则
公共类ChatWorker扩展SwingWorker{
专用SSCCE2 SSCCE2=null;
专用扫描仪=空;
公共聊天工作者(SSCCE2 SSCCE2,套接字套接字)引发IOException{
this.sscce2=sscce2;//获取实例并分配给字段
scanner=新扫描仪(socket.getInputStream());
}
@凌驾
受保护的Void doInBackground()引发异常{
//这是在后台线程中调用的
while(scanner.hasNextLine()){
发布(scanner.nextLine());
}
返回null;
}
@凌驾
受保护的无效进程(列表块){
//这是在Swing事件线程上调用的
for(字符串文本:块){
sscce2.append(text);//输入文本时追加文本
}
}
}
首先也是最重要的一点是,您错误地使用了继承。不要让SSCCESub从SSCCE继承,这不是继承的目的,也不是它的工作方式。而是使用构图。继承是为了将行为传递给子类,但不是为了促进子类和父类之间的对象到对象的通信。接下来,一旦解决了这个问题,您的代码就会违反Swing线程规则——您应该只在Swing事件线程上变异Swing组件。请阅读