FirstSwingFrame.java Page 1 of 1 2: * A first example of using Swing. A JFrame is created with 3: * a label and buttons (which don t yet respond to events). 4: * 5: * @author Andrew Vardy 6: */ 7: import javax.swing.*; 8: import java.awt.flowlayout; 9: 10: public class FirstSwingFrame extends JFrame { 11: public FirstSwingFrame() { 12: super("firstswingframe"); 13: setdefaultcloseoperation(jframe.exit_on_close); 14: setlayout(new FlowLayout()); 15: 16: // You can any Component to the JFrame 17: add(new JLabel("Label")); 18: add(new JButton("Button1")); 19: add(new JButton("Button2")); 20: 21: // Set the size of the JFrame and make it visible 22: setsize(300, 100); 23: setvisible(true); 24: } 25: 26: public static void main(string[] args) throws Exception { 27: // An anonymous inner class created to run on the event- 28: // dispatching thread. 29: SwingUtilities.invokeLater(new Runnable() { 30: public void run() { 31: new FirstSwingFrame(); 32: } 33: }); 34: } 35: }
SecondSwingFrame.java Page 1 of 1 2: * Just like FirstSwingFrame only we do not extend 3: * JFrame, we have a JFrame attribute instead. 4: * 5: * @author Andrew Vardy 6: */ 7: 8: import javax.swing.*; 9: import java.awt.flowlayout; 10: 11: public class SecondSwingFrame { 12: 13: JFrame frame = new JFrame("SecondSwingFrame"); 14: 15: public SecondSwingFrame() { 16: frame.setdefaultcloseoperation(jframe.exit_on_close); 17: frame.setlayout(new FlowLayout()); 18: 19: frame.add(new JLabel("Label")); 20: frame.add(new JButton("Button1")); 21: frame.add(new JButton("Button2")); 22: 23: frame.setsize(300, 100); 24: frame.setvisible(true); 25: } 26: 27: public static void main(string[] args) throws Exception { 28: SwingUtilities.invokeLater(new Runnable() { 29: public void run() { 30: new SecondSwingFrame(); 31: } 32: }); 33: } 34: }
LayoutPlay.java Page 1 of 2 2: * Demonstrates Swing s component layout features using three different 3: * layout managers: FlowLayout, GridLayout, and BoxLayout. 4: * 5: * The suggested layout manager is GridBagLayout but it is rather complicated. 6: * Alternatively, you can use a GUI-builder such as NetBeans. 7: * 8: * @author Andrew Vardy 9: */ 10: import javax.swing.*; 11: import java.awt.*; 12: 13: public class LayoutPlay extends JFrame { 14: 15: // RedPanel uses the default layout for JPanels --- FlowLayout 16: class RedPanel extends JPanel { 17: public RedPanel() { 18: setbackground(color.red); 19: setpreferredsize(new Dimension(200, 200)); 20: add(new JLabel("x")); add(new JButton("Set")); 21: add(new JLabel("y")); add(new JButton("Set")); 22: add(new JLabel("z")); add(new JButton("Set")); 23: } 24: } 25: 26: // GreenPanel uses GridLayout 27: class GreenPanel extends JPanel { 28: public GreenPanel() { 29: setbackground(color.green); 30: setpreferredsize(new Dimension(200, 200)); 31: setlayout(new GridLayout(3, 2)); 32: add(new JLabel("x")); add(new JButton("Set")); 33: add(new JLabel("y")); add(new JButton("Set")); 34: add(new JLabel("z")); add(new JButton("Set")); 35: } 36: } 37: 38: // BluePanel uses BoxLayout to layout three individual rows of 39: // (label, button) pairs. 40: class BluePanel extends JPanel { 41: public BluePanel() { 42: setbackground(color.blue); 43: setpreferredsize(new Dimension(200, 200)); 44: 45: // Layout the BluePanel vertically. 46: setlayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 47: 48: // Create three rows, each one a horizontally laid out 49: // JPanel with a label and a button. 50: JPanel row1 = new JPanel(), 51: row2 = new JPanel(), 52: row3 = new JPanel(); 53: row1.setlayout(new BoxLayout(row1, BoxLayout.X_AXIS)); 54: row2.setlayout(new BoxLayout(row2, BoxLayout.X_AXIS)); 55: row3.setlayout(new BoxLayout(row3, BoxLayout.X_AXIS)); 56: row1.add(new JLabel("x")); row1.add(new JButton("Set")); 57: row2.add(new JLabel("y")); row2.add(new JButton("Set")); 58: row3.add(new JLabel("z")); row3.add(new JButton("Set")); 59: 60: add(row1); 61: add(row2); 62: add(row3); 63: } 64: } 65: 66: public LayoutPlay() { 67: super("layoutplay"); 68: setdefaultcloseoperation(jframe.exit_on_close); 69: 70: // At the highest level we will use FlowLayout. 71: setlayout(new FlowLayout()); 72: 73: // Add three different panels with differing 74: // layouts, but the same set of labels + buttons 75: add(new RedPanel()); 76: add(new GreenPanel()); 77: add(new BluePanel());
LayoutPlay.java Page 2 of 2 78: 79: // The JFrame will choose its initial size 80: // based on its content. 81: pack(); 82: setvisible(true); 83: } 84: 85: public static void main(string[] args) throws Exception { 86: SwingUtilities.invokeLater(new Runnable() { 87: public void run() { 88: new LayoutPlay(); 89: } 90: }); 91: } 92: }
Paint1.java Page 1 of 2 2: * First cut at creating a paint program with Swing. This program works 3: * but does not separate the model from the GUI. This will be fixed in 4: * subsequent versions of PaintX. 5: * 6: * @author Andrew Vardy 7: */ 8: import java.awt.*; 9: import java.awt.event.actionevent; 10: import java.awt.event.actionlistener; 11: import java.awt.event.mouseadapter; 12: import java.awt.event.mouseevent; 13: 14: import javax.swing.*; 15: 16: public class Paint1 extends MouseAdapter implements ActionListener { 17: // The underlying model is a 2-D array of booleans. 18: // This grid represents the contents of the canvas. 19: boolean grid[][] = new boolean[400][400]; 20: 21: JFrame frame = new JFrame("Paint1"); 22: PaintPanel paintpanel = new PaintPanel(); 23: JButton clearbutton = new JButton("Clear"); 24: 25: public Paint1() { 26: // Initialize frame and add the paintpanel in the center 27: frame.setdefaultcloseoperation(jframe.exit_on_close); 28: frame.setlayout(new BorderLayout()); 29: frame.add(paintpanel); 30: 31: // Create a panel on the left for buttons and add 32: // the button to it 33: JPanel buttonpanel = new JPanel(); 34: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 35: buttonpanel.add(clearbutton); 36: frame.add(buttonpanel, BorderLayout.WEST); 37: 38: // Setup event listeners. In this case, Paint1 is the 39: // listener for all component events. 40: clearbutton.addactionlistener(this); 41: paintpanel.addmouselistener(this); 42: paintpanel.addmousemotionlistener(this); 43: 44: frame.pack(); 45: frame.setresizable(false); // Must not be resizable because we aren t 46: frame.setvisible(true); // handling changes in size. 47: } 48: 49: @Override 50: public void actionperformed(actionevent e) { 51: for (int i=0; i<grid.length; i++) 52: for (int j=0; j<grid[0].length; j++) 53: grid[i][j] = false; 54: 55: // The panel must be informed that a repaint is now required. 56: paintpanel.repaint(); 57: } 58: 59: public void mousepressed(mouseevent e) { 60: int cellx = e.getx() / paintpanel.cw; 61: int celly = e.gety() / paintpanel.ch; 62: 63: if (cellx >= 0 && cellx < grid.length && 64: celly >= 0 && celly < grid[0].length) { 65: // Set the cell content to true. 66: grid[cellx][celly] = true; 67: paintpanel.repaint(); 68: } 69: } 70: 71: public void mousedragged(mouseevent e) { 72: mousepressed(e); 73: } 74: 75: class PaintPanel extends JPanel { 76: // Width and height of an individual cell.
Paint1.java Page 2 of 2 77: int cw, ch; 78: 79: PaintPanel() { 80: int pw = 400, ph = 400; 81: setpreferredsize(new Dimension(pw, ph)); 82: 83: cw = pw / grid.length; 84: ch = ph / grid[0].length; 85: } 86: 87: public void paintcomponent(graphics g) { 88: // First fill the whole panel with white. 89: g.setcolor(color.white); 90: g.fillrect(0, 0, getwidth(), getheight()); 91: 92: // Now fill in all true grid entries with blue. 93: g.setcolor(color.blue); 94: for (int i=0; i<grid.length; i++) 95: for (int j=0; j<grid[0].length; j++) 96: if (grid[i][j]) 97: g.fillrect(i*cw, j*ch, cw, ch); 98: } 99: } 100: 101: public static void main(string[] args) throws Exception { 102: SwingUtilities.invokeLater(new Runnable() { 103: public void run() { 104: new Paint1(); 105: } 106: }); 107: } 108: }
Paint2.java Page 1 of 1 2: * Here we re-factor Paint1 to isolate the model as a separate 3: * class---gridmodel. Also we factor out PaintPanel and call it 4: * GridPanel and place it in a separate top-level class. 5: * 6: * @author Andrew Vardy 7: */ 8: import java.awt.*; 9: import java.awt.event.actionevent; 10: import java.awt.event.actionlistener; 11: import java.awt.event.mouseadapter; 12: import java.awt.event.mouseevent; 13: 14: import javax.swing.*; 15: 16: public class Paint2 extends MouseAdapter implements ActionListener { 17: 18: GridModel model = new GridModel(100, 100); 19: JFrame frame = new JFrame("Paint2"); 20: GridPanel gridpanel = new GridPanel(400, 400, model); 21: JButton clearbutton = new JButton("Clear"); 22: 23: public Paint2() { 24: // Initialize frame and add the paintpanel in the center 25: frame.setdefaultcloseoperation(jframe.exit_on_close); 26: frame.setlayout(new BorderLayout()); 27: frame.add(gridpanel); 28: 29: // Create a panel on the left for buttons and add 30: // the button to it 31: JPanel buttonpanel = new JPanel(); 32: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 33: buttonpanel.add(clearbutton); 34: frame.add(buttonpanel, BorderLayout.WEST); 35: 36: // Setup event listeners. In this case, Paint2 is the 37: // listener for all component events. 38: clearbutton.addactionlistener(this); 39: gridpanel.addmouselistener(this); 40: gridpanel.addmousemotionlistener(this); 41: 42: frame.pack(); 43: frame.setresizable(false); // Must not be resizable because we aren t 44: frame.setvisible(true); // handling changes in size. 45: } 46: 47: @Override 48: public void actionperformed(actionevent e) { 49: model.clearall(); 50: gridpanel.repaint(); 51: } 52: 53: public void mousepressed(mouseevent e) { 54: int cellx = e.getx() / gridpanel.getcellwidth(); 55: int celly = e.gety() / gridpanel.getcellheight(); 56: 57: if (cellx >= 0 && cellx < model.getwidth() && 58: celly >= 0 && celly < model.getheight()) { 59: model.setvalue(cellx, celly, true); 60: gridpanel.repaint(); 61: } 62: } 63: 64: public void mousedragged(mouseevent e) { 65: mousepressed(e); 66: } 67: 68: public static void main(string[] args) throws Exception { 69: SwingUtilities.invokeLater(new Runnable() { 70: public void run() { 71: new Paint2(); 72: } 73: }); 74: } 75: } 76:
GridModel.java Page 1 of 1 2: * Represents a 2-D array of boolean values. 3: * 4: * @author Andrew Vardy 5: */ 6: public class GridModel { 7: protected int width; 8: protected int height; 9: protected boolean grid[][]; 10: 11: GridModel(int width, int height) { 12: this.width = width; 13: this.height = height; 14: grid = new boolean[width][height]; 15: } 16: 17: void clearall() { 18: for (int i=0; i<width; i++) 19: for (int j=0; j<height; j++) 20: grid[i][j] = false; 21: } 22: 23: boolean getvalue(int i, int j) { 24: return grid[i][j]; 25: } 26: 27: void setvalue(int i, int j, boolean value) { 28: grid[i][j] = value; 29: } 30: 31: int getwidth() { 32: return width; 33: } 34: 35: int getheight() { 36: return height; 37: } 38: }
GridPanel.java Page 1 of 1 2: * A JPanel that provides a view of a GridModel. 3: */ 4: import java.awt.color; 5: import java.awt.dimension; 6: import java.awt.graphics; 7: import javax.swing.jpanel; 8: 9: public class GridPanel extends JPanel { 10: // Width and height of an individual cell. 11: int cw, ch; 12: GridModel model; 13: 14: GridPanel(int width, int height, GridModel model) { 15: setpreferredsize(new Dimension(width, height)); 16: this.model = model; 17: 18: cw = width / model.getwidth(); 19: ch = height / model.getheight(); 20: } 21: 22: public void paintcomponent(graphics g) { 23: super.paintcomponent(g); 24: 25: // First fill the whole panel with white. 26: g.setcolor(color.white); 27: g.fillrect(0, 0, getwidth(), getheight()); 28: 29: // Now fill in all true grid entries with blue. 30: g.setcolor(color.blue); 31: for (int i=0; i<model.getwidth(); i++) 32: for (int j=0; j<model.getheight(); j++) 33: if (model.getvalue(i,j)) 34: g.fillrect(i*cw, j*ch, cw, ch); 35: } 36: 37: public int getcellwidth() { 38: return cw; 39: } 40: 41: public int getcellheight() { 42: return ch; 43: } 44: }
GameOfLife.java Page 1 of 3 2: * Based on Paint2, this application implements Conway s Game of Life 3: * Cellular Automaton. For event listeners we use anonymous inner 4: * class which are defined directly in the constructor for 5: * GameOfLife. 6: * 7: * @author Andrew Vardy 8: */ 9: import java.awt.*; 10: import java.awt.event.actionevent; 11: import java.awt.event.actionlistener; 12: import java.awt.event.mouseadapter; 13: import java.awt.event.mouseevent; 14: 15: import javax.swing.*; 16: 17: public class GameOfLife { 18: 19: // The underlying model is an extension of GridModel 20: // and implements the rules for the Game of Life. 21: LifeModel model = new LifeModel(100, 100); 22: 23: JFrame frame = new JFrame("GameOfLife"); 24: GridPanel paintpanel = new GridPanel(800, 800, model); 25: JButton clearbutton = new JButton("Clear"), 26: startbutton = new JButton("Start"), 27: stopbutton = new JButton("Stop"); 28: 29: public GameOfLife() { 30: // Initialize frame and add the paintpanel in the center 31: frame.setdefaultcloseoperation(jframe.exit_on_close); 32: frame.setlayout(new BorderLayout()); 33: frame.add(paintpanel); 34: 35: // Create a panel on the left for buttons and add 36: // the button to it 37: JPanel buttonpanel = new JPanel(); 38: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 39: buttonpanel.add(clearbutton); 40: buttonpanel.add(startbutton); 41: buttonpanel.add(stopbutton); 42: frame.add(buttonpanel, BorderLayout.WEST); 43: 44: // Setup event listeners. This time we will add the 45: // listeners as anonymous inner classes. 46: clearbutton.addactionlistener(new ActionListener() { 47: public void actionperformed(actionevent e) { 48: model.clearall(); 49: paintpanel.repaint(); 50: } 51: }); 52: startbutton.addactionlistener(new ActionListener() { 53: public void actionperformed(actionevent e) { 54: model.start(); 55: } 56: }); 57: stopbutton.addactionlistener(new ActionListener() { 58: public void actionperformed(actionevent e) { 59: model.stop(); 60: } 61: }); 62: 63: // For mouse events we also use an anonymous inner class 64: // only here we retain a reference to it so that it can 65: // be added as both a MouseListener and a MouseMotionListener 66: MouseAdapter mymouseadapter = new MouseAdapter() { 67: public void mousepressed(mouseevent e) { 68: int cellx = e.getx() / paintpanel.cw; 69: int celly = e.gety() / paintpanel.ch; 70: 71: if (cellx >= 0 && cellx < model.getwidth() && 72: celly >= 0 && celly < model.getheight()) { 73: model.setvalue(cellx, celly, true); 74: paintpanel.repaint(); 75: } 76: }
GameOfLife.java Page 2 of 3 77: 78: public void mousedragged(mouseevent e) { 79: mousepressed(e); 80: } 81: }; 82: paintpanel.addmouselistener(mymouseadapter); 83: paintpanel.addmousemotionlistener(mymouseadapter); 84: 85: // Create a timer object with a specific interval in 86: // milliseconds. Create a listener to update the model. 87: // Note that timer events require an ActionListener, just 88: // like JButton events. 89: Timer timer = new Timer(100, new ActionListener() { 90: public void actionperformed(actionevent e) { 91: model.step(); 92: paintpanel.repaint(); 93: } 94: }); 95: timer.start(); 96: 97: frame.pack(); 98: frame.setresizable(false); // Must not be resizable because we aren t 99: frame.setvisible(true); // handling changes in size. 100: } 101: 102: public static void main(string[] args) throws Exception { 103: SwingUtilities.invokeLater(new Runnable() { 104: public void run() { 105: new GameOfLife(); 106: } 107: }); 108: } 109: } 110: 111: class LifeModel extends GridModel { 112: // Used to store the new grid created on each call to step. 113: private boolean nextgrid[][]; 114: private boolean started = false; 115: 116: LifeModel(int width, int height) { 117: super(width, height); 118: nextgrid = new boolean[width][height]; 119: } 120: 121: // Allow the simulation to proceed. 122: void start() { 123: started = true; 124: } 125: 126: // Prevent the simulation from proceeding. 127: void stop() { 128: started = false; 129: } 130: 131: // Execute one iteration, updating grid according 132: // to the Game of Life rules. 133: void step() { 134: if (!started) 135: return; 136: 137: // Implement rules for Conway s Game of Life, for all grid 138: // cells not on the outside border. 139: for (int i=1; i<width-1; i++) 140: for (int j=1; j<height-1; j++) { 141: // Count the number of live neighbours. 142: int count = 0; 143: if (grid[i-1][j-1]) count++; 144: if (grid[i ][j-1]) count++; 145: if (grid[i+1][j-1]) count++; 146: if (grid[i-1][j ]) count++; 147: if (grid[i+1][j ]) count++; 148: if (grid[i-1][j+1]) count++; 149: if (grid[i ][j+1]) count++; 150: if (grid[i+1][j+1]) count++; 151: 152: if (grid[i][j]) 153: // A living cell will stays alive only if it
GameOfLife.java Page 3 of 3 154: // has exactly 2 or 3 living neighbours. 155: nextgrid[i][j] = count==2 count==3; 156: else 157: // A dead cell will only come back to life 158: // if it has exactly 3 living neighbours. 159: nextgrid[i][j] = count==3; 160: } 161: 162: // Swap the two grid references 163: boolean tmp[][] = grid; 164: grid = nextgrid; 165: nextgrid = tmp; 166: } 167: }