I have my main JFrame and one more JDialog.
If user click on the button, i want JDialog to call method from this JFrame(which contains some operations on ComboBox in this JFrame).
How can I do that?
I don't want to use MyJFrame form = new MyJFrame(); because it will make a new JFrame which i don't want to do, i want to call method from JFrame which is running currently on my computer.
Thanks.
Assuming the JButton is on the JDialog.
If both are in the same class, why not just do this?
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I just got clicked
form.doSomething();
}
});
which can be shortened to
button.addActionListener(e -> form.doSomething());
If they aren't, and you're extending JDialog (which I wouldn't recommend) just pass the JFrame in its constructor, then your dialog will have access to it.
It's not possible to add much more without seeing more of your code.
Maybe JOptionPane.showInputDialog() , show a JDialog to take input from User.
Related
I am a new Java Programmer and I am tying to link two JFrames Windows together nut I don't know how , can I get some help please.
What I mean is that I made a button and I need the button to go to the next window,
but I don't know how to do so...
If you are trying to do a wizard then you may want to take a look to Creating Wizard Dialogs with Java Swing document. You would need only one JFrame (or JDialog) and several JPanel which will pass as you press "Next" button.
If you want open a new window then you can create and show a new JDialog within button action listener implementation. Something like this:
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog();
dialog.setTitle("Title");
dialog.setModal(true);
dialog.getContentPane().add(...); // add components here
dialog.pack();
dialog.setVisible(true);
}
Suggested readings:
The Use of Multiple JFrames, Good/Bad Practice? (it's a bad practice)
How to Use CardLayout
How to Use Buttons, Check Boxes, and Radio Buttons
How to Use Modality in Dialogs
two JFrames,
JFrame Main; // Main JFrame
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
mainMenuItem.setActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
try{
Sub subFrame = new Sub();
subFrame.setVisible(true);
}catch(Exception e){}
}
});
}
The problem is whenever i close the second JFrame (Sub) it closes the first aswell.
Both JFrames have:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Is that part of the problem?
EXIT_ON_CLOSE means to exit the program immediately (System.exit()) when the frame is closed.
You probably want to set this to DISPOSE_ON_CLOSE, then add a WindowListener and close the program only if both frames have been closed.
(Or, perhaps you want only the main frame to have EXIT_ON_CLOSE)
Yes. JFrame.EXIT_ON_CLOSE by definition exits the application. For your second Frame use DISPOSE_ON_CLOSE or HIDE_ON_CLOSE.
Hope this helps!
You state:
JFrame Sub; //Second JFrame that is initialized from within Main via a JMenuItems ActionListener.
This suggests you've a design problem:
Your 2nd "frame" shouldn't even be a JFrame since it is not behaving as a separate independent main program window.
Instead it's acting as a dialog since it is dependent on and shown from a parent window, the main JFrame. So make the secondary window a JDialog not a JFrame, and all these problems will go away.
You will need to consider whether it should be a modal dialog where the main window is not accessable to the user while the dialog is open, or a non-modal dialog.
Having said that, you may even be better off using one window/JFrame and swapping views via a CardLayout.
Please read this link: The Use of Multiple JFrames, Good/Bad Practice?, and in particular please have a look at Andrew Thompson's community wiki answer.
Let's say we have a JFrame frame that contains two JPanels, buttonPanel and dataPanel, and in this panel a single JButton button. When clicked, button creates and shows a JDialog dialog in its own window (as usual). Using several JTextFields and a submit button, the JDialog dialog creates a new Object dataObject encapsulating these input data. If we wish our dataPanel JPanel in the main application frame to display this dataObject, how should dataObject be appropriately passed to the JPanel residing in a foreign JFrame?
That was a mouthful even to me while writing it, so I'll attempt to clarify:
JFrame frame
JPanel dataPanel - meant to display data from Objects created in the JDialog
JPanel buttonPanel - contains a button to open the JDialog, into which some information will be entered and with said information our Object dataObject is constructed.
The goal here is to pass this dataObject (and it's constituent fields) to the dataPanel to be displayed. What is the most appropriate way to handle this? I considered keeping the Objects in dataPanel static and then calling a static method from the JDialog to add the new object, but it doesn't seem the proper thing to do.
Some guidance?
Much will depend on the structure of your program, including how the dialog is supposed to behave:
If the JDialog is modal and disappears when the submit button has been pushed, then the solution is easy -- extract the data from the dialog-related class after it returns which will be the line of code right after where you display the dialog. The dialog's submit JButton's listener could simply make the dialog no longer visible.
Otherwise if the JDialog is non-modal and disappears when the submit button has been pushed, then you may wish to attach a Listener to its Window, I believe a WindowListener, and then have your calling code extract the information when the listener indicates that the dialog has been closed or is closing.
Otherwise, if the JDialog is non-modal and is not supposed to become invisible when the submit button has been pressed but you need to update the calling program with new data, then I would have the calling class add a PropertyChangeListener onto the dialog-related class so that the dialog-related class can notify any listeners that submit has been pressed. This code would be in the dialog's submit JButton's listener.
I would give a dialog-related class a public DataObject getDataObject() method that the calling code can call once the dialog returns, allowing the class that displays the dialog to extract the pertinent information when needed.
Whatever you do, there is no reason to use static fields and many reasons not to. I strongly urge you to not even consider this.
For example of a modal dialog that returns:
// caveat: code has not been tested by compilation or running.
JButton myButton = new JButton(new AbstractAction("Show Dialog Button") {
public void actionPerformed(ActionEvent evt) {
MyDialogPanel myDialogPanel = new MyDialogPanel();
JDialog myDialog = new JDialog(myJFrame, "My Dialog",
ModalityType.APPLICATION_MODAL);
myDialog.add(myDialogPanel);
myDialog.pack();
myDialog.setLocationRelativeTo(myJFrame);
myDialog.setVisible(true);
// dialog now returns and we can get the data
// assuming that the wrapper object for your data
// is called "DataObject"
DataObject dataObject = myDialogPanel.getDataObject();
// and perhaps use it. Assume setDataObject is a method
// of the main GUI that displays the data object
setDataObject(dataObject);
}
});
I am using Java's Swing here to make a UI application. I have a created a JFrame, with some buttons. When I click on this button, I want a new JFrame with some different content at this place. However, I do not want a new JFrame to load here.
One approach, I know is of setting the visbility of the second JFrame to be True in the actionPerformed(ActionEvent obj) method of the button in the first JFrame. But it again loads a new JFrame and I don't want that.
public class FirstUI extends JFrame {
JButton but1;
public FirstUI(){
but1= new JButton("Click here");
add(but1);
XYZ obj= new XYZ():
but1.addActionListener(obj);
}
public class XYZ implements ActionListener{
public void actionPerformed(ActionEvent obj1){
// WHAT TO DO HERE
}
}
}
I only want a single JFrame whose content changes as we click on different buttons. How can I achieve that ?
Have a look at CardLayout, this would allow to switch the content of your frame:
A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.
See How to Use CardLayout for an example.
You can also dynamically manipulate the contents of your JFrame at runtime. You can use add(...), remove(...), removeAll(...) methods to add and remove the contents as you do before showing the frame. After you're done you need to call revalidate() and repaint() methods of the modified container to make everything settle down and displayed properly.
However I think the right solution depends on the actual concept you are trying to implement. If you want to add or remove a couple of GUI elements to emphasize a functionality, then the correct way is to manipulate the container as I outlined. But if you want slightly different GUI depending on system state (not more then 2-3) then CardLayout would be a better suited choice
You can set visibility of parent class false.
Then you get only one Frame at a time with your required content.
You have to create static object of the frame and setVisible(fase) at the click event of the Button.
Ex.
public class demo {
static JFrame jf;
public static void main(String a[])
{
JButton b=new JButton("OK");
JPanel jp=new JPanel();
jf=new JFrame();
jf.setVisible(true);
jf.setSize(200,200);
jf.add(jp);
jp.add(b);
b.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e)
{
jf.setVisible(false);
JFrame f= new JFrame();
f.setSize(200,200);
f.setVisible(true);
}
});
}
}
It will help you.
you got my point?
One approach is to change the JFrame's Content Pane. which is basically a JPanel. You can do that byframe.setContentPane( <your new panel> );
The Second approach is to do what #Peter Lang did. and that is to use a Layout Manager which could change different content groups.
Does anyone know how to make a jbutton close a gui? I think it is like System.CLOSE(0); but that didnt work. it also could be exitActionPerformed(evt);, but that didn't work either. just the line of code will work.
EDIT: never mind guys. the answer was System.exit(0);. thanks for the help though!
Add your button:
JButton close = new JButton("Close");
Add an ActionListener:
close.addActionListner(new CloseListener());
Add a class for the Listener implementing the ActionListener interface and override its main function:
private class CloseListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
System.exit(0);
}
}
This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.
By using System.exit(0); you would close the entire process. Is that what you wanted or did you intend to close only the GUI window and allow the process to continue running?
The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked:
this.dispose();
If you are using the NetBeans GUI designer, the easiest way to add this actionListener is to enter the GUI editor window and double click the JButton component. Doing this will automatically create an actionListener and actionEvent, which can be modified manually by you.
See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.
The 'button' to invoke this operation is already on a frame.
See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.The JRE will end after all 3 frames are closed by clicking the X button.
You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.
The System.exit(0) will terminates the currently running Java Virtual Machine.
In Java 8, you can use Lambda expressions to make it simpler.
Close application
JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> System.exit(0));
Close window
JButton btnClose = new JButton("Close");
btnClose.addActionListener(e -> this.dispose());
Create a method and call it to close the JFrame, for example:
public void CloseJframe(){
super.dispose();
}
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for #override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */