Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

java - How can I return a value from a JDialog box to the parent JFrame?

I have created a modal JDialog box with a custom drawing on it and a JButton. When I click the JButton, the JDialog box should close and a value should be returned.

I have created a function in the parent JFrame called setModalPiece, which receives a value and sets it to a local JFrame variable.

The problem is that this function is not visible from the JDialog box (even though the JDialog box has a reference to the parent JFrame).

Two questions: 1) Is there a better way to return a value from a JDialog box to its parent JFrame?

2) Why can't the reference to the JFrame passed to the JDialog be used to access my JFrame function setModalPiece?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I generally do it like this:

Dialog dlg = new Dialog(this, ...);
Value result = dlg.showDialog();

The Dialog.showDialog() function looks like this:

ReturnValue showDialog() {
    setVisible(true);
    return result;
}

Since setting visibility to true on a JDialog is a modal operation, the OK button can set an instance variable (result) to the chosen result of the dialog (or null if canceled). After processing in the OK/Cancel button method, do this:

setVisible(false);
dispose();

to return control to the showDialog() function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...