Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Var's that store images in java?

Options
  • 14-11-2007 5:42pm
    #1
    Registered Users Posts: 26,579 ✭✭✭✭


    can this be done?

    basically i have a JPanel for arguments sake lets declare it like this
        //(x,x) has values obviously enough.
        JPanel myPanel = new JPanel(new GridLayout(x,x));
    
    want i want to be able to do is to say this.
        myPanel.add(myImage);
        //where myImage = a file in the same directory are the .java/.class files are.
    
    i've tried doing this. (added the below to the top of the .java file).
    import java.awt.Image;
    
    i declare an image like this.
    Image myImage = Toolkit.getDefaultToolkit().getImage("dice1.gif");
    
    i got this from a tutorial from google.

    anyone have any pointers (god i miss c++)


Comments

  • Moderators, Science, Health & Environment Moderators Posts: 10,079 Mod ✭✭✭✭marco_polo


    Cremo wrote: »
    can this be done?

    basically i have a JPanel for arguments sake lets declare it like this
        //(x,x) has values obviously enough.
        JPanel myPanel = new JPanel(new GridLayout(x,x));
    
    want i want to be able to do is to say this.
        myPanel.add(myImage);
        //where myImage = a file in the same directory are the .java/.class files are.
    
    i've tried doing this. (added the below to the top of the .java file).
    import java.awt.Image;
    
    i declare an image like this.
    Image myImage = Toolkit.getDefaultToolkit().getImage("dice1.gif");
    
    i got this from a tutorial from google.

    anyone have any pointers (god i miss c++)

    I cannot test this now but I think this ought towork. (Can't remember off the top of my head which package the ImageIcon class in I believe it is javax.swing)
    myPanel.add(new JLabel(new ImageIcon("dice1.gif")));
    


  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Yep, that should work perfectly.


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    cheers that works guys,

    it's a bit of an arse ways around it though, i thought with the likes of Java i could do something like this...

    Image myImg = new Image("image.gif");

    and on a side note, i despise java's case sensitivity :mad:


  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Most languages are case sensitive.


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    sorry possibly the wrong words.

    what i meant is in data types.

    String is not the same as string etc.

    guess i'm just stuck in my C ways where most primitive data types were lower case :p


  • Advertisement
  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    String is an object in java though (an array of chars) ;) int is a datatype.


  • Registered Users Posts: 1,996 ✭✭✭lynchie


    Cremo wrote: »
    sorry possibly the wrong words.

    what i meant is in data types.

    String is not the same as string etc.

    guess i'm just stuck in my C ways where most primitive data types were lower case :p

    And like C, Java primitive data types are also in lower case too!!


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    ok my head is melting here, i need your help again guys.

    basically i've to code this game that has the same rules as poker (5 card poker) but with using dice. you get served a set of 5 dice and the user has the option of keeping all none or 4 dice.

    now what i'm trying to do is to construct a Dice class that holds a integer number that represents the value of the dice, and then a image that hold a jpg that corresponds to that dice number.

    here's my dice class so far.
    public class Dice{
    
    	private String[] dice_img = {"dice1.gif", "dice2.gif", "dice3.gif", "dice4.gif", "dice5.gif", "dice6.gif"};
    	private int face ;
    	private JLabel face_img;
    
    
    	public Dice(){
    		//generate random number 1 = min range 6 = values in range.
    		double rand = 1 + (Math.random() * 6);
    		face = (int) rand;
    		//do a swtich statement here with face as the case, set the face_img = the icon of the face int value
    		switch(face){
    			case 1: face_img = new JLabel(new ImageIcon(dice_img[0])); break;
    			case 2: face_img = new JLabel(new ImageIcon(dice_img[1])); break;
    			case 3: face_img = new JLabel(new ImageIcon(dice_img[2])); break;
    			case 4: face_img = new JLabel(new ImageIcon(dice_img[3])); break;
    			case 5: face_img = new JLabel(new ImageIcon(dice_img[4])); break;
    			case 6: face_img = new JLabel(new ImageIcon(dice_img[5])); break;
    			default: System.out.println("ERROR!");
    		}
    
    		face_img = new JLabel(new ImageIcon(dice_img[0]));
    
    	}
    
    	public void Roll(){
    		double rand = 1 + (Math.random() * 6);
    		face = (int) rand;
    	}
    
    	public int get_face(){
    		return face;
    	}
    
    	public JLabel get_face_img(){
    		return face_img;
    	}
    
    	public String toString(){
    
    		String s = "" ;
    		s += face;
    		return s ;
    

    i then have a DiceSet class that includes an array of 5 dice.
    public class DiceSet{
    
    	private static final int SET_SIZE = 5;
    
    	//array for 5 dice.
    	private Dice[] set = new Dice[SET_SIZE];
    	private JPanel five_dice ;
    
    	//Constructor.
    	public DiceSet(){
    		five_dice = new JPanel(new GridLayout(0,5));
    		System.out.println("Creating new DiceSet");
    		for(int i = 0 ; i < set.length ; i++){
    			set[i] = new Dice();
    			five_dice.add(set[i]);
    			System.out.println(set[i]);
    		}
    	}
    
    	public void show(){
    		for(int i = 0 ; i < set.length ; i++){
    			System.out.println(set[i]);
    		}
    	}
    
    	public JPanel get_five_dice(){
    		return five_dice;
    	}
    
    	public Dice getDice1(){
    		return set[0];
    	}
    
    	public Dice getDice2(){
    			return set[1];
    	}
    
    	public Dice getDice3(){
    			return set[2];
    	}
    
    	public Dice getDice4(){
    			return set[3];
    	}
    
    	public Dice getDice5(){
    			return set[4];
    	}
    
    	public Dice getDice6(){
    			return set[5];
    	}
    

    now in my main class - DiceGame - i want to be able to create a panel and add the set of dice to the panel and display the images of the random dice.
    public class DiceGame extends JFrame{
    
    	//vars for UI
    	private Container pane;
    
    	
    
    	//vars for dicepanel
    	private JPanel dicepanel ;
    	private DiceSet set_of_dice ;
    	
    	//var for poker coloured table
    	private Color Background = new Color(51,79,30);
    
    	public DiceGame(){
    		//set up the window.
    		super("Supper fun happy poker!");
    		this.setSize(800, 600);
    
    		set_of_dice = new DiceSet();
    
    		setContentPane(createContentPane());
    		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		this.setVisible(true);
    	}
    
    	private Container createContentPane(){
    		pane = new JPanel(new BorderLayout());
    		pane.setBackground(Background);
    
    		//the below components are added to the main pane's CENTER region.
    
    
                    //here's where i'm trying to add the random dice to the screen 
    		//panel to hold the dice.
    		dicepanel = new JPanel();
    		dicepanel.add(set_of_dice.getDice1());
    
    		dicepanel.setBorder(new BevelBorder(BevelBorder.RAISED));
    		dicepanel.setBackground(Background);
    
    
    		pane.add(dicepanel);
    
    		
    		return pane;
    	}
    
    
    	public String show_score(){
    		String s = "";
    		s+= player_score;
    		return s;
    	}
    
    	/*public boolean check_pair(){
    		int pair = 0;
    		for(int i = 0 ; i < test_set.length ; i++){
    			if(test_set[i] == test_set[i+1]){
    				pair++;
    				return true;
    			}
    			else
    				return false;
    		}
    
    	}*/
    
    	public static void main(String args[]){
    		DiceGame game = new DiceGame();
    	}
    }
    

    when i run this i get a NullPointerException, anyone any ideas? i'll owe you a drink.


  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Paste the stacktrace.

    Also, you'll need to do this.

    dicepanel.add(set_of_dice.getDice1().get_face_img());

    instead of

    dicepanel.add(set_of_dice.getDice1());

    It works for me, so I don't know what's wrong. The stacktrace will show where the error is occuring.


  • Moderators, Science, Health & Environment Moderators Posts: 10,079 Mod ✭✭✭✭marco_polo


    public static void main(String args[]){
        try{		
            DiceGame game = new DiceGame();
        }catch( Exception e){
             e.printStackTrace();
        }
    

    Add the folowing lines, run it again and post up the output. Null pointers can be devilishly hard to find, this will give us more info.


  • Advertisement
  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    k i've made the change giblet pointed out and also printed out the stack trace. this is what i got...
    java.lang.NullPointerException
                 at DiceGame.createContentPane(DiceGame.java:127)
                 at DiceGame.(init)(DiceGame.java:81)
                 at DiceGame.main(DiceGame.java:236)
    press any key to continue...
    


    line 127 in my code is ... dicepanel.add(set_of_dice.getDice1().get_face_img());

    line 81 is ... setContentPane(createContentPane());

    line 236 is ... DiceGame game = new DiceGame();


  • Moderators, Science, Health & Environment Moderators Posts: 10,079 Mod ✭✭✭✭marco_polo


    I'm afraid it works for me too dude (except that i don't have the images). :)

    In the code you have posted you initailise the set_of_dice variable before the call to setContentPane().

    All I can think of (and how I can replicate the error) is that you may have indavertantly moved the initialisation of set_of_dice to after the call to setContentPane(), so set_of_dice is null when the method is called? Like this.
    setContentPane(createContentPane());
    set_of_dice = new DiceSet();
    

    Bar that I'm stumped :confused:


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    ahh i fixed it.

    i left out bits of my DiceGame class in previous post as not to post up all my code, never know there could be other people here doing the same assignment.

    what i had left out was i had created two objects of DiceSet and initalised one to be of type DiceSet and the other to be nothing (hence the NullPointer).

    when i got that working the dice would all show up as dice image 1. somehow in my constructor of my dice class i had the line face_img = new JLabel(new ImageIcon(dice_img[0])); i have no idea how or why that was there but it wasted precious ten minutes of my life :p

    anyways guys cheers for all the help, it is greatly appreciated. :D


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    sorry to keep calling on you guys but i've been trying to get another part done today and it's been causing me nothing by hassle.

    i have a menu bar that has a Game menu and a New Game menuItem.

    i'm trying to add a actionlistener to catch a press of New Game that will reset the set_of_dice and repaint the screen.

    i've done the three things needed for event handling.
    1. implement ActionListener
    2. register the component with the listener
    3. code what happens in the event.

    so my actionPreformed looks like this
    	public void actionPerformed(ActionEvent e) {
    
    			// get the event object
    			Object objUserInteractedWith = e.getSource();
    
    			
    			if (objUserInteractedWith instanceof JMenuItem) {
    
    				if (objUserInteractedWith == newGame) {
    					set_of_dice = new DiceSet();
                                            //this is here to show the actionevent is done. the cmd window shows this line.
    					System.out.println("pressed new game!");
    					repaint();
    
    				}
                           }
              }
    
    at the repaint() stage i want the images of the diceset to be equal to the new set_of_dice?

    in the cmd window i get a print out of the new dice numbers and the statement "pressed new game" so i know the actionevent is working it's just not updating the images.
    i force a repaint of the screen by dragging the window, but the images stay the same as the first set_of_dice.

    anyone know where i'm going wrong?


  • Moderators, Science, Health & Environment Moderators Posts: 10,079 Mod ✭✭✭✭marco_polo


    Are you removing the old dice images from the container and replacing it with the new ones? Also if you are adding and removing components you will need to call the revalidate() method to get the container to redraw itself as repaint only works on existing components.

    Something like this:
    dicePanel.remove(set_of_dice.getDice1().get_face_img());
    set_of_dice = new DiceSet();
    dicePanel.add(set_of_dice.getDice1().get_face_img());
    revalidate();
    


  • Registered Users Posts: 26,579 ✭✭✭✭Creamy Goodness


    life save marco_polo, thanks a mil.


Advertisement