Closing a JFrame using a button in eclipse - java

I'm a rookie when it comes to programming. We have this project about a log-in profile account. I just started doing it; and I came across a specific problem. I want to close a frame using a button.
buttonenter.setText("Enter");
buttonenter.addActionListener(new ActionListener (){
public void actionPerformed (ActionEvent ae){
}
});
I tried placing my frame.dispose();, set.Visible(false) etc. but i just got an error. I don't quite get. I really appreciate the help! Thank you!

Here's a simple example of what you're trying to do. What errors are you receiving?
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnClose = new JButton("CLOSE");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
frame.getContentPane().add(btnClose, BorderLayout.NORTH);
}

from JButtons ActionListener you can to call
JFrame#dispose(); (terminating current JVM)
JFrame#setVisible(false); (hide JFrame)
System.exit(0); (terminating current JVM)
and/or with (another standard ways are)
setDefaultCloseOperation();
add WindowListener and override proper event windowClosing();

when you close any objects by false visible, actually you just hide that object whereas the object stays in the memory yet.
you better use the
frame.dispatchEvent(new windowEvent(frame,windowEvent.window_closeing)); method

Related

GUI won't open when button pressed (Java)

I am trying to open a GUI from my main GUI by pressing a button. When the button is pressed, this is executed:
WorkloadFactor wf = new WorkloadFactor();
wf.setVisible(true);
This doesn't open the WorkloadFactor GUI. I am confused by this because I have other GUIs that open this way without issue.
WorkloadFactor class works fine when I run it by itself but won't open when it is called by my main GUI. Below is my class without imports and stuff:
public class WorkloadFactor extends JPanel {
public WorkloadFactor() {
setLayout(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
String[] tabnames = { "Zero", "One", "Two", "Three", "Four" };
for (int i = 0; i < tabnames.length; i++) {
tabbedPane.addTab(tabnames[i], createPane(tabnames[i]));
}
tabbedPane.setSelectedIndex(0);
JButton submit = new JButton("Submit All");
submit.setForeground(Color.RED);
add(tabbedPane, BorderLayout.CENTER);
add(submit, BorderLayout.SOUTH);
}
public JPanel createPane(final String t) {
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//setContentPane(contentPane); I think this might be it?
contentPane.setLayout(null);
setBounds(100, 100, 531, 347);
//***** all the components I am including then add them like so
//******contentPane.add(checkbox1);
//****** contentpane.add(label1);
return contentPane;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Set Workload Factor Information");
frame.getContentPane().add(new WorkloadFactor());
frame.setBounds(100, 100, 531, 347);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
I have tried arranging things in so many ways, putting everything in the constructor and other changes but can't seem to find a reason why instantiating this WorkloadFactor class elsewhere and setting it visible won't work.
Does it have something to do with setContentPane(contentPane) vs contentPane.add(xxxx) and returning it?
Thank you for reading!
WorkloadFactor wf = new WorkloadFactor();
wf.setVisible(true);
To be blunt, this won't display anything. Please understand that WorkloadFactor extends JPanel and like all non-top level components must be placed into a container that is ultimately held by a top-level window in order to be displayed. Look at how you display it in your main method -- you first put it into a JFrame, and then display that JFrame. You must do the same thing if you want to display it on button press -- you need to put it into a JPanel or other container that is held by a JFrame or JDialog, or JOptionPane.
Make sure that you have properly registered the button on your main GUI which opens WorkLoadFactor GUI to an action listener.
Since you have not included code from your main GUI I can't confirm this is the issue. However it is a commonly overlooked issue.
Heres some suggestions from the Java documentation tutorials:
"Problem: I'm trying to handle certain events from a component, but the component isn't generating the events it should.
First, make sure you registered the right kind of listener to detect the events. See whether another kind of listener might detect the kind of events you need.
Make sure you registered the listener on the right object.
Did you implement the event handler correctly? For example, if you extended an adapter class, then make sure you used the right method signature. Make sure each event-handling method is public void, that the name spelled right and that the argument is of the right type."
source: Solving Common Event-Handling Problems
Make a JFrame and add a JButton in it than add action listener in button and add this code in it like this:
This code makes a frame with a button and when button is pressed new window is opened.
public class Example extends JFrame {
public Example() {
super("Title");
setLayout(new FlowLayout());
JButton b = new JButton("Open new Frame");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newWindow nw = new newWindow();
}
});
add(b);
}
}
newWindow Code:
public class newWindow extends JFrame {
newWindow() {
super("title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
}
}

JFrame stuck, i can't move across sreen

I made a frame with some labels and a button on it, created an executable ear and now when i start it i can't move the application on my screen. Sometimes it works, sometimes it doesn't. I just can't drag the thing..
JFrame frame = new JFrame("Name");
frame.setPreferredSize(new Dimension(260, 160));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
frame.add(exitButton, BorderLayout.SOUTH);
frame.add(vertBox, BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
frame.setLocationRelativeTo(null);
Any ideas what's wrong? It's really annoying that i can't move it.
P.S. There is a code part that i skipped, where i made the labels and added them
Perhaps (in the code you didn't show) you were disabling your frame through
frame.setEnabled(false);
PS: I know it has been 2 years since you asked the question, but it might help someone else

How can I minimize/iconify a JWindow in Java?

My app has a JWindow that needs to be minimized when the custom minimizer button clicked.
Please reply if anyone knows how to minimize a JWindow. I have searched a lot but couldn't find any suitable method to minimize.
I know how to minimize a JFrame. So please don't bother answering regarding JFrame.
Thanks.
I know you don't want to hear this, but the terrible truth is that there is no big difference between undecorated jframes (with setstate methods) and jwindows... :)
JFrame f = new JFrame("Frame");
f.setUndecorated(true);
Due to the fact that a JWindow is not decorated with any control icons, no setState method is provided. One workaround is to allow your custom minimizer button to set the window visible as required:
public class JWindowTest extends JFrame {
JWindow window = new JWindow();
JButton maxMinButton = new JButton("Minimize Window");
public JWindowTest() {
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maxMinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (window.isVisible()) {
maxMinButton.setText("Restore Window");
} else {
maxMinButton.setText("Minimize Window");
}
window.setVisible(!window.isVisible());
}
});
add(maxMinButton);
window.setBounds(30, 30, 300, 220);
window.setLocationRelativeTo(this);
window.add(new JLabel("Test JWindow", JLabel.CENTER));
window.setVisible(true);
}
public static void main(String[] args) {
new JWindowTest().setVisible(true);
}
}

Closing a swing application once code is complete

This is no doubt a simple question for expert 'swingers' but after some research I've not come up with anything.
I have code in this form:
public static void main(Strings[] args) {
final JFrame frame = new JFrame("Symbol Formatter");
final JButton button = new JButton("Begin");
final JFileChooser filechoose = new JFileChooser();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
filechoose.showOpenDialog(frame);
filename = filechoose.getSelectedFile();
doSomething(filename);
button.setEnabled(false);
frame.setVisible(false); //edit for Andrew Thompson
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.pack();
frame.setSize(250, 75);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
I want to close the swing application once doSomething(filename) is completed. At the moment, the original frame remains where it is and the application only terminates when the frame is closed manually. How can I close once doSomething(filename) has run once.
I'm sure this is a simple question and just requires changing setDefaultCloseOperation however, the Jframe documentation hasn't helped me much.
Also, is there a way to add a title to the showOpenDialog? So that is has something like "Choose library file" as the title
You could use:
frame.dispose()
Call..
frame.setVisible(false);
I believe if you change the default close operation to
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calling dispose should terminate the application & exit the JVM.
If that fails, as has been mentioned, call System.exit(0) will certainly terminate te JVM
For the file chooser dialog title, see the javadoc.

I have a JLabel that doesn't want to update

I've looked at other JLabel threads and though similar, a few just don't seem to apply to what I'm experiencing. First, I want to say I am a novice when it comes to Java. Next, I am trying to follow tutorials and demos at the docs.oracle.com site. Now, I can update the label when I type something into a JTextField and there is an ActionListener on that...
But I also have a Menu, and when I select a Menu Item, that Action does not want to update the label.
Questions -
How do I have action listeners on both JTextFields and JMenuItems? Are there two ActionEvent methods or do I use one method and somehow identify each type of action?
If I use the same basic code in the JTextField ActionEvent and JMenuItem ActionEvent, the JLabel updates correctly with the JTextField event but not JMenuItem event. They both use the messageField.setText property. Could the JMenuItem action be doing something to block the setText?
I can easily copy code in here, but it's pretty spaghetti-like at the moment, so if you want to see anything, let me know specifically and I'll post it.
I would appreciate any assistance that anyone would be able to provide.
---edit---
Wow!! Thanks for all of the comments and suggestions.
1 - I know it has to be my code. As I mentioned, I am really just cobbling stuff together from demos and tutorials, and trying to learn Java along the way. I've just never gotten the hang of object oriented....
2 - I do know the individual Listeners are working. I'm using System.out.println to validate, as well as inspecting those labels in debug mode to see they have indeed changed.
3 - I will look at the various links and code posted here and see if I can figure out what's wrong with my code.
Really, thanks again!
---edit---
Here is what I originally had in my createAndShowGUI method....
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Create XML for Photo Gallery");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(new CreateGalleryXML());
frame.pack();
frame.setVisible(true);
}
Seems like you yourself are doing something wrong, in your code. Without a proper SSCCE it's hard to say what thing you doing wrong, since it works perfectly, using same ActionListener for both JMenuItem and JTextField.
Here is a sample program to match with yours :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateLabel
{
private JLabel label;
private String labelText;
private ActionListener action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
setLabelText((String) ae.getActionCommand());
label.setText(getLabelText());
}
};
private void setLabelText(String text)
{
labelText = text;
}
private String getLabelText()
{
return labelText;
}
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("Update Label");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JMenuBar menuBar = new JMenuBar();
JMenu programMenu = new JMenu("Program");
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
frame.dispose();
}
});
JMenu labelMenu = new JMenu("Label");
JMenuItem updateMenuItem = new JMenuItem("Update Label");
updateMenuItem.setActionCommand("Updated by JMenuItem");
updateMenuItem.addActionListener(action);
programMenu.add(exitMenuItem);
labelMenu.add(updateMenuItem);
menuBar.add(programMenu);
menuBar.add(labelMenu);
frame.setJMenuBar(menuBar);
JPanel contentPane = new JPanel();
label = new JLabel("I am the LABEL which will be updated!!");
contentPane.add(label);
JTextField tfield = new JTextField(10);
tfield.setActionCommand("Updated by JTextField");
tfield.addActionListener(action);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(tfield, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new UpdateLabel().createAndDisplayGUI();
}
});
}
}
And here is the output in both the cases :
and
Do check out the main method, might be you had failed to put your code inside EDT - Event Dispatcher Thread, that can lead to such issues too. All updates on the Swing GUI, must be done on the Event Dispatcher Thread.
LATEST EDIT
It seems to me that CreateGalleryXML extends JPanel by the look of it. See at Line 3 of this below code taken from your update, here you are initializing a new Object of CreateGalleryXML inside, when you already had one Object window created at Line 1:
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(new CreateGalleryXML());
So try to change the above thingy to this
CreateGalleryXML window = new CreateGalleryXML();
frame.setJMenuBar(window.createMenuBar());
frame.add(window);
and see what happens and Please do revert back again :-)
Use Action to encapsulate common functionality that must be shared by menus and related components. See this example that extends AbstractAction.
Pretty much everything you could need to know is in the Java tutorials. Down the bottom they have demo's on how to do both menu's and text fields. They include source code to look at as well.
There's not much more I can say that they don't say better, but in answer to your questions:
Both, you can have separate listener's on each component, or one that figures out what component is responsible for causing the action event. I would suggest you use separate ones for each thing.
Can't really say with out seeing the code, are you sure that the action on the JMenu is even firing? Does it print something to the console etc if you use System.out.println somewhere?

Categories