Java NetBeans call ActionListener with another - java

I am learning Java with GUI using JFrame, I would like to seek help regarding on how to call an ActionListener using an ActionListener. Here is some of my codes. The bottom part has the two action listeners and I added a simple comment for easy understanding.
package onlinedelivery;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu extends JFrame {
public JButton mainMenuButton;
public JButton exitButton;
public MainMenuButtonHandler mmHandler;
public ExitButtonHandler exHandler;
public static final int width = 400;
public static final int heigth = 300;
public MainMenu() {
Font bigFont = new Font("Arial",Font.BOLD,12);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mainMenuButton.addActionListener(mmHandler);
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
setTitle("Main Menu");
Container pane = getContentPane();
pane.setLayout(new GridLayout(5,2));
pane.add(mainMenuButton);
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class MainMenuButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
// ExitButtonHandler should be called here
// When I click Main Menu Button Handler, ExitButtonHandler shall perform
}
}
public class ExitButtonHandler implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
}

If both Actions logic is the same you can define just one and use it for both menu and button.
If not you can extend one action from another
public class MainMenuButtonHandler extends ExitButtonHandler {
#Override public void actionPerformed(ActionEvent e) {
// An additional logic here
super.actionPerformed(e);
}
}

You can use the doClick() method in JButton (inherited from AbstractButton)
With that alter the Handler Class of MainMenuButton like this:
public class MainMenuButtonHandler implements ActionListener {
private JButton exitButton;
public void setExitButton(JButton exitButton){
this.exitButton = exitButton;
}
#Override public void actionPerformed(ActionEvent e) {
//Do your work and invoke Click of exitButton
this.exitButton.doClick();
}
}
Also the MainMenu():
exitButton = new JButton("Exit");
exHandler = new ExitButtonHandler();
exitButton.addActionListener(exHandler);
mainMenuButton = new JButton("Main Menu");
mmHandler = new MainMenuButtonHandler();
mmHandler.setExitButton(exitButton) // newly added
mainMenuButton.addActionListener(mmHandler);

Related

How to know which jtable has a selected row [duplicate]

I have a class whitch extends JPanel:
public class ButtonPanel extends JPanel {
private label;
public ButtonPanel() {
label=new JLabel("waiting for click");
add(label);
}
public void setButtonText() {
label.setText("just clicked");
}
}
I have several instances of that class which is added to JFrame. I want to create one instanse of MouseAdapter class and then add them as a mouse listener to all of the ButtonPanel components on my JFrame. I meen:
ButtonPanel butt1 = new ButtonPanel();
ButtonPanel butt2 = new ButtonPanel();
ButtonPanel butt3 = new ButtonPanel();
//... here goes code which add ButtonPanels to JFrame
MouseAdapterMod mam = new MouseAdapterMod();
butt1.addMouseListener(mam);
butt2.addMouseListener(mam);
butt3.addMouseListener(mam);
The MouseAdapterMod class I want to be separate from the other and locate in it's own package. It should looks like this:
public class MouseAdapterMod extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
//here goes the code of calling setButtonText method of ButtonPanel component on which the event had occurred
}
}
So the problem is that I don't know how to implement mouseClicked method to make it determine which of ButtonPanel generate the event and call the corresponding to that component setButtonText() method. Is anyone know how to do that?
I know that I can achieve this by including event handling functionality in the ButtonPanel class, but thats not appropriate way for me, cuz I want to keep the class structure as I described above and have only one instance of MouseAdapterMod class for handling all of the ButtonPanels.
The MouseEvent#getSource method will return which object has been clicked:
public class MouseAdapterMod extends MouseAdapter {
// usually better off with mousePressed rather than clicked
public void mousePressed(MouseEvent e) {
ButtonPanel btnPanel = (ButtonPanel)e.getSource();
btnPanel.setButtonText();
}
}
As the comments note, you're often better off listening for mousePressed or mouseReleased rather than mouseClicked because for mouseClicked to work, the press and release must be from the same point, and if the mouse shifts even a slight amount, the click won't register.
My test program:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class MainForButtonPanel extends JPanel {
public MainForButtonPanel() {
setLayout(new GridLayout(4, 4));
MouseAdapter myMA = new MouseAdapterMod();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
ButtonPanel btnPanel = new ButtonPanel();
btnPanel.addMouseListener(myMA);
add(btnPanel);
}
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("MainForButtonPanel");
frame.getContentPane().add(new MainForButtonPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class ButtonPanel extends JPanel {
private static final int TIMER_DELAY = 2000;
private static final String JUST_CLICKED = "just clicked";
private static final String WAITING_FOR_CLICK = "waiting for click";
private static final Color CLICKED_COLOR = Color.pink;
private JLabel label;
public ButtonPanel() {
label = new JLabel(WAITING_FOR_CLICK);
add(label);
}
public void setButtonText() {
label.setText(JUST_CLICKED);
setBackground(CLICKED_COLOR);
new Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
label.setText(WAITING_FOR_CLICK);
setBackground(null);
((Timer)ae.getSource()).stop();
}
}).start();
}
}
class MouseAdapterMod extends MouseAdapter {
// usually better off with mousePressed rather than clicked
public void mousePressed(MouseEvent e) {
ButtonPanel btnPanel = (ButtonPanel)e.getSource();
btnPanel.setButtonText();
}
}

Manage JFrame Instances

In my project I've one instance of jframe1 and two instance of jframe2. Then I want to update from jframe1 txt2 component of first instance of jframe2. But when I invoke perfomaction() method it was to update the second instance of jframe2.
public class Jframe1 extends Jframe {
public jframe1() {
Performedaction() {
jframe2.txt2.setText("do it");
}
}
public class jframe2 extends Jframe {
public static JtextFiedl txt2;
public jframe2() {
}
Here is an example.. The example uses two JFrame window's and on clicking a button in one jframe, the second one's JLabel is updated. The example uses a JLabel instead of JTextField.
The mechanism uses java.util.Observer interface and Observable class to update from one window to the other one.
The example's code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TwoFramesExample {
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TwoFramesExample().start();
}
});
}
private void start() {
Frame1 f1 = new Frame1();
new Frame2(f1);
}
}
class Frame1 implements Observer {
private JLabel label;
#Override // Observer interface's implemented method
public void update(Observable o, Object data) {
label.setText((String) data); // displays new text in JLabel
}
Frame1() {
JFrame f1 = new JFrame("Frame-1");
f1.getRootPane().setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
label = new JLabel("Click button in frame-2...");
label.setFont(new Font("Dialog", Font.PLAIN, 20));
f1.add(label);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(350, 150);
f1.setLocation(200, 200);
f1.setVisible(true);
}
}
class Frame2 {
private int clicks;
Frame2(Frame1 f1) {
// Create Observable and add Observer
final MessageObservable observable = new MessageObservable();
observable.addObserver(f1);
// Display frame
JFrame f2 = new JFrame("Frame-2");
JButton button = new JButton("Press me");
button.setFont(new Font("Dialog", Font.PLAIN, 20));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "button clicks in frame-2: [" + ++clicks + "]";
observable.changeData(data);
}
});
f2.add(button);
f2.setSize(250, 150);
f2.setLocation(600, 200);
f2.setVisible(true);
}
}
class MessageObservable extends Observable {
MessageObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}

Receiving a string in Java graphics from a text box

I started to make a graphic for program I built in which to insert a name and length of a song, how do I do it in graphics? I found out how to pick up a button but I do not understand how to absorb something inserted into a text box
import java.awt.*;
import java.awt.event.*;
public class Active extends Frame {
public void init() {
ActionListener al = new MyActionListener();
TextField tf = new TextField(20);
Button b;
setLayout(new FlowLayout());
setSize(1000, 1000);
b = new Button ("first");
b.setActionCommand("First");
b.addActionListener(al);
add(b);
b = new Button ("Second");
b.setActionCommand("Second");
b.addActionListener(al);
add(b);
setVisible(true);
add(tf);
}
public Active(String caption) {
super(caption);
init();
}
public static void main(String[] args) {
Active m = new Active("Active buttons");
}
}
the main:
import java.awt.*;
import java.awt.event.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("First")) {
System.out.println("The first button was switched");
}
if(s.equals("Second")) {
System.out.println("The second button was switched");
}
}
}
I would write it with the Swing GUI Toolkit. Here is a short example of that:
public class MyPanel extends JPanel
{
private JTextField songNameField;
private JTextField songLengthField;
private JButton assignBtn;
public MyPanel()
{
this.songNameField = new JTextField();
this.songLengthField = new JTextField();
this.assignBtn = new JButton("Assign");
this.assignBtn.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent event)
{
String name = songNameField.getText();
int length = Integer.parseInt(parsesongLengthField.getText());
...
}
});
this.add(songNameField);
this.add(songLengthField);
this.add(assignBtn);
}
}

setDefaultCloseOperation doesn't work for JButton

I have created three classes:
public class Gui extends JFrame {
private final JButton buttonClose = new JButton("Close");
private final MyButtonListener buttonListener = new MyButtonListener(this);
private final MyWindowListener windowListener = new MyWindowListener();
public SwitchGuiExtListeners() {
super("Switch");
setSize(200, 150);
setLayout(new BorderLayout());
add(buttonClose, BorderLayout.EAST);
buttonClose.addActionListener(this.buttonListener);
this.addWindowListener(this.windowListener);
setVisible(true);
}
public JButton getButtonClose() {
return buttonClose;
}
}
public class SwitchGuiWindowListener implements WindowListener{
...
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
...
}
public class MyButtonListener implements ActionListener {
private final Gui gui;
public MyButtonListener (final Gui gui) {
this.gui = gui;
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == gui.getButtonClose()){
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//System.exit(0);
}
}
}
If I use the gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); my frame doesn't close. But when I use the System.exit(0) it works. Why can't I use the setDefaultCloseOperation(..)?
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); does not close a JFrame. It simply tells that the JFrame must exit when the close button on top-right corner of a window is clicked i.e., just sets the behavior but does trigger an exit.
To close a JFrame, use something like this:
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
Source: https://stackoverflow.com/a/1235994/1866196

Setting Text With Buttons

I have the following code below. My objective is to allow each button to add to the text field so that the user can input a phone number. The only thing I can't seem to get working is the field to allow multiple text input. Once you click on another button, it replaces it in the text field so only one digit at a time is present. How can I fix this so each button adds its number in without just completely replacing it? Also, why is my border manager not applying to the code? Thank you!!
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Keys
{
private JPanel phone;
public static void main (String[] args)
{
JFrame frame = new JFrame ("Keys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel phone = new JPanel();
phone.setBorder (BorderFactory.createRaisedBevelBorder());
JTabbedPane tp = new JTabbedPane();
tp.addTab ("KeyPad", new KeyPad());
frame.getContentPane().add(phone);
frame.getContentPane().add(tp);
frame.pack();
frame.pack();frame.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyPad extends JPanel
{
private JLabel resultLabel;
private JButton button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonclear;
public KeyPad()
{
setLayout (new GridLayout (5, 3));
resultLabel = new JLabel ("---");
button0 = new JButton ("0");
button1 = new JButton ("1");
button2 = new JButton ("2");
button3 = new JButton ("3");
button4 = new JButton ("4");
button5 = new JButton ("5");
button6 = new JButton ("6");
button7 = new JButton ("7");
button8 = new JButton ("8");
button9 = new JButton ("9");
buttonclear = new JButton ("Clear");
button0.addActionListener (new ButtonListener0());
button1.addActionListener (new ButtonListener1());
button2.addActionListener (new ButtonListener2());
button3.addActionListener (new ButtonListener3());
button4.addActionListener (new ButtonListener4());
button5.addActionListener (new ButtonListener5());
button6.addActionListener (new ButtonListener6());
button7.addActionListener (new ButtonListener7());
button8.addActionListener (new ButtonListener8());
button9.addActionListener (new ButtonListener9());
buttonclear.addActionListener(new ButtonListenerC());
add (resultLabel);
add (button0);
add (button1);
add (button2);
add (button3);
add (button4);
add (button5);
add (button6);
add (button7);
add (button8);
add (button9);
add (buttonclear);
setPreferredSize (new Dimension(250,250));
setBackground (Color.green);
}
private class ButtonListener0 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("0");
}
}
private class ButtonListener1 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("1");
}
}
private class ButtonListener2 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("2");
}
}
private class ButtonListener3 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("3");
}
}
private class ButtonListener4 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("4");
}
}
private class ButtonListener5 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("5");
}
}
private class ButtonListener6 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("6");
}
}
private class ButtonListener7 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("7");
}
}
private class ButtonListener8 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("8");
}
}
private class ButtonListener9 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText ("9");
}
}
private class ButtonListenerC implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
resultLabel.setText (" ");
}
}
}
In each of your actionPerformed method if should be :
resultLabel.setText (resultLabel.getText()+"theNumber");
There seems to be a lot of copy/paste in your code. Try to see if you can make it more simpler.
You can concatenate the new text on to the old text by doing something like this:
resultLabel.setText(resultLabel.getText() + "3");
This gets the current text, then appends "3" to the end of it.
First of all you should only have one ButtonListener, since every ButtonListener does the the same (except the number it should add. The following code should work:
private class ButtonListener implements ActionListener
{
private String value = "";
public ButtonListner(String value) {
this.value = value;
}
public void actionPerformed (ActionEvent event)
{
resultLabel.setText(resultLabel.getText() + value);
}
}
You can init your ButtonListeners this way:
button0.addActionListener(new ButtonListener("0"));

Categories

Resources