Ottenere fare clic su posizione in griglia. Java Swing

0

Domanda

Ho ottenuto questo codice strega crea un cliccabili griglia che mostra la posizione del mouse, anche se io non sono in grado di ottenere la posizione nella griglia in cui viene cliccato il mouse, cercando di essere sia la posizione X e Y. Tutte le idee? Questo è come la griglia look:

This how the grid looks

Codice:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;

public class TestGrid02 {


    public TestGrid02() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        private static final int ROWS = 20;
        private static final int COLUMNS = 20;
        private static GridBagConstraints gbc;

        public TestPane() {
            setLayout(new GridBagLayout());

            gbc = new GridBagConstraints();
            for (int row = 0; row < ROWS; row++) {
                for (int col = 0; col < COLUMNS; col++) {
                    gbc.gridx = col;
                    gbc.gridy = row;
                    CellPane cellPane = new CellPane();
                    Border border = null;
                    if (row < ROWS-1) {
                        if (col < COLUMNS-1) {
                            border = new MatteBorder(1, 1, 0, 0, Color.GRAY);
                        } else {
                            border = new MatteBorder(1, 1, 0, 1, Color.GRAY);
                        }
                    } else {
                        border = new MatteBorder(1, 1, 1, 0, Color.GRAY);
                    }
                    cellPane.setBorder(border);
                    add(cellPane, gbc);
                }
            }
        }
    }

    public class CellPane extends JPanel {

        private Color defaultBackground;

        public CellPane() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    defaultBackground = getBackground();
                    setBackground(Color.RED);
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    setBackground(defaultBackground);
                }
                @Override
                public void mouseClicked(MouseEvent e){
                    //Here is where it is supposed to be
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(30, 30);
        }
    }
}

Nel CellPane classe, la strega è destinato ad essere uno che ascolta il mouse si suppone che sia la funzione di cui ho bisogno, al mouseClicked ascoltatore, tuttavia ho provato con e.getX() o.e.getLocationOnScreen() e questi valori sono stati la modifica ogni volta che clicco nella stessa griglia.

java mouseevent swing
2021-11-24 00:49:45
2

Migliore risposta

1

Beh, che sembra familiare

2021-11-24 01:25:09

Sì, è dove l'ho preso da
Sebastián Bermúdez
0

Questo approccio (utilizzando i pulsanti di azione e ascoltatori) è meglio IMO. Utilizza la getButtonRowCol metodo per restituire una stringa che indica il pulsante di posizione in un array (le buttonArray).

enter image description here

Utilizzare b.setBorderPainted(false); (il commento che la riga di codice) per sbarazzarsi dei bordi di ogni pulsante. Guardare ai valori passati al costruttore di GridLayout per rimuovere lo spazio tra i pulsanti.

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

public class GameGridLayout {

    int size = 40;
    int iconSize = 10;
    JButton[][] buttonArray = new JButton[size][size];
    ActionListener actionListener;
    JLabel output = new JLabel("Click somewhere on the GUI");

    GameGridLayout() {
        JPanel gui = new JPanel(new BorderLayout(2,2));
        gui.setBorder(new EmptyBorder(4,4,4,4));
        gui.add(output,BorderLayout.PAGE_END);
        JPanel gameContainer = new JPanel(new GridLayout(0,size,2,2));
        gui.add(gameContainer);
        actionListener = e -> output.setText(getButtonRowCol((JButton)e.getSource()));
        for (int ii=0; ii<size*size; ii++) {
            JButton b = getButton();
            gameContainer.add(b);
            buttonArray[ii%size][ii/size] = b;
        }
        JFrame f = new JFrame("GameGridLayout");
        f.add(gui);
        f.pack();
        f.setMinimumSize(f.getSize());
        f.setLocationByPlatform(true);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
    }

    private String getButtonRowCol(JButton button) {
        StringBuilder sb = new StringBuilder();
        for (int xx=0; xx<size; xx++) {
            for (int yy=0; yy<size; yy++) {
                if (button.equals(buttonArray[xx][yy])) {
                    sb.append("User selected button at: ");
                    sb.append(xx+1);
                    sb.append(",");
                    sb.append(yy+1);
                    break;
                }
            }
        }
        return sb.toString();
    }

    private JButton getButton() {
        JButton b = new JButton();
        b.setIcon(new ImageIcon(
                new BufferedImage(iconSize,iconSize,BufferedImage.TYPE_INT_ARGB)));
        b.setRolloverIcon(new ImageIcon(
                new BufferedImage(iconSize,iconSize,BufferedImage.TYPE_INT_RGB)));
        b.setMargin(new Insets(0,0,0,0));
        //b.setBorderPainted(false);
        b.setContentAreaFilled(false);
        b.addActionListener(actionListener);
        return b;
    }

    public static void main(String[] args) {
        Runnable r = () -> new GameGridLayout();
        SwingUtilities.invokeLater(r);
    }
}
2021-11-24 05:07:29

In altre lingue

Questa pagina è in altre lingue

Русский
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................