簡體   English   中英

使用ActionListener將int值從一個jFrame傳遞到另一個jFrame

[英]Passing int value from one jFrame to another jFrame using ActionListener

我有兩個類,我正在使用ActionListeners,問題是我想從第二個類的First類中接收一個int值...第一個類是這個:

public class PanelCotizacion extends javax.swing.JPanel implements ActionListener {
    private int numCotizacion = 0;
    public PanelCotizacion() {
        initComponents();
    }
    public void actionPerformed(ActionEvent e) {
        System.out.println("HERE IS WHERE I WANT TO RECEIVE THE VALUE");
        this numCotizacion = "";
        //THE VALUE THAT I WANT TO RECEIVE FROM THE OTHER jFRAME
        //TRIGGERED BY THE EVENT OF THE BUTTON (action performed)
    }
}

這是第二個,我要在其中發送int值:

public class BusquedaCotizacionGUI extends javax.swing.JFrame {
    private int numCotizacion = 0;
    public BusquedaCotizacionGUI() {
        initComponents();
        this.setLocationRelativeTo(null);
        PanelCotizacion pC = new PanelCotizacion();
        this.cmdOK.addActionListener(pC);
    }
    private void cmdOKActionPerformed(java.awt.event.ActionEvent evt) { 
        this.numCotizacion = Integer.parseInt(this.txtNumCotizacion.getText());
        //Here is where I WANT TO PASS THE VARIABLE "numCotizacion" tho the other class
        //Can Somebody Help Me
        this.dispose();
    }
}

您能幫我做到這一點嗎,非常感謝!

從您的代碼中,我認為BusquedaCotizacionGUI JFrame負責打開PanelCotizacion Jpanel並傳遞您的變量。

因此,有很多方法可以將變量從JFrame傳遞到JPanel

您可以創建一個帶有int參數的構造函數,然后在該構造函數中傳遞變量,例如:

public PanelCotizacion(int numCotizacion) {
    initComponents();
    this.numCotizacion = numCotizacion;
}

或者您可以將JFrame作為父組件傳遞給JPanel到構造函數,然后通過創建一個geting方法來獲取值,例如,

private JFrame parent;
public PanelCotizacion(JFrame parent) {
    initComponents();
    this.parent= parent;
}

然后得到像這樣的值:

parent.getNumCotizacion();

ActionEvent類中有Object getSource()方法,因此在ActionListener中,您可以獲取源並將其轉換為PanelCotizacion 另一種可能性是BusquedaCotizacionGUI PanelCotizacion的引用添加到PanelCotizacion的構造函數中。

在您的第二個JFrame(BusquedaCotizacionGUI)中,添加以下代碼行(例如):

 PanelCotizacion.setParam(int parameterToPass)

在第一個JFrame(PanelCotizacion)中添加一個方法(例如setParam)和一個整數字段(例如myField):

 public void setParam (int param) {
 this.myField = param;
}

應該決定如何實現這個想法(靜態方法與創建第一個JFrame的實例,...); 這只是一般性的想法,請對其進行自定義以滿足您的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM