Results 1 to 3 of 3
Thread: Button click GUI question
- 11-28-2010, 09:32 PM #1
Member
- Join Date
- Feb 2009
- Posts
- 6
- Rep Power
- 0
Button click GUI question
I am new to the GUI part of Java. I have created a board with 9 buttons in a 3x3 fashion. My question is... How do I activate a button click with the following code
Java Code:public BoardLayout(){ setLayout(new GridLayout(3,3)); for (int i=1;i<10;i++){ add(new JButton("" + i)); } }
Java Code:JButton jbtOne = new JButton("1");
-
You should create a Button variable inside the loop, add an ActionListener to it, and add it to the container:
Java Code:for (int i=1;i<10;i++){ //add(new JButton("" + i)); JButton button = new JButton("" + i); button.addActionListener(new ActionListener() { // *** your action listener my be different public void actionPerformed(ActionEvent e) { myButtonsAction(e); // a method of the class } }); add(button); }
- 11-29-2010, 08:48 AM #3
Member
- Join Date
- Feb 2009
- Posts
- 6
- Rep Power
- 0
I appreciate the help. I was able to complete what I was trying to accomplish with your help.
Not sure if you want me to post what I did, but this is how I set it up.
Java Code:for (int i=1;i<10;i++){ final JButton button = new JButton("" + i, filler); add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ XO = (int)(Math.random()*3); if ( XO == 1) button.setIcon(showcross); else if ( XO == 2) button.setIcon(shownot); else button.setIcon(filler); } }); button.addActionListener(printButton); } } } static class PrintButtonClick implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println(e.getActionCommand() + " was clicked."); } }
Similar Threads
-
How to run a jar file from a Button click in swing.
By killerf2006 in forum New To JavaReplies: 1Last Post: 07-23-2010, 01:55 PM -
SaveAs button click
By kasiram.p@gmail.com in forum AWT / SwingReplies: 2Last Post: 07-06-2010, 09:35 AM -
How can I display on Button click?
By ntagrafix in forum New To JavaReplies: 3Last Post: 11-04-2009, 01:05 AM -
How we can open a file with a click in button
By kostinio in forum AWT / SwingReplies: 2Last Post: 11-01-2009, 05:46 PM -
deselecting a button after the click.
By ramsrocker in forum New To JavaReplies: 10Last Post: 02-15-2009, 07:52 AM
Bookmarks