how to know when an action happened in the my program - java

I write a program in java and used a several components that takes action(actionListener) in my program.
I want to know when any action happened by this component. For example when I clicked the button or a menu item , call a method.
public class ButtonFrame extends JFrame
{
private JButton plainJButton; // button with just text
private JButton fancyJButton; // button with icons
public ButtonFrame()
{
super( "Testing Buttons" );
setLayout( new FlowLayout() ); // set frame layout
plainJButton = new JButton( "Plain Button" );
add( plainJButton );
fancyJButton = new JButton( "Fancy Button");
add( fancyJButton );
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
fancyJButton.addActionListener( handler );
plainJButton.addActionListener( handler );
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( ButtonFrame.this, String.format(
"You pressed: %s", event.getActionCommand() ) );
}
}
}

Use event.getSource() to differentiate between registered components.
Example -
if(plainJButton == event.getSource()){
// do stuff (e.g. show message dialog, invoke method, and etc.)
}
else if(fancyJButton == event.getSource()){
// do stuff (e.g. show message dialog, invoke method, and etc.)
}
else{
// ut-oh..time to panic!
}

You can use getSource() on the event.

Related

Can you put an action listener inside an action listener?

When I press button labeled "one", my popup window freezes up, and I think it's because I'm trying to put a button with an action listener into the action listener of another button. Is that possible?
//code...
one = new JButton("Customize Race");
one.setBounds(30,200,200,75);
one.addActionListener(new ActionListener(){
#Override
public void actionPerformed( ActionEvent e ) {
one.setVisible(false);
Boolean pic = true;
String Player1 = "Player1";
while (pic == true)
{
p1 = new JButton(Player1);
p1.setBounds(50, 50, 200, 100);
p1.addActionListener(new ActionListener(){
#Override
public void actionPerformed( ActionEvent e ) {
// code that will pull up menu to
customize string value of Player1
}
});
next1 = new JButton("Next =>");
next1.setBounds(50, 375, 450, 50);
next1.addActionListener(new ActionListener(){
#Override
public void actionPerformed( ActionEvent e ) {
Boolean pic = false;
}
});
panel.add(p1);
panel.add(next1);
}
p1.setVisible(false);
}
});
panel.add(one);
frame.setVisible(true);
Can you put an action listener inside an action listener?
Yes you can create a component in your ActionListener and add an ActionListener to the new component.
That is not the problem.
my popup window freezes up,
while (pic == true)
The problem is you have a while loop that continues to execute.
Your ActionListener is continually creating components and adding them to the frame and the loop never ends.
Get rid of the while loop!!!
Also, when you add components to a visible frame the code should be:
panel.add(....);
panel.revalidate();
panel.repaint();
The revalidate() invokes the layout manager so the component can be positioned properly and the repaint() just makes sure all the components are repainted.

Must implement ActionListener.actionPerformed( ActionEvent )

package helloworld;
import javax.swing.*;
import java.awt.event.*;
public class helloworld extends JFrame{
public static void main( String args[] ){
JFrame frame = new helloworld();
frame.setSize( 400, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "HelloWorld" );
JPanel panel = new Panel();
frame.setContentPane( panel );
frame.setVisible( true );
}
}
class Panel extends JPanel {
private JButton button, resetbutton;
private JTextField textfield;
public Panel(){
button = new JButton( "click" );
button.addActionListener( new ButtonHandler() );
resetbutton = new JButton( "erase" );
resetbutton.addActionListener( new ResetbuttonHandler() );
textfield = new JTextField( 10 );
add( button );
add( textfield );
add( resetbutton );
}
class ButtonHandler implements ActionListener{
public void actionPerformed( ActionEvent e ){
textfield.setText( "you clicked" );
}
}
class ResetbuttonHandler implements ActionListener{
public void actionPreformed( ActionEvent e ){
textfield.setText( "" );
}
}
}
I just set up some basic code to learn a bit more about java. But I have a problem regarding my button classes.
The error says the following: The type Panel.ResetbuttonHandler must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent) Previously I also had this problem with the ButtonHandler class, somehow I solved this problem, but the ResetbuttonHandler still shows the same error, and I couldn't figure out what the differences between them were.I also tried to #Override them, but that didn't work. I've got a book about java (that is also where I'm learning from), and they do this in the exact same way. Even searched the whole internet, still didn't find the solution. I hope that someone can help me with this problem!
Please correct spelling of actionPreformed method to actionPerformed
class ResetbuttonHandler implements ActionListener{
public void actionPerformed( ActionEvent e ){
textfield.setText( "" );
}
}

Maintaining Focus While Not On Top Java

I'm looking to do something which may be impossible; in Java (1.6 running on Windows 7, since this is platform-dependent), I want to have a window appear over another window, but not steal focus from the triggering component. In the example attached below, I'd like to be able to be able to click on the text field, have the new pop up appear in front, but maintain focus on the text field. What I instead notice is that I get the panel to the front, but do not get focus on the text field again.
I'm primarily wondering if this is possible (normally the front Window has focus in Windows, so I'm leaning towards probably not). If not, but someone has opinions on a good workaround, I'm open ears.
Example:
public class PopUpExample
{
// Global toolkit listener.
enum PopUp
{
INSTANCE;
private PopUpWindow m_popUp;
private JTextComponent m_textComponent;
public void initialize(PopUpWindow p)
{
m_popUp = p;
Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener()
{
public void eventDispatched(AWTEvent e)
{
// Ensure event is a focus gain event.
if (( e instanceof FocusEvent )
&& ((FocusEvent)e).getID()==FocusEvent.FOCUS_GAINED)
{
// If it is on a text field, make the pop up appear, but maintain focus on the text field
if ( (e.getSource() instanceof JTextComponent) )
{
m_textComponent = (JTextComponent)e.getSource();
// FIXME Code below here should set the button on top, yet leave the text field with focus.
m_popUp.setAlwaysOnTop( true );
m_popUp.setFocusable( false );
m_popUp.setVisible( true );
m_textComponent.requestFocus();
// end FIXME
}
// Otherwise, make the pop up disappear (if it isn't the pop up itself).
else if (((JComponent)e.getSource()).getRootPane().getComponent(0) instanceof PopUpWindow)
{
m_popUp.setVisible( false );
}
}
}
}, AWTEvent.FOCUS_EVENT_MASK);
}
}
// Pop up window that isn't focusable
class PopUpWindow extends JFrame
{
public PopUpWindow()
{
super();
BorderLayout layout = new BorderLayout();
this.setLayout( layout );
this.setMinimumSize( new Dimension( 100, 100 ) );
JButton button = new JButton("WantOnFront");
button.setFocusable( false );
this.add( button, BorderLayout.CENTER );
this.setFocusable( false );
}
}
// Main application window.
class GuiWindow extends JFrame
{
public GuiWindow()
{
super();
BorderLayout layout = new BorderLayout();
this.setLayout( layout );
this.setMinimumSize( new Dimension( 400, 400 ) );
JButton button = new JButton("defaultFocusButton");
this.add( button, BorderLayout.CENTER );
JTextField textField = new JTextField("WantToMaintainFocusWhenClicked");
this.add( textField, BorderLayout.SOUTH );
}
}
// Setup code
public PopUpExample()
{
new GuiWindow().setVisible( true );
PopUp.INSTANCE.initialize( new PopUpWindow() );
}
public static void main( String[] args )
{
new PopUpExample();
}
}
have the new pop up appear in front, but maintain focus on the text field.
JDialog dialog = new JDialog(...);
dialog.setFocusableWindowState( false );
...
dialog.setVisible( true );

Switch between frames when select exercise in jTable

I'm building an Typing program and i have made an list with exercises to type
public class OefeningenListModel extends AbstractListModel {
private JComboBox time; //time combo box to select time
public OefeningenListModel() {
oefeningen = new ArrayList<Oefening>();
Oefening o1 = new Oefening("1", "Oefening HJ");
Oefening o2 = new Oefening("2", "Oefening KL");
Oefening o3 = new Oefening("3", "Oefening JH");
oefeningen.add(o1);
oefeningen.add(o2);
oefeningen.add(o3);
}
those exercises are shown in an jTable on my frame
public BasisSchermm() {
initComponents();
jList1.setModel(new OefeningenListModel());
and on this frame there is even add an jButton
now is my question:
i want to add a actionperformed on this button when a exercise is selected in the table and you click to button(when the exercise is selected) you move to a new frame to type the exercise but i have no idea how i can do this
to get the selected item in your JList you could do like this:
// Get the index of the selected item
int selectedIndex = jList1.getSelectedIndex();
// Get the selected item from the model
Object sel = jList1.getModel().getElementAt(selectedIndex);
or if needed you could cast it to the type you need:
Oefening selectedItem = (Oefening) list.getModel().getElementAt(selectedIndex);
to add the action listener:
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if (xItemIsSelected) {
//open 'x' frame
new xFrame().show();
}
if (yItemIsSelected) {
//open 'y' frame
new yFrame().show();
}
}
};
//add the listener to the button
button.addActionListener(actionListener);
To put you in the right direction a small piece of sample code (minus the imports) which creates a JFrame where the contents of the main panel is controlled by the selection in the JList. The example shows how to react on selection changes in the JList, and shows an alternative for constantly opening new windows, which is a terrible user experience.
public class ListSelectionExample {
private static String[] MODEL_CONTENTS = new String[]{"String1","String2","String3"};
public static void main( String[] args ) throws InvocationTargetException, InterruptedException {
EventQueue.invokeAndWait( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
//create a JList
final JList list = new JList( );
DefaultListModel listModel = new DefaultListModel();
for ( String modelContents : MODEL_CONTENTS ) {
listModel.addElement( modelContents );
}
list.setModel( listModel );
list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
//use a CardLayout to switch between different labels
final CardLayout cardLayout = new CardLayout();
final JPanel contentPane = new JPanel( cardLayout );
for ( String label_content : MODEL_CONTENTS ) {
contentPane.add( new JLabel( label_content ), label_content );
}
cardLayout.show( contentPane, MODEL_CONTENTS[0] );
//when the list selection is changed, switch the contents of the JPanel
list.addListSelectionListener( new ListSelectionListener() {
#Override
public void valueChanged( ListSelectionEvent aListSelectionEvent ) {
int selectedIndex = list.getSelectedIndex();
String modelElement = ( String ) list.getModel().getElementAt( selectedIndex );
cardLayout.show( contentPane, modelElement );
}
} );
frame.getContentPane().add( list, BorderLayout.EAST );
frame.getContentPane().add( contentPane, BorderLayout.CENTER );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
} );
}
}

KeyEvent not being generated by JFrame java?

I have a java program with a JFrame and 3 JButtons in it. I have added a keylistener to jframe. When i run the program a jframe window is opened and the first button is selected by default. My problem is that a KeyEvent is not being generated by this JFrame.
Now, besides adding a KeyListener to the jframe, i also added a KeyListener to the buttons.
Now the keyevent is being generated by the buttons.
How do I make the JFrame generate KeyEvent instead of the JButton generating them ??
Actually, my main purpose is building keyboard shortcuts for the buttons.
Have a look here How to Use Key Bindings.
An alternative to keylistener.
Here is a little Example it has a Button with focus and process a KeyEvent (F2).
On F2-clicked the Key-Binding process a ButtonClick which performed a System.out print.
public class Example {
static public void main( String[] s ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout( new BorderLayout() );
frame.setBounds( 50, 50, 600, 600 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
final JButton button = new JButton( new AbstractAction("MyButton") {
#Override
public void actionPerformed( ActionEvent e ) {
System.out.println("Button Clicked");
}
});
frame.getContentPane().add( button );
frame.getRootPane().setDefaultButton( button );
KeyStroke f2 = KeyStroke.getKeyStroke("F2");
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(f2, "clickButton");
frame.getRootPane().getActionMap().put("clickButton", new AbstractAction() {
#Override
public void actionPerformed( ActionEvent e ) {
button.doClick();
}
});
frame.setVisible( true );
// the Button has the focus
button.requestFocus();
// generate a KeyEvent 'F2'
KeyboardFocusManager.getCurrentKeyboardFocusManager().dispatchKeyEvent( new KeyEvent( frame, KeyEvent.KEY_PRESSED, 0, f2.getModifiers(), f2.getKeyCode(), f2.getKeyChar() ) );
}
});
}
}
The key event is called on the currently focused component (which is usually not the JFrame)

Categories