Reputation: 18498
Hi all im trying to do is add a button to the screen, so when the user clicks on the button a random dice picture is displayed somewhere else on the screen.
Simple
this is my code how I've tried doing it... although i cant seem to get the buttons to appear with the picture. its either one or the other. what am i doing wrong?
Any help would be appreciated. also im sure im using far too much code just to get the desired output.
ava.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class MyComponent extends JComponent {
public void paint(Graphics g) {
ImageIcon icon = new ImageIcon("dice1.png");
int x = 0;
int y = 0;
icon.paintIcon(this, g, x, y);
}
}
class Dice extends Panel
{
BufferedImage image;
public Dice(){
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel();
frame.add(panel);
JButton button2 = new JButton("Roll Die");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//execute when button is pressed
Random r= new Random();
System.out.println(r.nextInt(6)+1);
}
});
panel.add(button2);
frame.add(new MyComponent());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
}
public void paint(Graphics g){
g.drawImage(image, 0, 0, 50,50, null);
}
public static void main(String[] args)
{
Random r= new Random();
System.out.println(r.nextInt(6)+1);
new Dice();
}
}
Upvotes: 1
Views: 1449
Reputation: 1699
The issue is that the JFrame's contentPane has a BorderLayout by default and BorderLayout adds components to it's CENTER area by default. BorderLayout only supports one component in each of it's regions so when you add both yourJPanel and your custom component to the frame, only one is acutally displayed. The solution is to set the JFrame's contentPane to use another layout(FlowLayout maybe?):
frame.getContentPane().setLayout(new FlowLayout());
or to add one fo the components to another region of the BorderLayout:
frame.getContentPane.add(new MyComponent(), BorderLayout.West);
Upvotes: 1