java - JButton array ActionListener value -
for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--) for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++) { grid[btnnum] = new jbutton("" + (btnnum+1)); grid[btnnum].setpreferredsize(new dimension(75,75)); frame.add(grid[btnnum], gbc); grid[btnnum].addactionlistener(this); grid[btnnum].addkeylistener(this); btnnum++; }
i have array of buttons displayed in 3x3 grid , each 1 has action listener.
public void actionperformed(actionevent e){ string output = ""; if(e.getsource() == grid[0]){ system.out.println("button 1"); } }
is not correct?
complete example in context:
public class buttongrid implements actionlistener, keylistener{ jframe frame=new jframe(); //creates frame jbutton[] grid; //names grid of buttons public buttongrid(){ //constructor frame.settitle("mpc"); frame.setlayout(new gridbaglayout()); //set layout jbutton[] grid=new jbutton[12]; //allocate size of grid gridbagconstraints gbc = new gridbagconstraints(); gbc.gridx = 0; gbc.gridy = 0; int btnnum = 0; grid[9] = new jbutton("0"); grid[9].setpreferredsize(new dimension(75,75)); grid[10] = new jbutton("-"); grid[10].setpreferredsize(new dimension(75,75)); grid[11] = new jbutton("="); grid[11].setpreferredsize(new dimension(75,75)); frame.add(grid[9], gbc); gbc.gridx++; frame.add(grid[10], gbc); gbc.gridx++; frame.add(grid[11], gbc); for(gbc.gridy = 3; gbc.gridy > 0; gbc.gridy--) for(gbc.gridx = 0; gbc.gridx < 3;gbc.gridx++){ grid[btnnum] = new jbutton("" + (btnnum+1)); grid[btnnum].setpreferredsize(new dimension(75,75)); frame.add(grid[btnnum], gbc); grid[btnnum].addactionlistener(this); grid[btnnum].addkeylistener(this); btnnum++; } frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); //sets appropriate size frame frame.setvisible(true); //makes frame visible } public static void main(string[] args) { new buttongrid();//makes new buttongrid 2 parameters } public void actionperformed(actionevent e){ string output = ""; if(e.getsource() == grid[0]){ system.out.println("button one"); //playsound(abc.kick); }}
your grid variable null in actionlistener. bet -- you're shadowing variable.
solution: make sure initialize grid field, not local grid variable
public class buttongrid implements actionlistener, keylistener{ jframe frame=new jframe(); jbutton[] grid; // grid field remains null public buttongrid(){ frame.settitle("mpc"); frame.setlayout(new gridbaglayout()); jbutton[] grid=new jbutton[12]; // ****** local variable ******
at indicated line create shadowed variable. means because redeclare grid within constructor, initialize local variable , not field declared in class leaving field null. solution: don't re-declare grid. change to:
public class buttongrid implements actionlistener, keylistener{ jframe frame = new jframe(); jbutton[] grid; public buttongrid(){ frame.settitle("mpc"); frame.setlayout(new gridbaglayout()); grid = new jbutton[12]; // ***** initializes field ******
Comments
Post a Comment