我想把按鈕添加到所有這些面板,所以我可以檢查它們是否被點擊。我對Java還是一個新手,這就是我們如何去做的。這一行給出了一個空指針,我不知道爲什麼
現在我正在製作一個大面板,並在其上添加48個新面板,然後在每個面板上添加按鈕,以便我可以製作一個動作事件。如果我有辦法檢查我是否點擊了面板,那麼我可以做到這一點,但我不知道如何。
我在「panel [x] .add(單擊[x])」;行上收到NullPointerException;「
package CatchTheMouse;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CatchTheMouse extends JFrame implements ActionListener, MouseListener{
final int ROWS = 8;
final int COLS = 6;
final int GAP = 2;
final int MAX_PANELS = ROWS * COLS;
int clicks;
int hits;
int percentage = 0;
int width;
int height;
int panelX;
int panelY;
int whichPanel = (int)(Math.random() * 47 + 1);
JButton[] click = new JButton[MAX_PANELS];
JLabel grats = new JLabel("");
JLabel spot = new JLabel("X");
JPanel[] panel = new JPanel[MAX_PANELS];
JPanel pane = new JPanel(new GridLayout(ROWS, COLS, GAP, GAP));
Font xFont = new Font("Ariel", Font.BOLD, 20);
Font font = new Font("Ariel", Font.PLAIN, 12);
public CatchTheMouse() {
super("Catch the Mouse");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
add(spot);
spot.setFont(xFont);
add(grats);
grats.setFont(font);
add(pane);
for(int x = 0; x < MAX_PANELS; ++x) {
panel[x] = new JPanel();
pane.add(panel[x]);
panel[x].setBackground(Color.RED);
panel[x].add(click[x]);
click[x].addActionListener(this);
click[x].setVisible(false);
}
pane.setBackground(Color.BLACK);
panel[whichPanel].add(spot);
}
public void mouseClicked(MouseEvent e) {
clicks = e.getClickCount();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src == click[whichPanel]) {
hits++;
grats.setText("You have made " + Integer.toString(hits) + " hits");
}
}
public static void main(String[] args) {
CatchTheMouse frame = new CatchTheMouse();
frame.setVisible(true);
}
}
我做到了。我意識到我沒有包括它,所以我編輯英寸這樣說 – buckley183 2014-12-06 05:37:21