通过Java中的方法传递变量

时间:2018-07-13 17:15:45

标签: java swing variables methods jbutton

我在这里寻求一些已解决了多个小时的问题的帮助。

在实践中,我希望能够通过矩阵中的方法传递变量“ j”和“ k”。问题在于传递它们,在不了解其原因的情况下,当它们进入if时不会被“捕获”。实际上,如果我尝试在if之前打印'r'和'c',它们会匹配。我不明白我哪里错了,因为if里面的其他东西工作正常,但是当我尝试在if里面打印'r'和'c'时,它们总是变成0。

按钮创建:

Integer[] x = {10, 70, 130, 190, 250, 310, 370}; Integer[] y = {80, 140, 200, 260, 320, 380};
    for (int i = 0, k = 0, j = 0; i < 42; i++, j++) {
        if (j % 7 == 0 && i != 0) { j = 0; k++; }
        lblCircles[i] = new JLabel(new ImageIcon(this.getClass().getResource("vuoto.png")));
        lblCircles[i].setBounds(x[j], y[k], 50, 50);
        lblCircles[i].setName("vuota");
        lblCircles[i].addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {
                for (int i = 0; i < 42; i++) {
                    for (int j = 0; j < 6; j++) {
                        for (int k = 0; k < 7; k++)
                            if (e.getSource() == lblCircles[i] && choose == 1) lblClickedPlayer(lblCircles[i], j, k);
                    }
                }
            }
        });
        frame.getContentPane().add(lblCircles[i]);
    }

方法:

public void lblClickedPlayer(JLabel lbl, int r, int c) {
    if (n == 0 && "vuota".equals(lbl.getName())) {
        n = 1;
        lbl.setIcon(new ImageIcon(this.getClass().getResource("red.png")));
        lbl.setName("piena");
        tbl[r][c] = 1;
        System.out.println("tbl[" + r + "][" + c + "] = " + tbl[r][c]);
    } else if (n == 1 && "vuota".equals(lbl.getName())) {
        n = 0;
        lbl.setIcon(new ImageIcon(this.getClass().getResource("yellow.png")));
        lbl.setName("piena");
        tbl[r][c] = 2;
        System.out.println("tbl[" + r + "][" + c + "] = " + tbl[r][c]);
    }
}

预先感谢您的帮助。

测试代码:

public class Prova {
public JFrame frame;
public JLabel[] lblCircles = new JLabel[42];
public String hostname;
public Font big = new Font("Comic Sans MS", Font.BOLD, 18);
public Integer[][] tbl = new Integer[6][7];
public int choose = 1, n = 0;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Prova window = new Prova();
                window.frame.setVisible(true);
            } catch (Exception e) { e.printStackTrace(); }
        }
    });
}

public Prova() { initialize(); }

private void initialize() {
    frame = new JFrame();
    baseFrame(frame, 430, 510);

    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(6, 7));
    panel.setBackground(new Color(41, 41, 41));
    panel.setBounds(10, 80, 410, 350);
    frame.getContentPane().add(panel);

    Integer[] x = {10, 70, 130, 190, 250, 310, 370}; Integer[] y = {80, 140, 200, 260, 320, 380};
    for (int i = 0, k = 0, j = 0; i < 42; i++, j++) {
        if (j % 7 == 0 && i != 0) { j = 0; k++; }
        lblCircles[i] = new JLabel("test");
        lblCircles[i].setBounds(x[j], y[k], 50, 50);
        lblCircles[i].setForeground(Color.RED);
        lblCircles[i].setFont(big);
        lblCircles[i].setName("vuota");
        lblCircles[i].addMouseListener(new MouseAdapter() {  
            public void mouseClicked(MouseEvent e) {
                for (int i = 0; i < 42; i++) {
                    for (int j = 0; j < 6; j++) {
                        for (int k = 0; k < 7; k++) {
                            if (e.getSource() == lblCircles[i] && choose == 1) lblClickedPlayer(lblCircles[i], j, k);
                        }
                    }
                }
            }
        });
        panel.add(lblCircles[i]);
    }
}

public void baseFrame(JFrame baseFrame, int width, int height) {
    baseFrame.getContentPane().setBackground(new Color(41, 41, 41));
    baseFrame.setBounds(100, 100, width, height);
    baseFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    baseFrame.getContentPane().setLayout(null);
    baseFrame.setUndecorated(true);
    baseFrame.setLocationRelativeTo(null);
    baseFrame.setResizable(false);
    baseFrame.setVisible(true);
    baseFrame.setShape(new RoundRectangle2D.Double(0, 0, baseFrame.getWidth(), baseFrame.getHeight(), 30, 30));
}

public void lblClickedPlayer(JLabel lbl, int r, int c) {
    if (n == 0 && "vuota".equals(lbl.getName())) {
        n = 1;
        lbl.setText("ok1");
        lbl.setForeground(Color.GREEN);
        lbl.setName("piena");
        tbl[r][c] = 1;
        System.out.println("tbl[" + r + "][" + c + "] = " + tbl[r][c]);
    } else if (n == 1 && "vuota".equals(lbl.getName())) {
        n = 0;
        lbl.setText("ok2");
        lbl.setForeground(Color.GREEN);
        lbl.setName("piena");
        tbl[r][c] = 2;
        System.out.println("tbl[" + r + "][" + c + "] = " + tbl[r][c]);
    }
}

}

1 个答案:

答案 0 :(得分:1)

您不需要这些内部循环,因为您只需要i。您可以使用int除法和int余数轻松地从i值计算行和列

    int r = i / COLS;
    int c = i % COLS;

例如

public class Prova {
    private static final int ROWS = 6;
    private static final int COLS = 7;

    // ....

            lblCircles[i].addMouseListener(new MouseAdapter() {
                // better to use mousePressed, not mouseClicked
                public void mousePressed(MouseEvent e) {

                    // no magic numbers such as 42 please. 
                    for (int i = 0; i < lblCircles.length; i++) {
                        if (e.getSource() == lblCircles[i] && choose == 1) {
                            myLabelClicked(lblCircles[i], i);
                        }
                    }
                }
            });

public void myLabelClicked(JLabel label, int i) {
    int r = i / COLS;
    int c = i % COLS;
    if (n == 0 && "vuota".equals(label.getName())) {
        n = 1;
        label.setText("ok1");
        label.setForeground(Color.GREEN);
        label.setName("piena");
        tbl[r][c] = 1;
    } else {
        n = 0;
        label.setText("ok2");
        label.setForeground(Color.GREEN);
        label.setName("piena");
        tbl[r][c] = 2;
    }
    System.out.println("tbl[" + r + "][" + c + "] = " + tbl[r][c]);
}

侧面问题:

  • 是的,使用布局管理器比使用setBounds好得多,因此第二点代码会更好
  • 避免使用幻数,例如42,而应使用属性和常量。
  • 在我上面的代码中,ROWS = 6和COLS = 7

我的MCVE:

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class Prova2 extends JPanel {
    private static final int ROWS = 6;
    private static final int COLS = 7;
    private static final int LBL_EB = 25; // "eb" for empty border
    private static final int PNL_EB = 3;
    public static final Font BIG = new Font("Comic Sans MS", Font.BOLD, 18);
    private static final Color BACKGROUND = new Color(41, 41, 41);
    private static final String VUOTA = "vuota";
    private JLabel[] lblCircles = new JLabel[ROWS * COLS];
    private Integer[][] tbl = new Integer[ROWS][COLS];
    private int choose = 1, n = 0;

    public Prova2() {
        setBorder(BorderFactory.createEmptyBorder(PNL_EB, PNL_EB, PNL_EB, PNL_EB));
        setLayout(new GridLayout(ROWS, COLS));
        setBackground(BACKGROUND);
        for (int i = 0; i < lblCircles.length; i++) {
            lblCircles[i] = new JLabel("test");
            lblCircles[i].setForeground(Color.RED);
            lblCircles[i].setFont(BIG);
            lblCircles[i].setBorder(BorderFactory.createEmptyBorder(LBL_EB, LBL_EB, LBL_EB, LBL_EB));
            lblCircles[i].setName(VUOTA);
            lblCircles[i].addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    for (int i = 0; i < lblCircles.length; i++) {
                        if (e.getSource() == lblCircles[i] && choose == 1) {
                            myLabelClicked(lblCircles[i], i);
                        }
                    }
                }
            });
            add(lblCircles[i]);
        }
    }

    protected void myLabelClicked(JLabel label, int i) {
        int row = i / COLS;
        int col = i % COLS;
        if (!VUOTA.equals(label.getName())) {
            return;
        }
        if (n == 0) {
            n = 1;
            label.setText("ok1");
            tbl[row][col] = 1;
        } else {
            n = 0;
            label.setText("ok2");
            tbl[row][col] = 2;
        }
        label.setForeground(Color.GREEN);
        label.setName("piena");
        System.out.printf("tbl[%d][%d] = %d%n", row, col, tbl[row][col]);
    }

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

        JFrame frame = new JFrame("Prova 2");
        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());
    }
}