I al reading a code that I did not create and I have some trouble to understand how it is working and especially how action event ( like a click) are managed ?
So far I am undertanding that it creates a the first window will all buttons and boxes and the main end with a setVisible(true); and my window appears.
Then is ask my some file locations and I click on a button to go to the second window.
What I would like to understand it is how in java we managed this click event for the second action ? I mean I understand the use of button addActionListener the first time but my understanding ends with the second event (=I click on the button and it brings me to the second window and do the calculation) i.e. where/ how in the code this is handle and goes a scond time to the functions.
Knowing that at the end of the main I have some functions starting with
InterfaceDynamics.cardSwitch() and this function managed all events that can occur
public static void cardSwitch(final String _buttonKey, final String _Key, final JPanel _cardPanel,
Another related question (I guess related) it is the use of
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main();
which I really do not undertand (even if I already google it).
Sorry if I am not clear and for my bad understanding of java and window, Swing, Frame management and really thanks for any help.
Regards
Related
Through some searching, I made about ActionListeners and GUI. I think I have come to a conclusion that all the changes you do that affect the GUI, in the ActionListener, actually happen when ActionListener comes to it's end
I am currently making a memory game. In the action listener of a card button I first flip the image (that changes it's icon) and the I check if a have a match and in the case I don't have one I close the card(change icon).
Since those two happen in the same actionListener as a result if I dont have a match I only see the first card I pick and he second seems to no react to flip.
Sorry if it's confusing how I explain it. I think that the problem is the actionListener but maybe I am wrong. What would you suggest?
c.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae){
selectedCard = c;
String imgName = "Images/"+c.getId()+".jpg";
URL imageURL = this.getClass().getResource(imgName);
if (imageURL != null) {
ImageIcon icons = new ImageIcon(imageURL);
c.setIcon(icons);
}
c.setEnabled(false);
c.setDisabledIcon(c.getIcon());
pl.singlePlay(c);
if(pl.getMatch()==false){
for (Cards cd : cards){
if(cd.getMatched()==false){
cd.setEnabled(true);
cd.setIcon(icon);
}
}
}
});
I have come to a conclusion that all the changes you do that affect the GUI, in the ActionListener, actually happen when ActionListener comes to it's end
Yes, all code invoked from any listener executes on the Event Dispatch Thread (EDT). This thread is responsible for updating the GUI and so the GUI can't be updated until the code has finished executing. Read the section from the Swing tutorial on Concurrency for more information.
Since those two happen in the same actionListener
If you want to schedule animation, that is show one Icon and then seconds later show another Icon, then you can use a Swing Timer. The Timer allows you to schedule another event. The tutorial link from above also has a section on How to Use Swing Timers to get you started.
I seem to have a fairly unique problem, and I searched for a while for an answer on here without finding one. I have a class that has a simple JFrame with two buttons. Each button calls the Main method of a different class, as such:
checkRuling = new JButton("Check Your Deck's Rulings");
checkRuling.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
ReadHtmlCardDatabase.main(null);
}
});
One calls a class that takes a series of inputs into a text field and creates a formatted html document from the inputs, and the other loads the html document into a JEditorPane. My problem is that when I close one of the JFrames for the subclasses (either the input or html loader one), it exits my program completely, and I want to keep the main class (with the two buttons) open. I've tried using:
close = new JButton("CLOSE");
close.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
System.exit(1);
}
});
On a button in the subclasses, to no avail. When the button is clicked it simply exits everything. I've also tried using:
JFrame.DISPOSE_ON_EXIT
For the subclasses, but this causes the JFrames to go away without the subclasses actually closing, so the first one that saves the html document never actually saves it, and the second subclass that opens that same html document won't work, because it wasn't saved. Any help would be appreciated, because I can't figure out how to do this.
As Fast Snail says in the comments, you shouldn't be calling a main method. Instantiate a class that does each functonality. Set the frame to visible using setVisible(true) when you start using it, then setVisible(false) when you're done. So, in the action listener, just change the visibility.
Then, assuming you don't have anything too wild going on, the frame you just set to invisible should go out of scope and get freed so that memory isn't chewed up. You just instantiate a new copy of the ReadHtmlCardDatabase class each time you need one. Or you could have one static copy that you set visible/invisible as needed.
one of the JFrames
You should use only one JFrame in Your GUI. For other windows You can use for example JDialog or JWindow.
This should help, if not You can always use frame.setVisible(false) instead of dispose on close, but it' s not very neat.
Thanks to someone who posted a comment and then deleted it, I've figured out my own problem. I just had to replace my main call with this:
setDeck = new JButton("Set Deck");
setDeck.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
WriteHtmlCardDatabase w = new WriteHtmlCardDatabase();
w.main(null);
}
});
Thank you!
I have three classes I am working with here. The first is an admin page where the user can select to either add, update or delete an employee on the system via a drop down box. When the user selects one of the three options from the combo box, a JFrame (employees) comes up with the necessary fields to perform their task and the admin frame will still be displayed behind it. On this frame there is a "Cancel" button. When they click the cancel button only this frame must close but keep the admin frame open still. The button is generated from a separate class (empClass) to be displayed on the employee frame. My problem now is I am struggling to get the button to dispose of the employee frame, but out of the several ways of trying this it cannot work. One way produced an error each time I ran the application, another method caused the application to crash/freeze whenever I try select an option to perform on the employee frame and the code I have currently implemented performs no action at all. I think the problem is a an issue with communicating with the forms but I am not entirely sure. Please help as I have been struggling with this for hours and the internet is providing absolutely nothing useful. Most resources refer to the dispose() method which I have tried in various ways but all the ways I have tried do not work, crash the application or cause errors to occur. Even the other questions similar to this on here have not helped me out at all.
I have tried calling the button from the employee frame to try and link the function to the "Cancel" button. Here is the code I have implemented in the empClass:
public void disposeof()
{
employees empp = new employees();
empp.dispose();
}
private void cancelActionPerformed(java.awt.event.ActionEvent evt)
{
disposeof();
}
Here is the employee coding:
public class employees extends javax.swing.JFrame {
empClass ec = new empClass();
adminPage ap = new adminPage();
public employees() {
initComponents();
getContentPane().add(ec.getpanel());
this.add(ec.getpanel());
this.add(ec.lbltitle);
this.add(ec.cancel);
this.add(ec.bfunction);
this.add(ec.empList);
}
As you didn't provide the code of your JFrame so I guess problem is in the code of your JFrame. You might be setting setDefaultCloseOperation(JFrame .EXIT_ON_CLOSE) for your employee class as it is static property so it will close all JFrames. You should set it setDefaultCloseOperation(employees.DISPOSE_ON_CLOSE) OR setDefaultCloseOperation(employees.HIDE_ON_CLOSE). And after that while triggering your event you can call empp.dispose(); OR setVisible(flase).
First of all only use one JFrame and use JDialogs for the underlying other windows you may want to see appearing. On JDialog, use setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE).
Another way you can do this is to hide the frame using setVisible(false).
I am trying to find a method that can close the active JFrame.
I am unable to use frame.dispose();, as I am declaring the action listener in a toolbar class and the frames I want to close are not static and are declared at runtime.
I have tried using:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
and whilst this does work, in certain circumstances it will close more than one window even though only 1 window appears to be open, so frames will flash open and closed many times depending on what actions the user has made.
For me to fully recreate my problem would involve posting a significant amount of code which would not be in line with MCVE principles.
I am hoping someone will know of a more simple and reliable way of closing the active frame in the mould of acitveframe.dispose(); - which I now is not a real solution!!
What happens if you try to get the Window ancestor of the source of the action event? i.e.,
#Override
public void actionPerformed(ActionEvent actionEvent) {
Component comp = (Component) actionEvent.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
This won't work if the source is not a Component or if it is not contained within the top level Window of interest.
Regarding:
For me to fully recreate my problem would involve posting a significant amount of code which would not be in line with MCVE principles.
I'll bet with a bit of effort you could create and post something that comes close.
I am hoping someone will know of a more simple and reliable way of closing the active frame
In your loop you can add:
if (window.isActive())
// do something
Or maybe a simpler approach is:
Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
Also, assuming your active window is a JFrame, instead of using window.dispose(), I have used code like:
WindowEvent windowClosing = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
frame.dispatchEvent(windowClosing);
this will simulate the user clicking on the "Close" button which means that any WindowListener you added to the frame will also be executed. See Closing an Appplication for more information and ideas.
When you are declaring your JFrames, declre them as final if you cannot use static :
final JFrame f = new JFrame();
It would solve the problem.
I have written a calculator in NetBeans and it functions perfectly. However, I have to actually click the buttons to insert numbers and am trying to remedy that with a KeyListener. I have all my numbers and function buttons set inside a JPanel named buttons. I have my display label in a JPanel named display.
I set my class to implement KeyListener and it inserted the KeyPressed, -Typed, and -Released methods; however I stuck from there. I'm not sure how to make my buttons actually listen for the KeyPressed event, and when it hears the event - activate the button. Also, my buttons are named by their number (e.g. the Zero Button is named zero, One button is one, etc.).
I've read that you actually have to implement a KeyListener somewhere by using: something.addKeyListener(something);
but I cannot seem to figure this out.
Can I get some help here? I'm new to Java and this is my first solo project. And let me know if I didn't provide enough information.
EDIT: Most of my code is NetBeans Generated and I cannot edit the initialization of the components which seems to be my problem I think?
My class declaration:
public class Calculator extends javax.swing.JFrame implements KeyListener {
//Creates new form Calculator
public Calculator() {
initComponents();
}
One of my buttonPressed actions (all identical with changes for actual number):
private void zeroActionPerformed(java.awt.event.ActionEvent evt) {
if (display.getText().length() >= 16)
{
JOptionPane.showMessageDialog(null, "Cannot Handle > 16 digits");
return;
}
else if (display.getText().equals("0"))
{
return;
}
display.setText(display.getText().concat("0"));
Main method supplied by NetBeans:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator().setVisible(true);
}
});
}
The initComponents() netbeans generated is absolutely massive (about 500 lines of code) and I cannot edit any of it. Let me know if I can supply any more helpful information.
Could there be an issue of Focus, and if so how can I resolve the issue?
Yes there is probably an issue with focus. That is why you should NOT be using a KeyListener.
Swing was designed to be used with Key Bindings. That is you create an Action that does what you want. Then this Action can be added to your JButton. It can also be bound to a KeyStroke. So you have nice reusable code.
Read the Swing tutorial on How to Use Key Bindings for more information. Key Bindings don't have the focus issue that you currently have.
I'm not sure I completely understand your question, and some code would help, but I'll take a crack, since it sounds like a problem I used to have a lot.
It sounds like the reason that your key presses aren't being recognized is that the focus is on one of the buttons. If you add keylisteners to the buttons, then you shouldn't have any problem.
In netbeans you can add keylisteners through the design screen really easily.
Here's a picture showing you how to add a keyPressed listener to a button in a jPanel.
private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {
//Check which key is pressed
//do whatever you need to do with the keypressed information
}
It is nice to be able to write out the listeners yourself, but if you are just learning, then it is also nice to get as much help as possible.
This might not be the best solution, since you would have to add the listener for each of your buttons.