Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.Timer;

public class Main {
    Component activeComponent;
    Component[] buttons;
    int index = 0;

    public Main() {
        JPanel panel = new JPanel();
        BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
        panel.setLayout(boxLayout);
        for (int i = 0; i < 40; i++) {
            panel.add(new JButton("Button " + i));
        }
        buttons = panel.getComponents();
        activeComponent = buttons[index];
        final JScrollPane scroll = new JScrollPane(panel);

        Timer timer = new Timer(500, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ((JButton) activeComponent).setForeground(Color.BLACK);
                if (index >= buttons.length - 1) {
                    index = 0;
                } else {
                    index++;
                }
                activeComponent = buttons[index];
                ((JButton) activeComponent).setForeground(Color.red);
                setView(scroll, activeComponent);
                System.out.println(((JButton) activeComponent).getActionCommand());
            }
        });
        timer.start();

        scroll.setPreferredSize(new Dimension(200, 300));
        JFrame frame = new JFrame();
        frame.add(scroll);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public void setView(JScrollPane scroll, Component comp) {
        JViewport view = scroll.getViewport();
        Point p = comp.getLocation();
        view.setViewPosition(p);
    }

    public static void main(String[] args) {
        new Main();
    }
}