I am a beginner with Java and eventually I would like to create code for a robot I am making for a senior project. I am planning for the robot to set up dominoes in a specified pattern to then be knocked down. I first need to write a program that will allow me to choose dominoes to be placed on a grid. I am then planning on having the program print out a new program for Arduino.
As a test and to learn, I would like to make a 20x40 grid with JButtons. I would then like to click a few Jbuttons then add the Jbutton values to a new array. ex. I click the 1st, 5th, 30th, and 799th button. The program will then add those to a new array where array[0]=1
, array[2]=5;
etc.
I spent many hours with trial and error and looking online to come up with this code: The problem right now is that it seems to be skipping the Buttongrid method (?). If I make the method public static void main (String [] args){, then the action listener doesn't work.
Again, I am JUST beginning so I will not be surprised if many things are wrong. Please just take a look at it and help me figure out what I have to fix. Thanks
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]);
}
}
}
}
This is because you didn't call your ButtonGrid frame in main class , Like this :
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();
}