[英]Pass a value from one class to another
我試圖從我的Calculator(在其單獨的類中)到另一個類的JTextPane
中獲取一個值。 我唯一擔心的是,由於我的程序設計,我無法這樣做。
在我的主類中,我有一個內部類,當單擊JMenuItem
時,它將打開另一個框架。
public class Notepad extends JFrame
{
...
// Opens when the user clicks Calculator
// (JMenuItem in the JFrame of the Notepad class)
private class Calculator implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Calculate c = new Calculate();
c.buildGUI();
// I've tried creating a reference to the Insert class and tried to
// retrieve the value from the JLabel in the Calculator but continuously
// receive a NullPointerException
}
}
...
}
在我的另一個類中,我有一個Insert類的內部類(允許用戶根據需要將答案插入JTextPane
)。
***我在這里嘗試了很多東西,比如創建一個“getter”和“setter”,它將值傳遞到Notepad類,但發現它們由於我的程序設置而無法工作。
public class Calculate extends JFrame
{
...
/* Insert
* Inserts the answer into the
* text pane of the Notepad class
*/
private class Insert implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String answer = proposal.getText(); // from the JLabel
if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please");
// else, insert the answer
// ***
}
}
...
}
我的另一個問題是,單擊記事本框架中的JMenuItem
(計算器)時,我收到NullPointerException
因為JLabel
(計算器的答案)中沒有任何值。
那么如何從計算器中獲取JLabel
的值並在單擊Insert時將其放入記事本框架的JTextPane
中? 另外,如果未將我的程序設置為執行此類操作,那么您是否有任何重新設計建議?
最簡單的方法是將對NotePad的引用傳遞給Calculator類。 Calculator類將如下所示:
public class Calculator extends JFrame{
Notepad notepad;
public Caluclator(Notepad np){
this();
notepad = np;
//any other code you need in your constructor
}
...
private class Insert implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String answer = proposal.getText(); // from the JLabel
if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please");
else{
notepad.myJTextPane.setText(answer);
}
// ***
}
}
並在記事本類中調用它:
Calculate c = new Calculate(Notepad.this);
話雖如此,查找一些設計模式(例如Observer)是一個好主意,這些設計模式恰好可以在更改另一個類時更新一個類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.