Reputation: 33
I want to insert an image and then want to add an event to this image using Java GUI. I add the image and then try to insert it into this container but it shows error. Can you please show me which is the right way of inserting an image in Java and then adding a listener to this image or an event handler? Or if using a container to handle the image is the right way. How can I do it?
This is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
public class Back extends JFrame {
private Container pane;
public Back() {
super("title");
setLayout(null);
Icon i=new ImageIcon(getClass().getResource("1.png"));
pane=new Container();
thehandler hand=new thehandler(); //konstruktori i handler merr
//nje instance te Background
}
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
Upvotes: 0
Views: 780
Reputation: 7724
Here is an example of making a clickable button using a JButton
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITemplate {
JFrame myMainWindow = new JFrame("Title");
JPanel firstPanel = new JPanel();
private void runGUI() {
myMainWindow.setBounds(10, 10, 400, 400);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
}
private void createFirstPanel() {
firstPanel.setLayout(new FlowLayout());
ImageIcon image1 = new ImageIcon("YourImage.ImageFileType");
Image image2 = image1.getImage().getScaledInstance(300,300,0);
ImageIcon image3 = new ImageIcon(image2);
JButton jB = new JButton(image3);
jB.addActionListener(new TheHandler());
firstPanel.add(jB);
}
private class TheHandler implements ActionListener { //Changed thehandler to TheHandler
public void actionPerformed(ActionEvent event) { //because it is a class
//Do Something
}
}
public static void main(String[] args) {
GUITemplate gt = new GUITemplate();
gt.runGUI();
}
}
Upvotes: 1