gpt4 book ai didi

java - 初学者 : JButton/Gridlayout (Similar to Minesweeper)

转载 作者:行者123 更新时间:2023-12-01 04:45:05 26 4
gpt4 key购买 nike

我是 Java 初学者,最终我想为我正在为高级项目制作的机器人创建代码。我计划让机器人按照指定的模式搭建多米诺骨牌,然后将其推倒。我首先需要编写一个程序,允许我选择要放置在网格上的多米诺骨牌。然后我计划让该程序为 Arduino 打印一个新程序。

作为测试和学习,我想用 JButtons 制作一个 20x40 网格。然后,我想单击几个 Jbutton,然后将 Jbutton 值添加到新数组中。前任。我单击第 1 个、第 5 个、第 30 个和第 799 个按钮。然后,程序会将它们添加到一个新数组中,其中 array[0]=1array[2]=5; 等。

我花了很多时间进行试验和错误,并在网上查找以得出此代码:现在的问题是它似乎跳过了 Buttongrid 方法(?)。如果我将方法设置为 public static void main (String [] args){,则操作监听器将不起作用。

再说一次,我才刚刚开始,所以如果很多事情都是错误的,我不会感到惊讶。请看一下它并帮助我找出需要解决的问题。谢谢

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class ButtonGrid extends JFrame implements ActionListener {
static int clicked[]=new int[800];
static JButton button[]=new JButton[800];
static int x;
static int count=0;
int value;
ActionListener listen;
public ButtonGrid() {
JFrame frame= new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
GridLayout grid=new GridLayout(20,40);
frame.setLayout(grid);
//fill clicked with 0s////////////////////////////////////
for (int c=0;c<=10;c++){
clicked[c]=0;}
for(x=0;x<800;x++){
button[x]= new JButton();
button[x].setActionCommand(Integer.toString(x));
frame.add(button[x]);
button[x].addActionListener(this);
}}
public void actionPerformed (ActionEvent e){


while(count<11){
int newvalue=value;
value=Integer.parseInt( e.getActionCommand());
if(value!=newvalue){
clicked[count]=this.value;
count=count+1;
System.out.println("Found");
}
else{
newvalue=value;
System.out.println("Looking...");}}
} public static void main(String [] args){
ButtonGrid b=new ButtonGrid();
if (count>10){
for (int t=0;t<=11;t++){
System.out.println(clicked[t]);
}
}
}
}

最佳答案

这是因为您没有在主类中调用 ButtonGrid 框架,如下所示:

 public static void main(String[] args) {
System.out.println("this prints and no window pops up. it skipped the grid/frame code");
ButtonGrid b = new ButtonGrid();
}

关于java - 初学者 : JButton/Gridlayout (Similar to Minesweeper),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com