khirulnizam

Colors actionListener

Feb 12th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4.  
  5. public class Colors extends JFrame
  6.         //1. add ActionListener
  7.         implements ActionListener{
  8.     //UUIs for buttons & textfield
  9.     private JButton btnred, btnblue;
  10.     private JTextField txt1;
  11.     private Container pane = getContentPane();
  12.    
  13.     public Colors(){
  14.        
  15.         pane.setBackground(Color.white);
  16.         pane.setLayout(new FlowLayout());
  17.        
  18.         //create UI's object
  19.         btnred = new JButton("Red");
  20.         btnred.addActionListener(this);
  21.         //2. Add listener to UI button
  22.         btnblue = new JButton("Blue");
  23.         btnblue.addActionListener(this);
  24.         txt1=new JTextField("Color string");
  25.        
  26.         //UI placement
  27.         pane.add(btnred);
  28.         pane.add(btnblue);
  29.         pane.add(txt1);
  30.     }
  31.    
  32.     //3. add actionPerformed method
  33.     public void actionPerformed(ActionEvent e){
  34.         Object ui = e.getSource();
  35.         if (ui==btnred){
  36.             pane.setBackground(Color.red);
  37.             txt1.setText("Red");
  38.         }
  39.         else if (ui==btnblue){
  40.             pane.setBackground(Color.blue);
  41.             txt1.setText("Blue");
  42.            
  43.         }
  44.     }
  45.  
  46.     public static void main(String[] args) {
  47.         // TODO Auto-generated method stub
  48.        
  49.         Colors frame = new Colors();
  50.         frame.setDefaultCloseOperation(
  51.                 JFrame.EXIT_ON_CLOSE);
  52.         frame.setTitle("Colors Test");
  53.         frame.setSize(300, 200);
  54.         frame.setVisible(true);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment