Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class Colors extends JFrame
- //1. add ActionListener
- implements ActionListener{
- //UUIs for buttons & textfield
- private JButton btnred, btnblue;
- private JTextField txt1;
- private Container pane = getContentPane();
- public Colors(){
- pane.setBackground(Color.white);
- pane.setLayout(new FlowLayout());
- //create UI's object
- btnred = new JButton("Red");
- btnred.addActionListener(this);
- //2. Add listener to UI button
- btnblue = new JButton("Blue");
- btnblue.addActionListener(this);
- txt1=new JTextField("Color string");
- //UI placement
- pane.add(btnred);
- pane.add(btnblue);
- pane.add(txt1);
- }
- //3. add actionPerformed method
- public void actionPerformed(ActionEvent e){
- Object ui = e.getSource();
- if (ui==btnred){
- pane.setBackground(Color.red);
- txt1.setText("Red");
- }
- else if (ui==btnblue){
- pane.setBackground(Color.blue);
- txt1.setText("Blue");
- }
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Colors frame = new Colors();
- frame.setDefaultCloseOperation(
- JFrame.EXIT_ON_CLOSE);
- frame.setTitle("Colors Test");
- frame.setSize(300, 200);
- frame.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment