I am working on a simple image guessing game. Instead of having a jLabel for each image, I'm using only one jLabel and it changes its icon using arrays when a button is clicked after the image has been guessed correctly.
But how can I code it so that the answer required in the jTextField (txtAnswer) is determined by the icon set in the jLabel?
So for instance, if the current icon is of the Aston Martin DBS and the user guesses correctly, the icon will then change to the Ferrari 458. What must I do then to ensure that the txtAnswer will now require the user to enter "Ferrari 458" to guess correctly based on the image icon that is set?
Here is the code I currently have:
private static String[] imageList = {"/carGuessPackage/2010 Aston Martin DBS.jpg", "/carGuessPackage/2010 Ferrari 458 Italia.jpg"};
//This method is called in the constructor to set the first image on startup
public void firstIcon()
{
ImageIcon image;
image = new javax.swing.ImageIcon(getClass().getResource(imageList[0]));
lblImage.setIcon(image);
}
private void btnCheckActionPerformed(java.awt.event.ActionEvent evt) {
ImageIcon image;
if(imageList[0].equals(true))
{
if("Aston Martin DBS".equals(txtAnswer.getText()))
{
image = new javax.swing.ImageIcon(getClass().getResource(imageList[1]));
lblImage.setIcon(image);
}
else
{
JOptionPane.showMessageDialog(this, "Incorrect");
}
}
}
Check out the JLabel.setIcon() method. You would need and array of Icon objects, and they would be passed to the existing JLabel.
Related
How do I cover all my JButton with the ImageIcon given?
my JButtoon size is 90x90 and my Image as well
I also set a text to my JButton (the text is necessary for the program to work)
Code: (I get a padding inside mi button)
btnBoton[i][j].setText(Integer.toString(i)+","+Integer.toString(j));
btnBoton[i][j].setIcon(new ImageIcon("img//"+num+".jpg"));
(When I comment my setText):
//btnBoton[i][j].setText(Integer.toString(i)+","+Integer.toString(j));
btnBoton[i][j].setIcon(new ImageIcon("img//"+num+".jpg"));
I'm trying to acomplish as the second image but without commenting my setText
you can use these two methods to place text at the center of buttons
btnBoton[i][j].setHorizontalTextPosition(JButton.CENTER);
btnBoton[i][j].setVerticalTextPosition(JButton.CENTER);
and texts will be placed in center of buttons,
if you want to assign a value to buttons and don't showing any text, instead of .setText(),create a new class like MJButton which extends JButton and create a String field to it named tag or data or etc. then encapsulate the field and use .setTag() and .getTag() to do so.
class MJButton extends JButton {
private String tag;
public MJButton(String tag, Icon icon) {
super( icon);
this.tag = tag;
}
public MJButton() {
super();
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
so use this new class to create buttons, in two ways:
1: btnBoton[i][j] = new MJButton();
and call .setTag() for them:
btnBoton[i][j].setTag(Integer.toString(i)+","+Integer.toString(j));
2: assign icon and tag to button in one line using second constructor
btnBoton[i][j] = new MJButton((Integer.toString(i)+","+Integer.toString(j)), new ImageIcon("img//"+num+".jpg"));
I wonder why am getting null in my comparison that checks if two JButtons have the same ImageIcon? Here is my class
public class Card extends JButton{
// Instance Variables
private ImageIcon icon;
private static final int CARD_SIZE = 165;
public Card(ImageIcon icon){
setIcon(ResizeIcon(icon));
this.icon = icon;
setOpaque(true);
setBorder(new EmptyBorder(0,0,0,0));
// Preferred card size
setPreferredSize(new Dimension(CARD_SIZE, CARD_SIZE));
}
public boolean SameIcon(Card card){
System.out.println(((ImageIcon)this.getIcon()).getDescription());
return getIcon() == card.getIcon();
}
// Resize the image to fit into JButton regardless of its original dimensions
private ImageIcon ResizeIcon(ImageIcon imagIcon){
Image img = imagIcon.getImage();
Image newimg = img.getScaledInstance(CARD_SIZE - 5, CARD_SIZE - 5, java.awt.Image.SCALE_SMOOTH);
return new ImageIcon(newimg);
}
}
My question is basically why i get null when i do (ImageIcon)this.getIcon().getDescription(). It seems like setIcon only sets only ImageIcon and not the Icon. Because it shows on the JButton that an ImageIcon is present but when i try to retrieve it, it get null
I changed to Resize method to return an Image instead so it looked as follows
private Image ResizeIcon(ImageIcon imagIcon){
return (imagIcon.getImage()).getScaledInstance(
CARD_SIZE - 5,
CARD_SIZE - 5,
java.awt.Image.SCALE_SMOOTH);
}
then when calling the setIcon() Method of any specific JButton, i say
setIcon(new ImageIcon(ResizeIcon(icon), icon.toString()));
Remember, icon is an ImageIcon variable so its easier to get the location string. I compare the strings instead.
I know its a bit not wise to compare strings, but it proved to be a way out forthe time being
I made a game using NetBeans design tool, called WordHunt. It looks like this:
I need to make a class that will apply a mouseover effect to those 16 labels I have. This is the code that changes the icon B when enter the mouse:
private void b1MouseEntered(java.awt.event.MouseEvent evt) {
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
}
I had applied a default icon to the label.
After making that class, instead of writing:
b1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png")));
to write className(b1 ,B);
For the next label, the same thing
className(b2 ,C);
Observation: b1 is a label and I have all letters icon in .png format from A to Z.
Can anybody give me an idea of how I can do that?
If I understand what you want to do, you can use this method:
public void setRolloverIcon(Icon rolloverIcon)
defined in the class JButton to configure the rollover icon.
Just create a simple class like this:
class HoverEffectButton extends JButton{
HoverEffectButton(Image img1, Image img2) {
super(new ImageIcon(img1));
this.setRolloverIcon(new ImageIcon(img2));
}
}
Hope this will help.
And of course you can create a helper class that permits to load an image according to the image name
class AssetsHelper{
private static final String DEFAULT_ASSETS_ROOT = "assets/";
private static final String DEFAULT_IMAGE_SUBFIX = ".png";
public static Image loadImage(String name){
BufferedImage img = null;
try {
img = ImageIO.read(new File(DEFAULT_ASSETS_ROOT + name + DEFAULT_IMAGE_SUBFIX));
} catch (IOException e) {
....
}
return img;
}
}
How about something like this: (rough draft)
// for storage so we don't load it for each mouse-over
HashMap<String, ImageIcon> images = new HashMap<String, ImageIcon>();
void setIcon(JLabel button, String image)
{
if (images.containsKey(image))
return images.get(image);
else
{
String path = "/ip/imag/" + image + ".png";
ImageIcon icon = new ImageIcon(getClass().getResource(path));
images.put(image, icon);
return icon;
}
}
And then:
setIcon(b1, "B");
But you should probably consider using buttons so you can use setRolloverIcon rather than MouseEntered.
public class MyButton extends JButton {
private ImageIcon normalIcon;
private ImageIcon hoverIcon;
public MyButton(String normalURL) {
String hoverURL = normalURL.replaceFirst("\\.png$", "-hover.png");
normalIcon = new ImageIcon(getClass().getResource("/ip/imag/" +B+ ".png"); // or so
hoverICon = ...
}
private void b1MouseEntered(MouseEvent evt) {
setIcon(hoverIcon);
}
}
Firstly at the top of your code add this import:
import javax.swing.ImageIcon;
//Then you only need to write
new ImageIcon(...);
Instead of:
new javax.swing.ImageIcon(...)
Already shorter :)
Then you can create a hashmap of the images preloaded where each instance of B is the key and the loaded icon is the value.
if i get u well i think you want just an image and not evry image to chang when mouse is on it right. if that is the case what u should do is to get the position of each image in a buffer and compare it with the mouse x n y position to know wc image to change. I hope this solve your problem
I would like to write a program in java...
I want to set the shape of the window(a JFrame) to a set of PNG Images(with a transparent background).
(Actually, I would like to make the window change its shape continual, and it look like an animation!)
And, I read images from files,save them to a array, then, I use class GeneralPath to get the area of my animated character(in png images), save it to areaArray.
After all things are done, I start the paint thread. It works well...But sometimes the window would flash(ah...I mean a flicker happened, but the background color I saw when flashing is transparent, I could saw my desktop wallpaper!).
I don't want to see the flicker/flash again, would someone help me? Thanks!
P.S. : Sorry for my poor English!
public class JCustomFrame extends JFrame implements Runnable
{
private final int max_frame=18; //Here is the max numbers of my png images
private BufferedImage[] BufImageArray; //The array to save all the png images
private BufferedImage nowImage; //Save the image to be drawn in this turn
private int counter; //Indicate which png image to be drawn
private Area[] areaArray; //Save the shapes of the animated character in each png image
public void run()// a thread function to paint the frame continual
{
while(true){
if(counter==max_frame)counter=0;
nowImage=BufImageArray[counter];
setShape(areaArray[counter]);
repaint();
try{
Thread.sleep(100);
}catch(InterruptedException e){
System.out.println("Thread.sleep error!");
}
counter++;
}
}
public JCustomFrame()
{
super();
setUndecorated(true);
setBackground(new Color(0,0,0,0));
counter= 0;
//...some codes here
new Thread(this).start();
}
public void paint(Graphics graphic)
{
graphic.drawImage(nowImage,0,0,this);
}
}
Here is a sample code to run the program:
import javax.swing.*;
public class MainFrame
{
public static void main(String[] args)
{
JCustomFrame myFrame = new JCustomFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,400);
myFrame.setVisible(true);
return ;
}
}
I modified 2 lines above, the "png file name" and the "max_frame" to apply the new image files.
I found that if I put the same program on Windows rather than my OpenSuse, it works very well(without the flicker), here I upload all the pack of my source(include the image file).
Here my code is.
Thanks again.
==================================================================================
Thanks Andrew Thompson for suggestions.
This time, I try to delete the codes unrelated to the problem, and paste a gif to show the situation. The codes above isn't runnable, but the source code in the link works well.
P.S. The flicker/flash happened in random frame, isn't completely the same as the gif shows.
('cause I could only add a transparent panel in my gif image at a fixed sequence)
Thanks!!
How can I display a series of images one by one every time the user clicks the next button?
I have few images stored in array. I used button next to go from image to image. How to programme the button? I used action listener but I just don't know how to get back to the array.
I know I'm being lazy here by not writing the entire code, but here goes anyway.
class whatEver implements ActionListener{
JButton btnNext = new JButton();
static int fileNumber = 0;
static int totalFiles;
void functionLoadInterface () //Function with
{
btnNext.addActionListener(this);
//Initialize array ImageArray with file paths.
}
public void cycleImage()
{
String file = ImageArray[fileNumber%totalFiles];
//Code to load the image wherever follows
}
public void actionPerformed(ActionEvent e)
{
filenumber++;
this.cycleImage();
}