
Patrick B. answered 11/14/20
Math and computer tutor/teacher
Unfortunately not as simple as that...
First , You create a Button object
Then you write the method that gets called when the button is clicked...
this is called a click event handler
Finally, you have to connect them with an EventListener, an object
that associates the click event with the method that is called
This is done different ways depending on your user interface...
Here is a java program that creates a Form Panel containing a button
that says "HELLO" when clicked
===========================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyWindow
{
static JFrame frame;
public static void main(String[] args)
{
// schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
displayJFrame();
}
});
}
static void displayJFrame()
{
frame = new JFrame("Our JButton listener example");
// create our jbutton
JButton showDialogButton = new JButton("Click Me");
// add the listener to the jbutton to handle the "pressed" event
showDialogButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// display/center the jdialog when the button is pressed
JDialog d = new JDialog(frame, "Hello", true);
d.setLocationRelativeTo(frame);
d.setVisible(true);
}
});
// put the button on the frame
frame.getContentPane().setLayout(new FlowLayout());
frame.add(showDialogButton);
// set up the jframe, then display it
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Lily P.
Ah ok thanks. I am not proficient in Java, but I understand the concept.11/15/20