Button1
File: java/Button1/Main.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* Main program for Button1
* This is an example of a javadoc comment
*/
public class Main extends JFrame
implements ActionListener {
/** Remember these for listener callbacks */
private JButton b1, b2;
public static void main (String [] args) {
new Main();
}
public Main () {
// Window setup
setSize (500, 500);
Container content = getContentPane();
content.setLayout (new BorderLayout());
setDefaultCloseOperation (EXIT_ON_CLOSE);
// Our canvas
MyCanvas canvas = new MyCanvas ();
content.add (canvas, BorderLayout.CENTER);
// Control panel at bottom
JPanel controls = new JPanel ();
controls.setBorder (new LineBorder(Color.blue));
controls.setLayout (new FlowLayout());
content.add (controls, BorderLayout.SOUTH);
// First button, use its public methods to set it up for now
b1 = new JButton ();
b1.setText ("First button");
b1.addActionListener (this);
controls.add (b1);
// Second button, ditto, this one has icon not text
b2 = new JButton ();
b2.setIcon (new ImageIcon ("leftArrow.gif"));
b2.addActionListener (this);
controls.add (b2);
setVisible (true);
}
/**
* Uses ivars b1, b2 to decode the event
*/
public void actionPerformed (ActionEvent e) {
if (e.getSource()==b1) System.out.println ("Button 1 was pushed");
else if (e.getSource()==b2) System.out.println ("Button 2 was pushed");
}
}
File: java/Button1/MyCanvas.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* A canvas we can draw on
*/
public class MyCanvas extends JComponent implements MouseListener {
/** Let's save this and re-use */
private Rectangle square = new Rectangle (100, 50, 50, 50);
public MyCanvas () {
addMouseListener (this);
setBorder (new LineBorder(Color.blue));
}
public void paintComponent (Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.draw (square);
}
/**
* MouseListener callbacks, just to demonstrate for now
*/
public void mousePressed (MouseEvent event) {
System.out.println ("Mouse down at " + event.getPoint().x + ", " + event.getPoint().y);
}
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}