How to get to JDialog methods? - java

I just get stuck with app. The thing is in second actionListener, I want to get object or more specifically access to methods in my JDialog class.
I got few dialogs created, but not visible. In first actionListener I get to them by getDialog function which is returning JDialog. So I can each one of them visible.
2nd actionListener which I need help with, is showing JOptionPane and if user pick the YES_OPTION I want to run my method from specific dialog.
I it's not clear I'd try to fix my explanations so you can understand it.
modifyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton thisButton = (JButton) e.getSource();
JPanel parentPanel = (JPanel) thisButton.getParent();
Container topLevel = parentPanel.getTopLevelAncestor();
MainFrame mainFrame = (MainFrame) topLevel;
mainFrame.getDialog(TABLECOUNTER).setVisible(true);
}
});
abortButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object[] options = {"Tak", "Nie"};
int userReply = JOptionPane.showOptionDialog(null, "Czy na pewno chcesz anulować rachunek?", "Probujesz anulować rachunek!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (userReply == JOptionPane.YES_OPTION) {
JButton thisButton = (JButton) e.getSource();
JPanel parentPanel = (JPanel) thisButton.getParent();
Container topLevel = parentPanel.getTopLevelAncestor();
MainFrame mainFrame = (MainFrame) topLevel;
mainFrame.getDialog(TABLECOUNTER).myMethod(); //here
}
}
});

"I want to get object or more specifically access to methods in my JDialog class"
If the method getDialog returns a standard JDialog,
public JDialog getDialog(...) {}
Then you're stuck with the methods of JDialog, without proper casting, or changing the return type. That would explain why you are able to setVisible in the first method, because JDialog does have a method setVisible. So to access the method myMethod you'll want to do some casting.
((MyDialog)mainFrame.getDialog(TABLECOUNTER)).myMethod();

Related

Passing an object from one JFrame to another [duplicate]

I have two Jframes where frame1 has some text fields and when a button on frame1 is clicked, I open another JFrame which contains a search box and a JTable containing search results.
When I click on a result row on JTable, I want that particular values to be reflected in the frame1 text fields.
I tried passing the JFrame1's object as a parameter but I have no clear idea on how to achieve this.
Any help would be highly appreciated.
Thanks
First of all, your program design seems a bit off, as if you are using a JFrame for one of your windows where you should in fact be using a JDialog since it sounds as if one window should be dependent upon the other.
But regardless, you pass references of GUI objects the same as you would standard non-GUI Java code. If one window opens the other (the second often being the dialog), then the first window usually already holds a reference to the second window and can call methods off of it. The key often is when to have the first window call the second's methods to get its state. If the second is a modal dialog, then the when is easy -- immediately after the dialog returns which will be in the code immediately after you set the second dialog visible. If it is not a modal dialog, then you probably want to use a listener of some sort to know when to extract the information.
Having said this, the details will all depend on your program structure, and you'll need to tell us more about this if you want more specific help.
For a simple example that has one window open another, allows the user to enter text into the dialog windows JTextField, and then places the text in the first window's JTextField, please have a look at this:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}
You'd do a very similar technique to get information out of a JTable.
And again, if this information doesn't help you, then please tell us more about your program including showing us some of your code. The best code to show is a small compilable example, an SSCCE similar to what I've posted above.

How to transfer an answer to another jframe? [duplicate]

I have two Jframes where frame1 has some text fields and when a button on frame1 is clicked, I open another JFrame which contains a search box and a JTable containing search results.
When I click on a result row on JTable, I want that particular values to be reflected in the frame1 text fields.
I tried passing the JFrame1's object as a parameter but I have no clear idea on how to achieve this.
Any help would be highly appreciated.
Thanks
First of all, your program design seems a bit off, as if you are using a JFrame for one of your windows where you should in fact be using a JDialog since it sounds as if one window should be dependent upon the other.
But regardless, you pass references of GUI objects the same as you would standard non-GUI Java code. If one window opens the other (the second often being the dialog), then the first window usually already holds a reference to the second window and can call methods off of it. The key often is when to have the first window call the second's methods to get its state. If the second is a modal dialog, then the when is easy -- immediately after the dialog returns which will be in the code immediately after you set the second dialog visible. If it is not a modal dialog, then you probably want to use a listener of some sort to know when to extract the information.
Having said this, the details will all depend on your program structure, and you'll need to tell us more about this if you want more specific help.
For a simple example that has one window open another, allows the user to enter text into the dialog windows JTextField, and then places the text in the first window's JTextField, please have a look at this:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}
You'd do a very similar technique to get information out of a JTable.
And again, if this information doesn't help you, then please tell us more about your program including showing us some of your code. The best code to show is a small compilable example, an SSCCE similar to what I've posted above.

JOptionPane always returning -1

I want to double check the delete operation to prevent accidental deletion.
(Here the Yes button would only be enabled if the checkbox is checked.)
But both Yes and No Buttons are returning -1.
This is a snippet of my program.
public class class1 extends javax.swing.JInternalFrame {
JCheckBox cbConfirmDelete;
JPanel outer = new JPanel(new BorderLayout());
final JButton btnYes = new JButton("Yes");
final JButton btnNo = new JButton("No");
public class1() {
......
//Button btnYes ActionListener for JOptionPane
btnYes.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent) e.getSource());
pane.setValue(btnYes);
}
});
//Button btnNo ActionListener for JOptionPane
btnNo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent) e.getSource());
pane.setValue(btnNo);
}
});
//layout for JOptionPane
JPanel nested1 = new JPanel();
nested1.add(cbConfirmDelete);
JPanel nested2 = new JPanel();
nested2.add(btnYes);
nested2.add(btnNo);
outer.add(nested1, BorderLayout.NORTH);
outer.add(nested2, BorderLayout.CENTER);
}
protected JOptionPane getOptionPane(JComponent parent) {
JOptionPane pane = null;
if (!(parent instanceof JOptionPane)) {
pane = getOptionPane((JComponent) parent.getParent());
} else {
pane = (JOptionPane) parent;
}
return pane;
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int dialogResult = JOptionPane.showOptionDialog(null, "Are you sure you want to Delete the Reference ?", "Delete Reference", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{outer}, btnYes);
System.out.println("DialogResult: " + dialogResult);
}
}
The Output DialogResult is always -1. Why is that happening ?
If I pass the following object in JOptionPane it works fine..
new Object[]{cbConfirmDelete, btnYes, btnNo}
But this is not working
new Object[]{outer}
I see a couple of problems here. Since you're creating a Yes/No option dialog, your Object[] array should contain two, and only two, components that correspond to yes or no.
For your example that works, your Object[] array contains the checkbox, the yes button, and the no button. That's one too many components. When you set the pane value in the yes or no action listener, you're setting it to 1 or 2 instead of 0 or 1, since positionally, those components are the second and third. This isn't necessarily a big problem, but usually when you return from a yes/no dialog box, you check for JOptionPane.YES_OPTION (0) or JOptionPane.NO_OPTION (1) to see if the user chose yes or no. In your scenario, you're going to have to check for 1 or 2 since the checkbox is component 0.
For your non-working scenario, the problem is that your object array only contains one object, the outer panel containing the checkbox and the yes/no buttons. Technically what's happening is that you're telling the option pane that there's only one selectable component, a JPanel. Calling pane.setValue() with any component other than the outer panel will have no effect, since the pane's selection value is -1 (uninitialized value) to begin with, and it will only change if you call setValue(outer).

i have following code for jframe.i want to add a jdialog whose parent is the current jframe.pls suggest

the code i have used is this.i want the new jDialog to be subclass of the ManagerScreen Frame.here using 'this' id not helping as i am inside inner class.
class ManagerScreen extends JFrame {
...
void createGui() {
JButton btncreateacc = new JButton("Create Account");
btncreateacc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new JDialog(ManagerScreen) ;
}
});
}
}
however it gives error . pls suggest how it can be done?
Use ManagerScreen.this
new JDialog(ManagerScreen.this, "Dialog Title", true);
using this buy itself, is actually pointing to the ActionListener class
See JDialog Docs for more constructors.
"i want the new jDialog to be subclass of the ManagerScreen Frame"
Also, not the above does not make, the JDialog a sublcass of the JFrame class but instead, makes the JFrame the owner of the JDialog

JFrame problems

I am creating a popup JFrame that will have a message and yes/no buttons. I am using this method in 2 ways. In 1, the main program calls this method and in the other, this method is called directly after a previous JFrame is closed. This method works when being called form the main program, but when another JFrame calls it, the JFrame created in this method shows up completely blank and the GUI freezes. I cannot exit out of the JFrame, but I can move it. The freezing is a result of the Thread.yield because response is always null, but in what instances will the JFrame fail to be created properly?
Note: response is a static variable. Also when this JFrame is created by another JFrame, the original JFrame does not exit correctly. That JFrame has a JComboBox, and the selected option is frozen on the dropdown. When it does not call this method, it closes properly.
public static String confirmPropertyPurchase(String message)
{
response = null;
final JFrame confirmFrame = new JFrame("Confirm");
confirmFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
response = "No";
}
public void windowDeactivated(WindowEvent e) {
confirmFrame.requestFocus();
}
});
final JPanel confirmPanel = new JPanel();
final JButton yes = new JButton();
final JButton no = new JButton();
yes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
response = "Yes";
confirmFrame.setVisible(false);
}
});
no.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
response = "No";
confirmFrame.setVisible(false);
}
});
final JLabel confirmLabel = new JLabel(" " + message);
yes.setText("Yes");
yes.setPreferredSize(new Dimension(100, 100));
no.setText("No");
no.setPreferredSize(new Dimension(100,100));
confirmFrame.add(confirmLabel, BorderLayout.CENTER);
confirmPanel.add(yes);
confirmPanel.add(no);
confirmFrame.add(confirmPanel, BorderLayout.AFTER_LAST_LINE);
confirmFrame.setPreferredSize(new Dimension(520, 175
));
confirmFrame.pack();
confirmFrame.setVisible(true);
while(response == null)
{
Thread.yield();
}
return response;
}
Again, you shouldn't be using a JFrame as a dialog. In fact your whole bit of code can be replaced with a simple JOptionPane. e.g.,
Component parent = null; // non-null if being called by a GUI
queryString = "Do you want fries with that?";
int intResponse = JOptionPane.showConfirmDialog(parent, queryString,
"Confirm", JOptionPane.YES_NO_OPTION);
myResponse = (intResponse == JOptionPane.YES_OPTION) ? "Yes" : "No";
System.out.println(myResponse);
And this:
while(response == null)
{
Thread.yield();
}
should never be called on the main Swing thread, the EDT or event dispatch thread. The reason the code works when it does is because you're calling this little bit above off of the EDT, but when you call it on the EDT it freezes the EDT and thus the entire GUI. Simply don't do it.
You can't do this, plain and simple. There's only one event thread, and while you're sitting in a loop waiting for somebody to click in your JFrame, you're tying up that thread such that no events can be handled.
Don't try to create your own dialog out of a JFrame -- use JOptionPane or a JDialog, which are designed to handle this situation for you internally.

Categories