JButton ActionListener执行if-和else-语句

时间:2018-11-03 12:43:34

标签: java swing jbutton

我正在尝试用Java为学校编写一款基本的九人莫里斯游戏。 GUI由24个JButton组成。单击的第一个按钮应设置移动的开始位置,第二个按钮应设置为目的地。我尝试创建一个布尔并将其单击一次后将其设置为true,然后检查该布尔值是true还是false,以确定Button应该设置开始还是目标。 但是,当我这样尝试并将“开始”和“目的地”打印到控制台时,它们都设置为0,1,0。我对Java还是很陌生,所以那里可能有一些不好的做法。

    JButton button010 = new JButton("");
    button010.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                if(!targ) {
                    setStart(0,1,0);
                    targ = true;
                } else {
                    setDest(0,1,0);
                    targ = false;
            }
        }
    });
    button010.setOpaque(false);
    button010.setContentAreaFilled(false);
    button010.setBorderPainted(false);
    button010.setBounds(222, 11, 47, 44);
    contentPane.add(button010);

2 个答案:

答案 0 :(得分:1)

这不是对您问题的答案,仅是建议一种更好的设计来删除侦听器代码中的硬编码。

为什么将布尔变量称为“ targ”。由于您具有“开始”和“目标”方法,因此为什么要创建第三个变量名?我建议使用一个更好的名称“ start”,以便您知道它与您的start / dest方法有关。默认为true,因为这是您单击按钮时尝试设置的第一个值。

因此,您的自定义操作可能类似于:

class GameAction action = new Action()
{
    private int value1;
    private int value2;
    private int value3;

    public GameAction(int value1, int value2, int value3)
    {
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (start)
        {
            setStart(value1, value2, value3);
            start = false;
        }
        else
        {
            setDest(value1, value2, value3);
            start = true;
        }
 }

您将使用更合适的变量名。

现在,您所有的逻辑都在一个类中,如果您需要更改逻辑,它包含在一个地方而不是24个自定义侦听器中。

然后在代码中创建按钮时:

JButton button010 = new JButton("");
button010.addActionListener( new GameAction(0, 1, 0) );

当然,最好在循环中创建24个按钮,这样就不必对参数进行硬编码。

答案 1 :(得分:0)

这不是一个真实或完整的答案,因为您的问题目前尚不完整,无法按当前说明回答,但是我正在测试此代码,以了解如何使用Swing,布局管理器和分隔符创建9 Man's Morris Grid来自GUI的模型。我创建了一个7 x 7的JLabel网格,并将其添加到使用GridLayout(7,7)的JPanel中。如果网格位置与9个人的morris中的单元格位置匹配,则将创建一个网格单元格,其中包含鼠标侦听器和所有元素。  以下代码创建此GUI:

enter image description here

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.*;

@SuppressWarnings("serial")
public class MorrisPanel extends JPanel {
    private static final int ICON_WIDTH = 80;
    private static final int SMALL_OVAL = 10;
    private static final int LARGE_OVAL = 40;
    private static final int GRID_SIDES = 7;
    private MorrisGameGrid game = new MorrisGameGrid();
    private Map<MorrisCell, JLabel> cellLabelMap = new HashMap<>();
    private Map<JLabel, MorrisCell> labelCellMap = new HashMap<>();
    private Icon blankIcon;
    private Icon cellIcon;
    private Icon whiteIcon;
    private Icon blackIcon;

    public MorrisPanel() {
        blankIcon = createIcon(null, 0);
        cellIcon = createIcon(Color.DARK_GRAY, SMALL_OVAL);
        whiteIcon = createIcon(Color.WHITE, LARGE_OVAL);
        blackIcon = createIcon(Color.DARK_GRAY, LARGE_OVAL);

        setLayout(new GridLayout(GRID_SIDES, GRID_SIDES));
        MyMouse myMouse = new MyMouse();
        List<MorrisColumn> columns = Arrays.asList(MorrisColumn.values());
        Collections.reverse(columns);
        for (MorrisColumn column : columns) {
            for (MorrisRow row : MorrisRow.values()) {
                MorrisCell cell = new MorrisCell(column, row);
                JLabel label = new JLabel(blankIcon);
                if (game.contains(cell)) {
                    label.setIcon(cellIcon);
                    label.addMouseListener(myMouse);
                    cellLabelMap.put(cell, label);
                    labelCellMap.put(label, cell);
                } 
                add(label);
            }
        }
    }

    private Icon createIcon(Color color, int size) {
        int w = ICON_WIDTH;
        int h = ICON_WIDTH;
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

        if (color != null) {
            Graphics2D g2 = img.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(color);
            int x = (ICON_WIDTH - size) / 2;
            int y = x;
            int width = size;
            int height = size;
            g2.fillOval(x, y, width, height);
            g2.setColor(Color.BLACK);
            g2.drawOval(x, y, width, height);
            g2.dispose();
        }
        return new ImageIcon(img);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        for (MorrisEdge edge : game.getEdges()) {
            JLabel l1 = cellLabelMap.get(edge.getCell1());
            JLabel l2 = cellLabelMap.get(edge.getCell2());
            int x1 = l1.getLocation().x + l1.getWidth() / 2;
            int x2 = l2.getLocation().x + l2.getWidth() / 2;
            int y1 = l1.getLocation().y + l1.getHeight() / 2;
            int y2 = l2.getLocation().y + l2.getHeight() / 2;
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    private class MyMouse extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent e) {
            JLabel source = (JLabel) e.getSource();
            MorrisCell cell = labelCellMap.get(source);


            // TODO: Begin testing block -- delete this
            System.out.println(cell); // !! just for testing purposes
            Icon icon = source.getIcon();
            if (icon == cellIcon) {
                source.setIcon(blackIcon);
            } else if (icon == blackIcon) {
                source.setIcon(whiteIcon);
            } else if (icon == whiteIcon) {
                source.setIcon(cellIcon);
            }
            // TODO: end testing block

            // TODO: finish
        }

    }

    private static void createAndShowGui() {
        MorrisPanel mainPanel = new MorrisPanel();

        JFrame frame = new JFrame("TestButtons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

class MorrisGame {
    private MorrisGameGrid grid = new MorrisGameGrid();

    // TODO: logic for game goes here

    public MorrisGameGrid getGrid() {
        return grid;
    }
}

class MorrisGameGrid {
    Set<MorrisCell> cells = new HashSet<>();
    Set<MorrisEdge> edges = new HashSet<>();

    public MorrisGameGrid() {
        cells.add(new MorrisCell("a1"));
        cells.add(new MorrisCell("d1"));
        cells.add(new MorrisCell("g1"));
        cells.add(new MorrisCell("b2"));
        cells.add(new MorrisCell("d2"));
        cells.add(new MorrisCell("f2"));
        cells.add(new MorrisCell("c3"));
        cells.add(new MorrisCell("d3"));
        cells.add(new MorrisCell("e3"));
        cells.add(new MorrisCell("a4"));
        cells.add(new MorrisCell("b4"));
        cells.add(new MorrisCell("c4"));
        cells.add(new MorrisCell("e4"));
        cells.add(new MorrisCell("f4"));
        cells.add(new MorrisCell("g4"));
        cells.add(new MorrisCell("c5"));
        cells.add(new MorrisCell("d5"));
        cells.add(new MorrisCell("e5"));
        cells.add(new MorrisCell("b6"));
        cells.add(new MorrisCell("d6"));
        cells.add(new MorrisCell("f6"));
        cells.add(new MorrisCell("a7"));
        cells.add(new MorrisCell("d7"));
        cells.add(new MorrisCell("g7"));

        connectLoop(getCell("a1"), getCell("d1"), getCell("g1"), 
                getCell("g4"), getCell("g7"), getCell("d7"),
                getCell("a7"), getCell("a4"));
        connectLoop(getCell("b2"), getCell("d2"), getCell("f2"),
                getCell("f4"), getCell("f6"), getCell("d6"), 
                getCell("b6"), getCell("b4"));
        connectLoop(getCell("c3"), getCell("d3"), getCell("e3"),
                getCell("e4"), getCell("e5"), getCell("d5"), 
                getCell("c5"), getCell("c4"));
        connectEdge(getCell("d1"), getCell("d2"), getCell("d3"));
        connectEdge(getCell("d7"), getCell("d6"), getCell("d5"));
        connectEdge(getCell("a4"), getCell("b4"), getCell("c4"));
        connectEdge(getCell("e4"), getCell("f4"), getCell("g4"));

    }

    public boolean contains(MorrisCell cell) {
        return cells.contains(cell);
    }

    public Set<MorrisCell> getCells() {
        return cells;
    }

    public Set<MorrisEdge> getEdges() {
        return edges;
    }

    private void connectCells(MorrisCell cell1, MorrisCell cell2) {
        cell1.addNeighbors(cell2);
        cell2.addNeighbors(cell1);
        edges.add(new MorrisEdge(cell1, cell2));
    }

    private void connectEdge(MorrisCell... cells) {
        for (int i = 0; i < cells.length - 1; i++) {
            connectCells(cells[i], cells[i + 1]);
        }
    }

    private void connectLoop(MorrisCell... cells) {
        connectEdge(cells);
        connectCells(cells[0], cells[cells.length - 1]);
    }

    public MorrisCell getCell(String text) {
        if (text == null || text.length() != 2) {
            String errorTxt = "For text: " + text;
            throw new IllegalArgumentException(errorTxt);
        }
        MorrisCell temp = new MorrisCell(text);
        for (MorrisCell morrisCell : cells) {
            if (morrisCell.equals(temp)) {
                return morrisCell;
            }
        }
        return null;
    }
}

class MorrisEdge {
    private MorrisCell cell1;
    private MorrisCell cell2;

    public MorrisEdge(MorrisCell cell1, MorrisCell cell2) {
        if (cell1.compareTo(cell2) < 0) {
            this.cell1 = cell1;
            this.cell2 = cell2;
        } else {
            this.cell2 = cell1;
            this.cell1 = cell2;
        }
    }

    public MorrisCell getCell1() {
        return cell1;
    }

    public MorrisCell getCell2() {
        return cell2;
    }

    @Override
    public int hashCode() {
        int result = ((cell1 == null) ? 0 : cell1.hashCode());
        result += ((cell2 == null) ? 0 : cell2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MorrisEdge other = (MorrisEdge) obj;

        boolean e1 = compareCells(cell1, other.cell1);
        e1 &= compareCells(cell2, other.cell2);
        boolean e2 = compareCells(cell1, other.cell2);
        e2 &= compareCells(cell2, other.cell1);
        return e1 || e2;
    }

    private static boolean compareCells(MorrisCell c1, MorrisCell c2) {
        if (c1 == null) {
            if (c2 != null)
                return false;
        } else if (!c1.equals(c2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Edge [" + cell1 + ", " + cell2 + "]";
    }

}

class MorrisCell implements Comparable<MorrisCell> {
    private MorrisColumn column;
    private MorrisRow row;
    private Set<MorrisCell> neighbors = new HashSet<>();
    private MorrisPlayer player = null;

    public MorrisCell(MorrisColumn column, MorrisRow row) {
        this.column = column;
        this.row = row;
    }

    public MorrisCell(String text) {
        if (text.length() != 2) {
            String errorTxt = "For text: " + text;
            throw new IllegalArgumentException(errorTxt);
        }
        String columnTxt = text.substring(0, 1).toLowerCase();
        String rowTxt = text.substring(1, 2);
        MorrisColumn column1 = null;
        MorrisRow row1 = null;
        for (MorrisColumn c : MorrisColumn.values()) {
            if (c.getText().equals(columnTxt)) {
                column1 = c;
                break;
            }
        }
        for (MorrisRow r : MorrisRow.values()) {
            if (r.getText().equals(rowTxt)) {
                row1 = r;
                break;
            }
        }
        if (column1 == null || row1 == null) {
            String errorTxt = "For text: " + text;
            throw new IllegalArgumentException(errorTxt);
        }
        this.column = column1;
        this.row = row1;
    }

    public void addNeighbors(MorrisCell neighbor) {
        neighbors.add(neighbor);
    }

    public boolean isNeighbor(MorrisCell possibleNeighbor) {
        return neighbors.contains(possibleNeighbor);
    }

    public MorrisRow getRow() {
        return row;
    }

    public MorrisColumn getColumn() {
        return column;
    }

    public void setPlayer(MorrisPlayer player) {
        this.player = player;
    }

    public MorrisPlayer getPlayer() {
        return player;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((column == null) ? 0 : column.hashCode());
        result = prime * result + ((row == null) ? 0 : row.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MorrisCell other = (MorrisCell) obj;
        if (column != other.column)
            return false;
        if (row != other.row)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return column.getText() + row.getText();
    }

    @Override
    public int compareTo(MorrisCell o) {
        int colCompare = column.compareTo(o.column);
        int rowCompare = row.compareTo(o.row);
        return colCompare != 0 ? colCompare : rowCompare;
    }

}

enum MorrisRow {
    ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7");

    private String text;

    private MorrisRow(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

enum MorrisColumn {
    A("a"), B("b"), C("c"), D("d"), E("e"), F("f"), G("g");

    private String text;

    private MorrisColumn(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

enum MorrisPlayer {
    WHITE("White"), BLACK("Black");

    private String text;

    private MorrisPlayer(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

}