GUI in java “go to previous/next” option?

只愿长相守 提交于 2019-11-29 16:48:17

Use Action "to separate functionality and state from a component." In the example below, the actions change the index and update() a JLabel from a List<String>. Your application might update a JTextArea from a List<Employee>.

package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * @see http://stackoverflow.com/a/20116944/230513
 */
public class PrevNext {

    private final List<String> list = new ArrayList<>(
        Arrays.asList("Alpher", "Bethe", "Gamow", "Dirac", "Einstein"));
    private int index = list.indexOf("Einstein");
    private final JLabel label = new JLabel(list.get(index), JLabel.CENTER);

    private void display() {
        JFrame f = new JFrame("PrevNext");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JButton(new AbstractAction("<Prev") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (--index < 0) {
                    index = list.size() - 1;
                }
                update();
            }
        }), BorderLayout.LINE_START);
        f.add(label);
        f.add(new JButton(new AbstractAction("Next>") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (++index == list.size()) {
                    index = 0;
                }
                update();
            }
        }), BorderLayout.LINE_END);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private void update() {
        label.setText(list.get(index));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new PrevNext().display();
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!