I have to use the function of this class in another class in action_performed
. This code is giving me error.
public class Menu {
public void Menu()
{
try {
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));\\to get image
Image img1 = ImageIO.read(getClass().getResource("Image2.jpg"));
Image img2 = ImageIO.read(getClass().getResource("Image3.png"));
Image img3 = ImageIO.read(getClass().getResource("Image4.jpg"));
Image img4= ImageIO.read(getClass().getResource("Image5.jpg"));
Image img5= ImageIO.read(getClass().getResource("Image6.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
f1.setVisible(true);
JPanel P1=new JPanel();
P1.setVisible(true);
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
b1.add(P1);
b1.setVisible(true);
P1.add(f1);
} catch (IOException ex) {
}
}
}
Cant add more details and this is all I can tell Just tell me how to solve this problem as quick as possible.
Remove the line:
P1.add(f1);
This will give you a java.lang.IllegalArgumentException because you are trying to add a window to a container. It should work if you remove that line.
However, your code is totally incorrect. You are adding a JFrame to a JPanel and adding the JPanel to the JButton, it should be the opposite way around.
For example, this will work for you:
public void Menu()
{
Image img = ImageIO.read(getClass().getResource("Image1.jpg"));
JFrame f1=new JFrame("Menu");
f1.setSize(400,200);
JPanel P1=new JPanel();
JButton b1=new JButton("Creamy Chocolate Cup");
b1.setIcon(new ImageIcon(img));
P1.add(b1);
f1.add(P1);
f1.setVisible(true);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.