How do I display images in GridGagLayou开发者_运维百科t
format?
I'm making a card game (3 card poker to be exact) I managed to display the card names like 3 of Hearts as a JLabel
and whatnot, but I don't know how to display image(s) and how do I position it where I want to like..
JLabel label = new JLabel("Deal");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 2;
pane.add(label, c);
And where should I store the image files, anywhere on the drive, or in the project folder?
edit: hey thx i kinda figure it out myself but just to make sure i did:
card=new ImageIcon("G:\\CS3\\png cards\\Card Back.png");
c1 = new JLabel(card);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(c1, c);
so this does show the images i want it ,looks its working fine right now so is there any problems with this coding?
Take a look at the java gridbag tutorial for an idea on how to layout items http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
But the basic concept is that as you add components they are assigned a location on a grid and they can take multiple cells in that grid. Just be aware that it can be tedious at times.
In terms of adding an image there are a few ways but possibly the cleanest way that I know of is by creating a BufferedImage and then adding that image to a jpanel as an image icon:
InputStream imageStream = this.getClass().getResourceAsStream("resources/image.jpeg")
BufferedImage image = ImageIO.read(imageStream);
JLabel picLabel = new JLabel(new ImageIcon(image))
you then have a JLabel which is an image and you can add this to your pane.
pane.add(picLabel);
Finally, in terms of storing the images you should create a resources folder in your project and if your class path is set correctly then you can use the getResourceAsStream()
method on class to get your image.
精彩评论