This is an example of putting a lot of buttons onto a JPanel, which is then put onto a JFrame.
Notes:
Image:
// File: HangND.java
// Date: Oct 9, 2010
// Author: Nicholas Duchon
// Reference: Liang 8, Hangman game problem series
// pg 341, 9.31
// pg 530, 15.17
// pg 568, 16.35
// Purpose: how to create a panel with lots of buttons,
// with listeners,
efficiently
// Recall: JFrame default layout is BorderLayout
// JPanel default layout
is FlowLayout
// NOTE: check the combinations of setting GridLayout and pack
below
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JButton;
importjava.awt.BorderLayout;
importjava.awt.GridLayout;
importjava.awt.event.ActionListener;
importjava.awt.event.ActionEvent;
importjava.awt.Color;
public class HangND
extends JFrame
{
public HangND
() {
initAlphabetPanel ();
getContentPane().setBackground (Color.cyan);
// grey is so boring
setTitle ("Hangman
Duchon");
setSize (400, 400);
setLocationRelativeTo (null);
setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
// pack (); // try turning
this on and off
setVisible (true);
} // end constructor
void initAlphabetPanel
() {
JPanel p = new
JPanel ();
p.setLayout (new
GridLayout (0, 7)); //
try turning this on and off also
add (p,
BorderLayout.PAGE_END);
for(inti =
'A'; i
<= 'Z';
i++) {
JButton b = new
JButton (String.format("%c",
i));
p.add (b);
b.addActionListener (new
ActionListener () {
public
void actionPerformed (ActionEvent e) {
pressedButton
(e.getActionCommand());
} //
end listener method
} //
end anonymous inner class definition
);
// end accActionListener
parameter
} //
end for each letter
} //
end initAlphabetPanel
void pressedButton
(String s) {
System.out.println ("Button
pressed: "+ s);
} // end pressedButton method
public
static void main (String args []) {
JFrame f = new
HangND ();
} // end main
} //
end HangND