Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new PopupMenu());
        frame.validate();
        frame.pack();
        frame.setVisible(true);
    }
}

class PopupMenu extends Box {
    Dimension preferredSize = new Dimension(400, 30);

    public PopupMenu() {
        super(BoxLayout.Y_AXIS);
        final JPopupMenu menu = new JPopupMenu("Options");
        for (int i = 1; i < 20; i++)
            menu.add(new JMenuItem("Option" + i));

        JLabel clickMe = new JLabel("ClickMe");
        clickMe.setAlignmentX(RIGHT_ALIGNMENT);
        clickMe.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                menu.show(e.getComponent(), e.getX(), e.getY());
            }
        });
        add(clickMe);
    }

    public Dimension getPreferredSize() {
        return preferredSize;
    }
}