Guest User

Untitled

a guest
Sep 14th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. package chap12;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6.  
  7. public class TwoButtons  {
  8.  
  9.     JFrame frame;
  10.     JLabel label;
  11.  
  12.     public static void main (String[] args) {
  13.        TwoButtons gui = new TwoButtons();
  14.        gui.go();
  15.     }
  16.  
  17.     public void go() {
  18.        frame = new JFrame();
  19.        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  20.  
  21.        JButton labelButton = new JButton("Change Label");
  22.        labelButton.addActionListener(new LabelButtonListener());
  23.  
  24.        JButton colorButton = new JButton("Change Circle");
  25.        colorButton.addActionListener(new ColorButtonListener());
  26.  
  27.        label = new JLabel("I'm a label");      
  28.        MyDrawPanel drawPanel = new MyDrawPanel();
  29.        
  30.        frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
  31.        frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
  32.        frame.getContentPane().add(BorderLayout.EAST, labelButton);
  33.        frame.getContentPane().add(BorderLayout.WEST, label);
  34.  
  35.        frame.setSize(420,300);
  36.        frame.setVisible(true);
  37.     }
  38.    
  39.      class LabelButtonListener implements ActionListener {
  40.         public void actionPerformed(ActionEvent event) {
  41.             label.setText("Ouch!");
  42.         }
  43.      } // close inner class
  44.  
  45.      class ColorButtonListener implements ActionListener {
  46.         public void actionPerformed(ActionEvent event) {
  47.             frame.repaint();
  48.         }
  49.      }  // close inner class
  50.    
  51. }
  52.  
  53. class MyDrawPanel extends JPanel {
  54.    
  55.       public void paintComponent(Graphics g) {
  56.          
  57.          g.fillRect(0,0,this.getWidth(), this.getHeight());
  58.  
  59.          // make random colors to fill with
  60.          int red = (int) (Math.random() * 255);
  61.          int green = (int) (Math.random() * 255);
  62.          int blue = (int) (Math.random() * 255);
  63.  
  64.          Color randomColor = new Color(red, green, blue);
  65.          g.setColor(randomColor);
  66.          g.fillOval(70,70,100,100);
  67.       }
  68.  
  69. }
Add Comment
Please, Sign In to add comment