[英]How can I pass data from another class to a GUI?
如何使用GUI將數據/值從一個類傳遞到另一個類? 我正在嘗試將namesOut
數組傳遞給GUI中的namesOut
標簽。 我陷入困境並得到一個錯誤。
這是我的代碼:
package testClassesGUI;
import java.awt.BorderLayout;
public class UI extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI frame = new UI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDisplayOutNames = new JLabel("Display out names:");
lblDisplayOutNames.setBounds(32, 25, 121, 16);
contentPane.add(lblDisplayOutNames);
JLabel namesOut = new JLabel(""); //here i need to bring the data
namesOut.setBounds(32, 63, 228, 87);
contentPane.add(namesOut);
}
}
我在這里得到一個錯誤。
package testClassesGUI;
public class Logic {
private String[] someArray = { "Great", "World" };
// getter method
public String[] message2(){
return someArray;
}
// setter method
public void setSomeArray(String[] someArray){
this.someArray = someArray;
}
UI logicObject = new UI();
logicObject.namesOut.setText(message2); //here my error misplaced construct(s), variable declaratoridexpected
}
非常感謝您的幫助。
把它放在你的UI構造函數中。 您應該在其中創建一個Logic
對象
public UI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDisplayOutNames = new JLabel("Display out names:");
lblDisplayOutNames.setBounds(32, 25, 121, 16);
contentPane.add(lblDisplayOutNames);
JLabel namesOut = new JLabel(""); //here i need to bring the data
namesOut.setBounds(32, 63, 228, 87);
contentPane.add(namesOut);
Logic logic = new Logic(); <<---
String[] array = logic.message2(); |
|
String s = ""; |
for (String str : array){ |
s += str + " "; |
} |
|
namesOut.setText(s); <<----
}
您可以從Logic
類中刪除它
UI logicObject = new UI();
logicObject.namesOut.setText(message2);
namesOut
是在UI的構造函數中聲明的局部變量。 你無法從Logic
訪問它。 將其聲明為公共成員變量
public JLabel namesOut;
你必須定義一個函數。 也許是一個構造函數:
Logic () {
logicObject.namesOut.setText(message2);
}
你也可以在代碼塊里面執行,但這不常見:
{
logicObject.namesOut.setText(message2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.