Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';t让MouseListener处理六边形(生成的多边形)_Java_Swing - Fatal编程技术网

Java Can';t让MouseListener处理六边形(生成的多边形)

Java Can';t让MouseListener处理六边形(生成的多边形),java,swing,Java,Swing,我正在生成一个六边形网格,并且能够做到这一点,但是当我向单个六边形添加鼠标侦听器时(当它们被创建时),几乎就像它们在某个东西后面一样,因为在六边形上悬停/单击不会注册或做任何事情。我希望最终能够与六边形互动,但如果我不能让它工作,我就不能这样做 我的主要GUI元素: import java.awt.*; import javax.swing.*; public class Game2 { public Game2(int radius,int num_hexes) {

我正在生成一个六边形网格,并且能够做到这一点,但是当我向单个六边形添加鼠标侦听器时(当它们被创建时),几乎就像它们在某个东西后面一样,因为在六边形上悬停/单击不会注册或做任何事情。我希望最终能够与六边形互动,但如果我不能让它工作,我就不能这样做

我的主要GUI元素:

import java.awt.*;
import javax.swing.*;

public class Game2
{
    public Game2(int radius,int num_hexes)
    {
    if(num_hexes%2==0) throw new AssertionError("Can't generate map with 
    an even number of hexagons.");

    JFrame frame=new JFrame();
    JPanel panel=new JPanel();

    panel.setBorder(BorderFactory.createLineBorder(Color.RED));
    panel.setLayout(new BoxLayout(panel,1));

    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setTitle("HexGame");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    Rectangle r=frame.getBounds();
    int screen_height=r.height;
    int screen_width=r.width;

    Hexes2 hexes2=new Hexes2(num_hexes,radius,screen_width,screen_height);

    panel.add(hexes2);
    JScrollPane scroll_pane=new JScrollPane(panel);
    frame.getContentPane().add(scroll_pane);
    panel.setOpaque(false);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args)
{
    Runnable r=new Runnable()
    {
        @Override
        public void run()
        {
            new Game2(100,11);
        }
    };
    SwingUtilities.invokeLater(r);
}
}
我的多重六边形:

import java.awt.*;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JPanel;

public class Hexes2 extends JPanel
{
private static final long serialVersionUID=1L;
private static List<Polygon> hexagons;
private static int[] rows;
private int radius;

public Hexes2(int num_columns,int radius,int screen_width,int screen_height)
{
    super();

    this.radius=radius;
    hexagons=new LinkedList<Polygon>();
    rows=Functions.columns(num_columns);

    int x=screen_width/6;
    int y=screen_height/2;

    double height=radius*Math.sqrt(3);
    double range=num_columns-rows[0];

    //build by columns, first
    for(int j=0;j<num_columns;j++)
    {
        x+=((3/2)*radius)*1.5015;

        if(j<=Math.floor(num_columns/2)) y=(int) (100-(j*(height/2)));
        else y=(int) ((100-(height*(range/2))+(num_columns-rows[j])*(height/2)));

        for(int i=0;i<rows[j];i++)
        {
            y+=height;
            Hex2 hex=new Hex2(i,radius,x,y);
            hexagons.add(hex.getHex());
        }
    }
}

protected void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    setOpaque(false);

    for(int i=0;i<hexagons.size();i++)
    {
        Stroke stroke=new BasicStroke(radius/20, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke);

        g2.setColor(Color.BLACK);
        g2.drawPolygon(hexagons.get(i));
    }
}
};
import java.awt.*;
导入java.util.LinkedList;
导入java.util.List;
导入javax.swing.JPanel;
公共类Hexes2扩展了JPanel
{
私有静态最终长serialVersionUID=1L;
私有静态列表六边形;
私有静态int[]行;
私有整数半径;
公共十六进制2(整数列、整数半径、整数屏幕宽度、整数屏幕高度)
{
超级();
这个。半径=半径;
hexagons=新链接列表();
行=函数.列(num_列);
int x=屏幕宽度/6;
int y=屏幕高度/2;
双倍高度=半径*数学sqrt(3);
双范围=num_列-行[0];
//首先,按列构建

对于(int j=0;j您正在将鼠标侦听器添加到Hex2 JLabel:

public Hex2(int ID, int r, int x, int y) {
    super();
    this.ID = ID;
    hexagon = generateHex(r, x, y);
    addMouseListener(this);
}
这些是您从未添加到GUI的JLabel,因为您在此处的A行中创建它们:

    for (int j = 0; j < num_columns; j++) {
        x += ((3 / 2) * radius) * 1.5015;
        if (j <= Math.floor(num_columns / 2))
            y = (int) (100 - (j * (height / 2)));
        else
            y = (int) ((100 - (height * (range / 2)) + (num_columns - rows[j]) * (height / 2)));
        for (int i = 0; i < rows[j]; i++) {
            y += height;
            Hex2 hex = new Hex2(i, radius, x, y);  // ****** [A] *****
            hexagons.add(hex.getHex());  // ****** [B] *****
        }
    }

问题已编辑。请理解“我到处都搜索了…”语句不能帮助我们理解您在搜索中找到了什么,或者信息对您没有帮助。我们需要详细信息。您的代码不能为我们编译。什么是
函数
,什么是
函数。列(num_列)
do?最好创建并发布一个有效的对话框,以便您和我们都能更轻松地进行调试。谢谢。刚刚编辑过以显示my Functions类的功能。请参阅最新编辑以回答
new BoxLayout(面板,1)
阅读您的代码的人不会知道
1
是什么。请使用有意义的常量。谢谢!是的,这更有意义。
public Hex2(int ID, int r, int x, int y) {
    super();
    this.ID = ID;
    hexagon = generateHex(r, x, y);
    addMouseListener(this);
}
    for (int j = 0; j < num_columns; j++) {
        x += ((3 / 2) * radius) * 1.5015;
        if (j <= Math.floor(num_columns / 2))
            y = (int) (100 - (j * (height / 2)));
        else
            y = (int) ((100 - (height * (range / 2)) + (num_columns - rows[j]) * (height / 2)));
        for (int i = 0; i < rows[j]; i++) {
            y += height;
            Hex2 hex = new Hex2(i, radius, x, y);  // ****** [A] *****
            hexagons.add(hex.getHex());  // ****** [B] *****
        }
    }
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.*;

public class HexPanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private List<Hex2b> hex2bs = new ArrayList<>();
    private int radius;
    private int[] rows;

    public HexPanel(int num_columns, int radius, int screen_width, int screen_height) {
        super();
        setBackground(Color.WHITE);
        this.radius = radius;
        hex2bs = new LinkedList<Hex2b>();
        rows = Functions.columns(num_columns);
        int x = screen_width / 6;
        int y = screen_height / 2;
        double height = radius * Math.sqrt(3);
        double range = num_columns - rows[0];
        // build by columns, first
        for (int j = 0; j < num_columns; j++) {
            x += ((3 / 2) * radius) * 1.5015;
            if (j <= Math.floor(num_columns / 2))
                y = (int) (100 - (j * (height / 2)));
            else
                y = (int) ((100 - (height * (range / 2)) + (num_columns - rows[j]) * (height / 2)));
            for (int i = 0; i < rows[j]; i++) {
                y += height;
                Hex2b hex = new Hex2b(i, radius, x, y);
                hex2bs.add(hex);
            }
        }
        addMouseListener(new MyMouse());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // smooth graphics
        // setOpaque(false); // doesn't belong in here
        for (int i = 0; i < hex2bs.size(); i++) {
            Stroke stroke = new BasicStroke(radius / 20, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
            Hex2b hex2b = hex2bs.get(i);
            Color color = hex2b.getColor();
            g2.setColor(color);
            g2.fill(hex2b.getHex());
            g2.setStroke(stroke);
            g2.setColor(Color.BLACK);
            g2.draw(hex2b.getHex());
        }
    }

    private class MyMouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            for (Hex2b hex2b : hex2bs) {
                if (hex2b.getHex().contains(e.getPoint())) {
                    hex2b.changeColor();
                    repaint();
                    break;
                }
            }
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Game2b");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Toolkit toolKit = Toolkit.getDefaultToolkit();
        Dimension screen = toolKit.getScreenSize();
        int width = screen.width;
        int height = screen.height;
        frame.getContentPane().add(new HexPanel(11, 100, width, height));
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class Hex2b {
    private static final Color INIT_COLOR = Color.white;
    private static final Color SELECTED_COLOR = Color.red;
    private int ID;
    private Polygon hexagon;
    private Color color = INIT_COLOR;

    public Hex2b(int ID, int r, int x, int y) {
        super();
        this.ID = ID;
        hexagon = generateHex(r, x, y);
    }

    public Color getColor() {
        return color;
    }

    public void changeColor() {
        color = color == INIT_COLOR ? SELECTED_COLOR : INIT_COLOR;
    }

    public Polygon generateHex(int r, int x, int y) {
        Polygon hexagon = new Polygon();
        for (int i = 0; i < 6; i++) {
            int _x = (int) (x + r * Math.cos(i * 2 * Math.PI / 6));
            int _y = (int) (y + r * Math.sin(i * 2 * Math.PI / 6));
            hexagon.addPoint(_x, _y);
        }
        return hexagon;
    }

    public int getID() {
        return ID;
    }

    public Polygon getHex() {
        return hexagon;
    }
}