MatiasMerkuri
1/3/2019 - 2:20 PM

GUI with Special Image JButton

GUI WITH SPECIAL IMAGE JBUTTON

import javax.swing.*;

public class First{
    public static void main(String args[]){

        Second gui = new Second();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(300, 200);
        gui.setVisible(true);


    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Second class inherits JFrame
public class Second extends JFrame {

    // Making two JButton variables
    private JButton reg, custom;

    // Making a constructor for the GUI
    public Second(){
        // Setting the title & the layout
        super("Title");
        setLayout(new FlowLayout());

        // Assigning reg variable to a JButton with a value
        reg = new JButton("Regular Button");
        // Adding the variable
        add(reg);

        // Making two ImageIcon variables and assigning them a file from our src
        Icon ovRank = new ImageIcon(getClass().getResource("Overlord Rank.png"));
        Icon logo = new ImageIcon(getClass().getResource("raidpvp-logo.png"));

        // Assigning custom variable to a JButton with a value and an image
        custom = new JButton("Custom Button", logo);
        // Assigning an event to the variable which will execute when the button is rolled over aka. hovered upon with cursor
        custom.setRolloverIcon(ovRank);
        // Adding the variable
        add(custom);

        // Creating the object of the event handling class
        HandlerClass handler = new HandlerClass();
        // Assigning an event to the buttons
        reg.addActionListener(handler);
        custom.addActionListener(handler);

    }

    // Creating the event handling class
    private class HandlerClass implements ActionListener{
        public void actionPerformed(ActionEvent event){
            // Handling the event to where it will display a message dialog on position: null (center) and with a value of the source name Ex: If reg button is clicked it will display: Regular button, which was taken when assigning the variable to the JButton
            JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
        }
    }
}