简体   繁体   中英

How to click in an internal frame of JFrame, without using a button

I'm currently making an application using Internal Frames, and I don't want to use buttons in the internal frame. I want it to understand where I am clicking (specific coordinates), and complete and action based on the location of the click.

This is one of the internal frames that I am currently trying to get he mouse clicks to register on.

package com.xxemu.main;

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

import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;

public class Techni extends JInternalFrame implements InternalFrameListener, MouseListener {

    private static final long serialVersionUID = -7905672790566329537L;
    static int openFrameCount = 0;
    private ImageIcon image;
    private JLabel label;
    private Menu menu;
    public int frame = 1;
    static final int xOffset = 75, yOffset = 90;

    public Techni() {
        super("emu",
        true, //resizable
        true, //closable
        true, //maximizable
        true); //iconifiable
        //setSize(783, 522);
        setSize(400, 400);

        setLocation(xOffset, yOffset);
    }
    public void setLayeredPane(JLayeredPane layered) {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                System.out.println("asdfsd");
                if (e.getX() < 0 && e.getY() > 0) {
                    System.out.println("test");
                }

            }
        });
    }@Override
    public void internalFrameActivated(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameClosed(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameClosing(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameDeactivated(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameDeiconified(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameIconified(InternalFrameEvent arg0) {}

    @Override
    public void internalFrameOpened(InternalFrameEvent arg0) {}@Override
    public void mouseEntered(MouseEvent e) {}@Override
    public void mouseExited(MouseEvent e) {}@Override
    public void mousePressed(MouseEvent e) {}@Override
    public void mouseReleased(MouseEvent e) {}@Override
    public void mouseClicked(MouseEvent e) {}
}

Emulator class

package com.xxemu.main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;


public class Emulator extends JFrame implements ActionListener {


    private static final long serialVersionUID = 1922575930226682951L;
    JDesktopPane desktop;
    private boolean running = true;
    private Menu menu;
    private Techni techni;

    public enum STATE {
        techniMenu,
        p5Menu,
    };

    public static STATE emuState = null;

    public Emulator() {
        super("Emu");
        int inset = 50;
        setBounds(inset, inset,
        1000,
        800);

        desktop = new JDesktopPane();

        setContentPane(desktop);
        setJMenuBar(createMenuBar());

    }

    protected JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        //Set up the lone menu.
        JMenu menu = new JMenu("Options");
        menu.setMnemonic(KeyEvent.VK_O);
        menuBar.add(menu);

        //Set up the first menu item.
        JMenuItem menuItem = new JMenuItem("Technicolor");
        menuItem.setMnemonic(KeyEvent.VK_N);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_T, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("techni");
        menuItem.addActionListener(this);
        menu.add(menuItem);

        //Set up the second menu item.
        menuItem = new JMenuItem("P5");
        menuItem.setMnemonic(KeyEvent.VK_N);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_P, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("p5");
        menuItem.addActionListener(this);
        menu.add(menuItem);

        //Set up the third menu item.
        menuItem = new JMenuItem("Quit");
        menuItem.setMnemonic(KeyEvent.VK_Q);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
        KeyEvent.VK_Q, ActionEvent.ALT_MASK));
        menuItem.setActionCommand("quit");
        menuItem.addActionListener(this);
        menu.add(menuItem);

        return menuBar;
    }

    //React to menu selections.
    public void actionPerformed(ActionEvent e) {
        if ("techni".equals(e.getActionCommand())) { //new
            emuState = STATE.techniMenu;
            System.out.println("testasdfas");
            createFrameTechni();
        } else if ("p5".equals(e.getActionCommand())) { //new
            createFrameP5();
        } else {
            quit();
        }
    }

    //Create a new internal frame.
    protected void createFrameTechni() {
        Techni frame = new Techni();
        frame.setVisible(true);
        desktop.add(frame);
        try {
            frame.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {}
    }
    protected void createFrameP5() {
        P5 frame = new P5();
        frame.setVisible(true);
        desktop.add(frame);
        try {
            frame.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {}
    }
    public synchronized void start() {
        if (running) return;
        running = true;
    }

    protected void quit() {
        System.exit(0);
    }

    public void run() {
        long lastTime = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        long timer = System.currentTimeMillis();
        int updates = 0;
        int frames = 0;
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while (delta >= 1) {
                tick();
                updates++;
                delta--;
            }

            if (System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println("FPS: " + frames + " TICKS " + updates);
                frames = 0;
                updates = 0;
            }
        }
        stop();
    }
    private void tick() {
        menu.tick();
    }
    public synchronized void stop() {

    }

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        Emulator frame = new Emulator();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }


}

You can add a MouseListener to a Component instance, which has a mouseClicked event with x and y coordinates.

Example:

component.addMouseListener(new MouseAdapter() {

    @Override
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int xOnScreen = e.getXOnScreen();

        int y = e.getY();
        int yOnScreen = e.getYOnScreen();
    }

});

I have a method that I used while writing a GUI that displays your mouse coordinates inside of a frame.

private static void debugMousePosition(JFrame frame) {
    final JFrame box = new JFrame("Mouse Position");
    box.setAlwaysOnTop(true);
    box.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    box.setLocation(frame.getX() + 800,frame.getY());
    box.setSize(300, 100);
    box.setLayout(new GridLayout(1,2));
    box.setVisible(true);
    final JLabel X = new JLabel();
    final JLabel Y = new JLabel();
    frame.addMouseMotionListener(new MouseAdapter() {
        public void mouseMoved(MouseEvent me) {
            X.setText(String.valueOf("X Position: " + me.getX()));
            Y.setText(String.valueOf("Y Position: " + me.getY()));
            box.repaint();
        }
    });
    box.add(X);
    box.add(Y);

}

You pass the frame you which to monitor to the debugMousePosition() method.

It seems that you want to use a MouseActionListener, to see when the user clicks, and then onClick would get the mouse information from a MouseMotionListener. So something like

frame.addMouseListener(new MouseAdapter(){

   @Override
   public void mouseClicked(MouseEvent e)
   {
       if(e.getX() == someVariable && e.getY() == anotherVariable)
       {
          do something here
       }
   }
});

If you need more functionality, like when the mouse leaves the frame, take a look at the MouseAdapter() class to see the other methods that it has.

When you implement classes, such as InternalFrameListener, you are required to override the methods included in it. Instead of this, try to just import the Adapter versions, and when you need them create a new adapter from it. Like my above code, you'd do something similar with InternalFrameAdapter.

Here is what I would suggest your class look like:

package com.xxemu.main;
import java.awt.Menu;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;

public class Techni extends JInternalFrame
{

    private static final long serialVersionUID = -7905672790566329537L;
    static int openFrameCount = 0;
    private ImageIcon image;
    private JLabel label;
    private Menu menu;
    public int frame = 1;
    static final int xOffset = 75, yOffset = 90;

    public Techni()
    {
        super("emu",
              true, //resizable
              true, //closable
              true, //maximizable
              true);//iconifiable
        //setSize(783, 522);
        setSize(400, 400);

        setLocation(xOffset, yOffset);
    }

    public void setLayeredPane(JLayeredPane layered)
    {
        addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                System.out.println("asdfsd");
                if (e.getX() < 0 && e.getY() > 0)
                {
                    System.out.println("test");
                }

            }
        });
    }
}

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