import java.awt.*; import java.awt.event.*; import javax.swing.*; class MyFrame extends JFrame{ // components of frame MyPanel mPanel; MyButton mButton; JComboBox mColorBox; // Constructor public MyFrame(String title){ super(title); // calls the constructor of JFrame setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when cross at top right is pressed // add components to MyFrame's container Container container = getContentPane(); //container.setLayout( new FlowLayout() ); // BoxLayout is the default layout mPanel = new MyPanel(); container.add("Center", mPanel); // Center, South, North, East & West is for BoxLayout mButton = new MyButton(); container.add("South", mButton); mColorBox = new JComboBox(); mColorBox.addItem(Color.RED); mColorBox.addItem(Color.BLACK); mColorBox.addItem(Color.BLUE); mColorBox.addItem(Color.GREEN); mColorBox.addItem(Color.YELLOW); container.add("North", mColorBox); setSize(400, 500); System.out.print("MyFrame"); // output text System.out.println(" is constructed"); // ... with newline } // The program start here public static void main( String[] args) { MyFrame frame = new MyFrame("My First Application"); // puts window in the middle of the screen // Dimension frameSize = frame.getSize(); // Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //frame.setLocation(screenSize.width / 2 - frameSize.width / 2, screenSize.height / 2 - frameSize.height / 2); frame.show(); // should be the last operation } // MyButton Class class MyButton extends JButton { MyButton() { super("Enlarge Figure"); // add text of button enableEvents(AWTEvent.MOUSE_EVENT_MASK); // to activate processMouseEvent } protected void processMouseEvent(MouseEvent e){ if (e.getID() == MouseEvent.MOUSE_CLICKED){ mPanel.mSize += 10; System.out.println("Button "+e.getButton()+" clicked: new size = "+mPanel.mSize); } } } // MyPanel Class class MyPanel extends JPanel{ int mX, mY; int mSize = 50; MyPanel() { super(); enableEvents(AWTEvent.MOUSE_EVENT_MASK); // to activate processMouseEvent setBackground(Color.white); } protected void processMouseEvent(MouseEvent e){ if (e.getID() == MouseEvent.MOUSE_CLICKED){ System.out.println("Button "+e.getButton()+" mouse pressed at x= "+e.getX()+", y="+e.getY()); mX = e.getX(); mY = e.getY(); repaint(); // call whenever the component should be repainted after some changements } } public void paintComponent(Graphics g){ super.paintComponent(g); // to draw background colors etc. g.setColor((Color) mColorBox.getSelectedItem() ); g.drawOval(mX - mSize/2, mY - mSize/2, mSize, mSize); g.drawRect(mX - mSize/2, mY - mSize/2, mSize, mSize); } } }