import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import javax.swing.*; /** * @author Brad Chase * A Simple Swing Application * */ public class MainWindow2 extends JComponent implements ActionListener { private DrawingComponent canvas; private static void createGUI() { MainWindow2 mainWindow = new MainWindow2(); JFrame frame = new JFrame("Amazing Swing App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(400, 300)); /*** setup menu ***/ JMenuBar menuBar = new JMenuBar(); /* the menu bar itself */ JMenu menu = new JMenu("File"); /* create a new menu */ menuBar.add(menu); /* add the menu to the menu bar that will contain it*/ JMenuItem item = new JMenuItem("Exit"); /* add an exit option */ item.addActionListener(mainWindow); /* this class will handle actions for this item */ item.setActionCommand("exit"); /* this is the text that accompanies the action event */ menu.add(item); frame.setJMenuBar(menuBar); /* add the menubar to the frame */ /*** setup main window area */ mainWindow.canvas = new DrawingComponent(); frame.getContentPane().add(mainWindow); /* add the main window component to the frame */ mainWindow.setLayout(new BorderLayout()); /* use the border layout manager */ mainWindow.add(mainWindow.canvas,BorderLayout.CENTER); frame.setVisible(true); frame.validate(); } /** * @param e the action that occurred * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { //we have to figure out what action occurred //to do so, we check the action command text in the actionevent if (e.getActionCommand().equals("exit")) { System.exit(0); } } private static class DrawingComponent extends JComponent implements MouseListener{ private BufferedImage _buff; private int _w = 320, _h = 240; public DrawingComponent() { /* set our size*/ this.setPreferredSize(new Dimension(_w, _h)); this.setMaximumSize(new Dimension(_w, _h)); this.setMinimumSize(new Dimension(_w, _h)); this.setDoubleBuffered(true); /* create the buffer we will draw on */ _buff = new BufferedImage(_w, _h, BufferedImage.TYPE_INT_RGB); this.addMouseListener(this); revalidate(); } /** * Overridden paint method for JComponent. Mostly just draws the BufferedImage. */ protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D)g.create(); g2d.drawImage(_buff, 0, 0, this); g2d.dispose(); //clean up } private int max(int a,int b){ return (a > b) ? a : b; } private int min(int a,int b){ return (a < b) ? a : b; } public void mouseClicked(MouseEvent e) { for(int row = e.getX()-2;row