Advertisement
makispaiktis

6. Create buttons using Swing

May 17th, 2022 (edited)
998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. import java.awt.FlowLayout;
  2. import java.awt.event.ActionListener;
  3. import java.awt.event.ActionEvent;
  4.  
  5. import javax.swing.Icon;
  6. import javax.swing.ImageIcon;
  7. import javax.swing.JOptionPane;
  8. import javax.swing.JFrame;
  9. import javax.swing.JButton;
  10.  
  11. public class Gui extends JFrame{
  12.  
  13.     // Variables
  14.     private JButton reg;
  15.     private JButton custom;
  16.  
  17.     // Constructor
  18.     public Gui(){
  19.  
  20.         // Basics
  21.         super("JFrame's title");
  22.         setLayout(new FlowLayout());
  23.         Icon green = new ImageIcon(getClass().getResource("green.png"));
  24.         Icon red = new ImageIcon(getClass().getResource("red.png"));
  25.  
  26.         // Buttons
  27.         reg = new JButton("Regular button");
  28.         reg.setSize(300, 300);
  29.         add(reg);
  30.         custom = new JButton("Custom button", red);
  31.         reg.setSize(300, 300);
  32.         custom.setRolloverIcon(green);
  33.         add(custom);
  34.  
  35.         // Calling the handler - action listener
  36.         HandlerClass handler = new HandlerClass();
  37.         reg.addActionListener(handler);
  38.         custom.addActionListener(handler);
  39.  
  40.     }
  41.  
  42.  
  43.     // New class inside classes - ActionListener is abstract!
  44.     // We promise that we will override the methods
  45.     private class HandlerClass implements ActionListener{
  46.         public void actionPerformed(ActionEvent event){
  47.             JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
  48.         }
  49.     }
  50.  
  51.     // Main Function
  52.     public static void main(String[] args){
  53.         Gui gui = new Gui();
  54.         gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  55.         gui.setSize(600, 600);
  56.         gui.setVisible(true);
  57.     }
  58.  
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement