简体   繁体   中英

Java: Iterating through a list of JButton

I have an ArrayList of JButtons on my JPanel. All the buttons are added in a horizontal line using GridBagLayout on the JPanel as shown below.

我的 JPanel

It is made so that the focusOwner JButton has Red background and others have Green background.

I want to shift focus by users keboard. For example, if the user clicks left arrow, the focus shifts to the button present on the left of the button which has focus. Similarly, if he clicks right arrow, the focus shifts to the button on right of the focusOwner.

I also want that if the user hits Enter key, the focusOwner button get's pressed (actionListener is run).

Use key bindings to register the required actions with each JButton .
Use focus listener to change the background color of the focused and non-focused JButton s.
Usekeyboard focus manager to move the focus.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;

public class RedGreen implements ActionListener, FocusListener, Runnable {
    private JFrame  frame;

    public void actionPerformed(ActionEvent event) {
        JOptionPane.showMessageDialog(frame, event.getActionCommand());
    }

    public void focusGained(FocusEvent event) {
        event.getComponent().setBackground(Color.red);
    }

    public void focusLost(FocusEvent event) {
        event.getComponent().setBackground(Color.green);
    }

    @Override
    public void run() {
        showGui();
    }

    private JButton createButton(int index) {
        JButton button = new JButton("Ledger");
        button.setActionCommand(String.valueOf(index));
        button.addActionListener(this);
        button.setBackground(Color.green);
        button.addFocusListener(this);
        InputMap inputMap = button.getInputMap();
        ActionMap actionMap = button.getActionMap();

        KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        inputMap.put(enter, "ACTION");
        actionMap.put("ACTION", new EnterAction());

        KeyStroke rightArrow = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
        inputMap.put(rightArrow, "NEXT");
        actionMap.put("NEXT", new RightAction());

        KeyStroke leftArrow = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
        inputMap.put(leftArrow, "PREVIOUS");
        actionMap.put("PREVIOUS", new LeftAction());

        return button;
    }
    private JPanel createButtonsPanel() {
        JPanel panel = new JPanel();
        panel.add(createButton(1));
        panel.add(createButton(2));
        panel.add(createButton(3));
        panel.add(createButton(4));
        return panel;
    }

    private void showGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new RedGreen());
    }

    private static class EnterAction extends AbstractAction {
        
        @Override
        public void actionPerformed(ActionEvent event) {
            Object source = event.getSource();
            if (source instanceof JButton) {
                JButton button = (JButton) source;
                button.doClick();
            }
        }
    }

    private static class LeftAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent event) {
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusPreviousComponent();
        }
    }

    private static class RightAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent event) {
            KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            kfm.focusNextComponent();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM