我有一個主類有兩個子類,一個用於GUI初始化,另一個用於服務器創建和功能。我有一個布爾變量「連接」,當用戶連接到服務器時爲true,否則爲false。我如何能夠在服務器子類中更新GUI子類中的JTextPane文本,以在「連接」爲真時稱「客戶端連接」,在錯誤時稱爲「無連接」?更改布爾變量的JTextPane文本
主類:
public class serverMain {
public static boolean allowConnections = false;
public static boolean connected = false;
public static boolean launchOnStart = false;
public static boolean loop = true;
public static int serverPort = 1234;
public static ServerSocket serverSocket;
public static void main(String args[]){
serverGUI.gui();
while (loop){
if (allowConnections == true){
serverCommands.commands();
}
else {
System.out.println("reject");
}
}
}
}
GUI類(去除不相關部分):
public class serverGUI extends serverMain {
public static JTextPane txtConnectionMarker;
public static void gui(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
serverGUI window = new serverGUI();
window.frmRemoteServer.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public serverGUI() {
initialise();
}
public void initialise() {
frmRemoteServer = new JFrame();
frmRemoteServer.setBounds(100, 100, 720, 420);
frmRemoteServer.setResizable(false);
frmRemoteServer.setTitle("Remote Server");
frmRemoteServer.getContentPane().setBackground(Color.WHITE);
frmRemoteServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmRemoteServer.getContentPane().setLayout(null);
JTextPane txtConnectionMarker = new JTextPane();
txtConnectionMarker.setEditable(false);
txtConnectionMarker.setBounds(548, 21, 149, 33);
txtConnectionMarker.setFont(new Font("Segoe UI Light", Font.BOLD, 16));
txtConnectionMarker.setBackground(SystemColor.menu);
frmRemoteServer.getContentPane().add(txtConnectionMarker);
if (connected == true){
txtConnectionMarker.setText("Connected");
txtConnectionMarker.setForeground(Color.GREEN);
}
else {
txtConnectionMarker.setText("No Connection");
txtConnectionMarker.setForeground(Color.RED);
}
// obviously this will not update as connected changes
}
}
服務器類(不相關的部分去掉):
public class serverCommands extends serverMain {
public static void commands() {
String input;
try {
serverSocket = new ServerSocket(serverPort);
System.out.println("socket opened on port "+serverPort);
Socket clientSocket = serverSocket.accept();
connected = true;
// there's more to all parts but the given code
// should be enough to get what I'm trying to do
// basically once the user disconnects connected
// will change back to false
'如果(連接){label.setText( 「已連接」); } else {label.setText(「Client not connected」)}'maybe(?) – Frakcool
究竟是什麼問題?訪問JTextPane實例?在正確的時間設置文本?添加到JTextPane?請更具體一些,否則我們可以猜測,理想情況下也請顯示你在[mcve]中試過的東西。 –
模型 - 視圖 - 控制器 – ControlAltDel