我有两个基于JFrame的窗口:SeatLayoutBillSummary。我需要从seatnumber框架中获取SeatLayout并将其显示在BillSummary中,但变量作用域仅限于第一帧。

我怎样才能做到这一点?

最佳答案

使用多个JFrame是一个不好的做法,应避免使用。
原因是,它将在将来增加更多问题,并且将成为维护的噩梦。

要回答您的问题,如何将变量从父代(JFrame)传递给子代(JDialog)。这可以通过使用JDialog实现。

我将通过一个例子。
可以说,您的BillSummary.java是....

//BillSummary Class
public class billSummary {
   JFrame frame;
   billSummary(JFrame frame) {
    this.frame = frame;
}

  public void launchbillSummary(int seatNumber) {
    // Create a dialog that suits your ui , you can use JPanel as your layout container
    JDialog dialog = new JDialog(frame, "Bill Summary", true);
    dialog.setLayout(new BorderLayout());
    dialog.setSize(100, 100);
    dialog.add(new JLabel(Integer.toString(seatNumber)), BorderLayout.CENTER);
    dialog.setVisible(true);
  }

}


您的seatLayout.java

public class seatLayout {

 seatLayout(){
    //Lets say you have seleted seat number 10
    int defaultSeatNumber = 10;

    //Lets say you have a button and when it is clicked , you pass the data to billsummary page
    JButton enter = new JButton("Enter");

    //Your seatLayout GUI
    JFrame frame = new JFrame("seat layout");
    frame.setSize(300,300);
    frame.add(enter);

    enter.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //Do your passing of data/ price of calculation here
            //You pass the data that to your custom dialog -> Bill summary
            new billSummary(frame).launchbillSummary(defaultSeatNumber);
        }
    });
    frame.setVisible(true);
}


public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new seatLayout();
        }
    });
  }
}


希望能对您有所帮助。祝好运 :)

关于java - 将可变范围从一帧扩展到另一帧,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58364114/

10-09 10:08