I'm trying to program an online version of the board game RISK. and I would like to place JButtons on the board. So basically I want JButtons on top of some images, however I can't get it to work. Here is my code:
public void main(String[] args){
JFrame frame = new JFrame("RISK");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("test");
button.setBounds(100, 100, 150, 150);
panel.add(button);
frame.setVisible(true);
frame.add(new graphics());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
try{
BufferedImage board = ImageIO.read(new File("board.jpg"));
}catch(IOException e){}
g.drawImage(board, 0, 0, null);
}
Thank you very much in advance. - your answer does not need to refer to this specific code, just a general example with graphics and JButtons would be amazing!
paintComponent(Graphics g) {.. BufferedImage board = ImageIO.read(..
Don't attempt to read images within the paint methods, and don't block the paint method with long running tasks. The image should be read before then, and cached as a class attribute. 3) frame.setSize(800, 600);
Set the preferred size of the components (if need be) rather than the size of the frame. 4) button.setBounds(100, 100, 150, 150);
Use Layout Managers!Andrew Thompson 2012-04-05 19:00
frame.add(new graphics());
Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use it consistently. 6) catch(IOException e){}
Don't do that, especially in code that 'does not work'. Use catch(IOException e){ e.printStacktrace(); }
instead. 7) g.drawImage(board, 0, 0, null);
I'd be willing to bet that a graphics
object is an ImageObserver
. So that should be g.drawImage(board, 0, 0, this);
Andrew Thompson 2012-04-05 19:30
You can add images on button if your wish is that. Here is an example code.
BufferedImage myPictur =ImageIO.read(getClass().getResourceAsStream("/resources/shoppingicon.png"));
JButton shoppingButton = new JButton("Shopping",new ImageIcon(myPicture));
First of all for online applications specially web, Swing will not work as it is designed for desktop applications. If you would like a Swing like web application then use
Java Web Start
JApplet
GWT
now for the botton to contain a background image use:
BufferedImage buferedImage;
JButton buttonImage;
buferedImage = ImageIO.read(getClass().getResourceAsStream("button-image-1.jpg"));
buttonImage = new JButton("Start", new ImageIcon(buferedImage));
JApplet
? 3) Even a Swing based JFrame
that is not launched using Java Web Start can easily act as the client-side consumer of a web-app - Andrew Thompson 2012-04-05 19:14