In netbeans I have a JDialog with a JPanel component (called Keypad). I simply draged and droped the JPanel Keypad onto JDialog and netbeans generated the code. On the Keypad I have an Enter button for which I am trying to detect ActionPerformed (button pressed) in the JDialog. Is this possible and how do I do it?
You have to add an ActionListener to your Enter button. You need to pass a reference to your JDialog in the JPanel constructor so you can communicate with it. You either need to implement ActionListener or you can use an anonymous class:
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do something to your JPanel reference
}
});
Related
public class myWindow extends JFrame implements ActionListener{
if i have this code my class will be a JFrame where where I can add component and add actionlistener to them in my constructor as followed
public MyWindow()
{
JButton b = new Jbutton("button");
b.addActionListener(this);
}
this keyword will work as an anonymous actionlistener object(which is my class) right ?
later on i will override the actionPerformed method with the heading:-
public void ActionPerformed(ActionEvent ae)
{ :
:
}
I really have a big confusion here .. my book says "the listener object invokes an event handler method with the event as an argument "
listener object : this
event handler method :ActionPerformed(ActionEvent ae)
argument: my event is the JButton b .. how come when it's not of EventAction type ? And if so why we are using :
ae.getActionCommand();
I thought it's a method to tell which component fired the event,why we need it when the component is passed as an argument then?
this keyword will work as an anonymous actionlistener object(which is my class) right ?
No this will be an Object of class which is implementing the actionsListener. In your case it is "MyWindow".
my event is the JButton b .. how come when it's not of EventAction type ? And if so why we are using :
JButton b is a component not an event. Events describes the changed in state of the source. When users interact with GUI, events are generated like clicking of button, moving the mouse.
Reference from Click here
Event Handling is a mechanism that controls the event and decides what should happen if an event occurs.
Steps involved in event handling:-
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.
I thought it's a method to tell which component fired the event,why we need it when the component is passed as an argument then?
Now you would have understood that there could be many buttons registered to the same ActionsListerner. Now to perform different actions for different events,
e.getActionCommand() comes handy, it will tell you which button is the source of firing the event.
Hope this helps.
I have tried to give you can example of a simple JButton program.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonSwing {
private int numClicks = 0;
public Component createComponents() {
//Method for creating the GUI componenets
final JLabel label = new JLabel("Clicks: " + "0"); //final so that i can access inside inner class
JButton button = new JButton("Simple Button");
button.addActionListener(
//inner class for ActionListener. This is how generally it is done.
new ActionListener() {
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText("Clicks: " + numClicks);
System.out.println(e.getActionCommand());
System.out.println(e.getModifiers());
System.out.println(e.paramString());
}
}
);
JPanel pane = new JPanel(); //using JPanel as conatiner first.
pane.setLayout(new FlowLayout());
pane.add(button); // adding button to the JPanel.
pane.add(label); // adding label to the JPanel.
return pane;
}
public static void main(String[] args) {
JFrame frame = new JFrame("SwingApplication");
ButtonSwing obj = new ButtonSwing();
Component contents = obj.createComponents();
frame.getContentPane().add(contents);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack(); //It will cause the window to be sized to fit the preferred size
//and layouts of its subcomponents.
frame.setVisible(true);
}
}
Your JButton is a component not an event. Events are generated by some action on components in this case When you click your button, an ActionEvent will be fired and it will be passed to all the listeners who subscribed to that event in this case it is your MyWindow object which is serving as an ActionListener
Im having problem with this code , it doesn't compile . Could you help me ?
I need to close the JFrame when i click the button
public class SlotMachine extends JFrame
{
/*
*
*/
JButton btnExit = new JButton("Exit");
btnExit.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
this.dispose();
}
});
}
The error is = The method dispose() is undefined for the type new MouseAdapter(){}
I dont know how to get the SlotMachine object from the mouseClicked method
You're calling this.dispose(); the key here being that this refers to the inner class, the MouseListener, and MouseListener doesn't have a dispose() method.
Solution: get rid of this, and it should work, since the compiler will then look into the outer class if the inner class does not contain the method. Alternatively you could specify which this you mean: SlotMachine.this.dispose(); will tell the compiler to call the method of the outer SlotMachine class.
Use an ActionListener on a JButton for several reasons:
Default behavior of buttons is to be activated by spacebar press if the button has focus. This will not work for a MouseListener.
Also an expected behavior is that if the button is disabled via setEnabled(false), then pressing it should not cause the action to be fired. This does not work with MouseListener but does with ActionListener.
You can easily share the ActionListener (or better yet, an AbstractAction) with other components including JMenuItems.
i am working in JAVA GUI project with netbeans ,,
I just created Jframe and put a button on it ,,
I created also another JFrame and added many labels
I am asking how can the second JFrame appears when i click on the button in the first JFrame
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SecondFrame().setVisible(true);
FirstFrame.this.dispose(); // if you want the first frame to close
}
Check out How to Write an Action Listener for more information.
I am currently studying Java to improve myself. I have a program which has a main window, menu and submenus.
I have other windows on when I click on my submenus.
One of them is setRates which is
public SetMyRates(){
JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6));
dataPanel.add(setTLLabel);
dataPanel.add(setDollarsLabel);
dataPanel.add(setTLField);
dataPanel.add(setDollarsField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(closeButton);
buttonPanel.add(setTLButton);
buttonPanel.add(setDollarsButton);
Container container = this.getContentPane();
container.add(dataPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
setTLButton.addActionListener(new SetTL());
setDollarsButton.addActionListener(new SetDollars());
closeButton.addActionListener(new closeFrame());
dataPanel.setVisible(true);
pack();
}
and I want that window to close when I click on my closeButton.
I made a class for closeButton, actionListener which is:
private class closeFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
dispose();
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please enter correct Rate.");
}
}
}
But when I click that button, it closes my main window instead of my submenus window. What should I exactly do to fix the problem?
You need to get a reference to the Window that you want to close and call dispose() directly on that reference. How you do this will depend on the details of your program -- information that we're currently not privy to.
Edit: one way to get that reference is via SwingUtilities.getWindowAncestor(...). Pass in the JButton reference returned from your ActionEvent object and call dispose on it. Something like...
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o instanceof JComponent) {
JComponent component = (JComponent)o;
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
caveat: code neither compiled nor run nor tested in any way.
Also note that for this to work, the component that holds and activates the ActionListener has to reside on the Window that you wish to close, else this won't work.
From what I think you could easily when opening an another window just store a reference to it and use it inside the action listener. Something along these lines:
JFrame openedWindow;
//inside the listener
if(openedWindow)
openedWindow.dispose();
else dispose();
I am creating a java application which consists of two frames(JFrame1 and JFrame2)
JFrame1 has a grid 6x6 button; and JFrame2 has 6 radio buttons representing colours. How can I link the two frames so that when a button in JFrame1 is clicked, JFrame2 pops up and when a colour is chosen from that the JFrame2 closes and the clicked button gets the respective colour?
It is better to have one JFrame for every application. Use one for the 6x6 JButtons and create a modal JDialog for your color JRadioButtons.
The color selection JDialog should have a public getSelectedColor() method in order to return the selected color to the caller class.
Instantiate the ColorDialog in main and do not set it visible.
The ActionListener of each JButton should make the modal JDialog visible.
The RadioButton ActionPerformed should set the selected color and make the JDialog invisible.
Call getSelectedColor() and apply the returned color to your JButton.
In your frame1's button action listner, you can do something like this
public void actionPerformed(ActionEvent e) {
Frame2 frame = new Frame2(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
where "this" refers to the frame1 object. This is you can access its jTEXTFIELD and jBUTTONs from the second frame. So naturally you have store it in Frame1 object declared in your second class.
Suppose you have a clickable color field in frame2 object, once you click on it, you should trigger a function that get the input field from frame1 (using your locale object reference) and store it in it. something like this:
public void actionPerformed(ActionEvent e) {
frame1.getMyTextField().setText(WHAT_THE_CLICKED_ON);
this.close();
}
Sorry if I made any syntax errors, it's been a long time I didnt work with java :)
Just create another class, let us say FrameMananger, then use the singleton pattern to manage them.
Then in any class, you can use FrameManager.getFrame1() to get the frame1, same as the frame2. You can add logic judgement inside, like dynamically dispose some frame or only create them when needed.
This issue is fairly common concept when you create a game and try to navigate between your every view(like the show score panel from everywhere).
public class FrameManager
{
Frame1 frame1;
Frame1 frame2;
public static Frame1 getFrame1()
{
if(frame1 == null)
frame1 = new Frame1();
return frame1;
}
public static Frame1 getFrame2()
{
if(frame2 == null)
frame2 = new Frame1();
return frame2;
}
public class Frame1 extends JFrame
{
}
public class Frame2 extends JFrame
{
}
}