Page 1 of 2 12 LastLast
Results 1 to 20 of 24

Thread: GUI help

  1. #1
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default GUI help

    Hey, first post yayyyy lulz!!!

    Im workin on a final project for class that mimicks the game show lets make a deal. i have the build of the GUI all set except i have to replace the JButton that the player chose with a JPG of a car or prize or something. I can display the JPG but its just displays under the button and makes the GUI all buggy. Im using a BorderLayout for the frame and a GridLayout in the CENTER of the frame to make the doors scale to the JFrame. Any suggestions. If you need to see the code ill post but its a lengthy class so i didnt want to paste it if it isnt neccessary. thanks in advance.

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    just post your code for the button and the picture. no need to see how everything else works. I'll get back to you after I look at some stuff. I think I remember reading that you can't attach images to a JButton(or maybe AWT button, SWT button, not sure)

  3. #3
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    Try using new JButton(Icon icon) constructor. You will need to convert your jpeg to an Icon object. Icon (Java 2 Platform SE v1.4.2)

    Here's a perfect example that paints an Icon on top of a button
    Swing Tutorial: JButton

  4. #4
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    this is the code. i tried using tutorial but it didnt quite tell me what i needed to kno.


    Java Code:
    package makeDeal;
    
    import javax.swing.*;
    
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Random;
    
    public class Doors extends JFrame{
    
    	
        	private int prizeDoor,doorChosen,eliminatedDoor;
        	private final int NUM_OF_DOORS=3;
        	private final int HEIGHT=400;
        	private final int WIDTH=500;
        	private JPanel instructions,switchDoor;
        	private JButton door1;
        	private JButton door2;
        	private JButton door3;
        	private JButton change,stay;
        	private ImageIcon winImage,loseImage;
        	private Host host;
        	private Contestant con;
    /***********************************
     * The Doors constructor initializes
     * the fields and builds a portion
     * of the GUI.    	
     ***********************************/
       
       
        public Doors(){
        	host=new Host();
        	con=new Contestant();    	
        	
        	door1=new JButton("Door 1");
        	door2=new JButton("Door 2");
        	door3=new JButton("Door 3");
        	
        	instructions=new JPanel();
        	JLabel firstInstructions=new JLabel("Pick a door.");
        	instructions.add(firstInstructions);
        	
        	buildDoorPanel();    	
        	buildCommunicationPanel();
        	
        	winImage=new ImageIcon("C:\\Users\\Owner\\Pictures\\project JPGS\\winImage.jpg");
        	loseImage=new ImageIcon("C:\\Users\\Owner\\Pictures\\project JPGS\\loseImage.jpg");
        	
        	setVisible(true);
        	  	
        }
    	/******************************************
    	 * The buildDoorPanel builds the portion
    	 * of the frame that has the door buttons
    	 * and registers them to the ButtonListener
    	 * class.
    	 *******************************************/
        public void buildDoorPanel(){
        	JPanel panel= new JPanel();
        	JPanel blank=new JPanel();
        	panel.add(instructions);
        	
        	//Creates the look and layout of the GUI.
        	setTitle("Lets Make a Deal!");
        	setSize(WIDTH,HEIGHT);
        	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	setLayout(new BorderLayout(30,10));
        	
        	//Adds the components to the container.
        	JPanel doorPanel=new JPanel();
        	doorPanel.setLayout(new GridLayout(1,3));
        	doorPanel.add(door1);
        	doorPanel.add(door2);
        	doorPanel.add(door3);    	
        	add(doorPanel, BorderLayout.CENTER);   	
        	add(panel, BorderLayout.NORTH);
        	add(blank,BorderLayout.SOUTH);
        
        	//Registers each of the buttons.
        	door1.addActionListener(new ButtonListener());
        	door2.addActionListener(new ButtonListener());
        	door3.addActionListener(new ButtonListener());
        }
       /*******************************************
        * The buildCommunicationPanel method builds
        * the buttons that prompt the user to either 
        * switch their door with the host or keep
        * the one they chose initially.
        *******************************************/
        public void buildCommunicationPanel(){
        	switchDoor=new JPanel();
        	stay=new JButton("Stay");
    		change= new JButton("Switch");
    		
    		switchDoor.add(stay);
    		switchDoor.add(change);
    		add(switchDoor,BorderLayout.SOUTH);
    		stay.addActionListener(new CommunicationListener());
    		change.addActionListener(new CommunicationListener());
        }
        
        public int getPrizeDoor()
    	{
    		return prizeDoor;
    	}
    	
    	public void setPrizeDoor()
    	{
    		Random randNum = new Random();
    		prizeDoor=randNum.nextInt(NUM_OF_DOORS);
    	}
    /*********************************************
     * The playGame method runs the game after the 
     * door is chosen by the player.
     *********************************************/
    	public void playGame(){
    		//Initializes the doorChosen and prizeDoor variables.
    		int doorChosen=con.getDoorChosen();
    		setPrizeDoor();
    		prizeDoor=getPrizeDoor();
    		
    		//Gets the eliminated door from the host class.
    		host.setEliminatedDoor(con,prizeDoor);
    		eliminatedDoor=host.getEliminatedDoor();
    		
    	}
    /***********************************************
     * The ButtonListener inner class is used	
     * after the user chooses a door from the 
     * graphical interface.
     ***********************************************/
    
    private class ButtonListener implements ActionListener{
    	@SuppressWarnings("deprecation")
    	public void actionPerformed(ActionEvent e){
    				
    		JLabel secondInstructions=new JLabel("Would you like to keep or change doors.");			
    		instructions.add(secondInstructions);
    		
    		//This set of if else statements is used to initialize
    		//the doorChosen field of the contestant class.
    		if(eliminatedDoor<0){
    			if(e.getSource()==door1){			
    			con.setDoorChosen(0);}
    		else if(e.getSource()==door2){			
    		con.setDoorChosen(1);}
    		else if(e.getSource()==door3){			
    			con.setDoorChosen(2);}}
    		
    		//This set of if else statements turns the door eliminated
    		//by the host black and then disables the eliminated door.
    		if(eliminatedDoor==0){
    			door1.setBackground(Color.BLACK);
    			door1.disable();}
    		else if(eliminatedDoor==1){
    			door2.setBackground(Color.BLACK);
    			door2.disable();}
    		else if(eliminatedDoor==2){
    			door3.setBackground(Color.BLACK);
    			door3.disable();}
    		
    		playGame();
    		
    		System.out.print("prize door"+prizeDoor+"   chosen "+doorChosen+"    eliminated      "+eliminatedDoor);
    		
    		setVisible(true);
    		
    	
    		}
    
    	
    	}
    private class CommunicationListener implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		int win;
    		JLabel icon=new JLabel();
    		
    		if(e.getSource()==change)
    			con.switchDoors(host);
    		System.out.println("after switch"+con.getDoorChosen());
    		
    		con.determineWin(getPrizeDoor());
    		win=con.getWins();
    		
    		if(win>0){
    			icon.setIcon(winImage);
    			add(icon,BorderLayout.CENTER);
    			setVisible(true);}
    		else{
    			icon.setIcon(loseImage);
    			add(icon,BorderLayout.SOUTH);
    			setVisible(true);}
    	
    		}
    }
    }

  5. #5
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    Your saying you want the button to be the jpeg image or you want a button with the image over it? If it's the latter(which seems to be 1000x easier to do) then
    Java Code:
    ImageIcon cup = new ImageIcon("images/cup.gif");
        JButton button2 = new JButton(cup);
        content.add(button2);
    should do exactly that.

  6. #6
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    my problem is that the button has to show up initially then after the game is played, display the .jpg. where the door was. I believe that sense the button has already been built and added i cant just do JButton button2=new JButton(cup); or atleast its not working

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I wonder if it would be better to use a JPanel and CardLayout that first displays a JButton, and then displays a JLabel with an ImageIcon that holds your image. This way your button or other code can tell the CardLayout when it should swap.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    for example:
    Java Code:
    import java.awt.CardLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class Door
    {
      private static final String IMAGE_PATH = "C:/Users/Owner/Pictures/project JPGS/";
      private static final String[] IMAGES = 
      { "winImage.jpg", "loseImage.jpg"};
      
      private static final String BUTTON = "Button";
      private static final String LABEL = "Label";
      
      private JPanel mainPanel = new JPanel();
      private CardLayout cardlayout = new CardLayout();
      
      public Door()
      {
        JLabel label = createLabel();
        JButton button = new JButton("Door");
        button.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent arg0)
          {
            // swap card to show label
            cardlayout.show(mainPanel, LABEL);
          }
        });
        
        mainPanel.setLayout(cardlayout); // set layout of jpanel to cardlayout
        mainPanel.add(button, BUTTON); // add button first with BUTTON string
        mainPanel.add(label, LABEL); // add label second with LABEL const string
      }
    
      private JLabel createLabel()
      {
        JLabel label = new JLabel();
        try
        {
          ImageIcon[] icons = new ImageIcon[IMAGES.length];
          for (int i = 0; i < icons.length; i++)
          {
            icons[i] = new ImageIcon(ImageIO.read(new File(IMAGE_PATH +
              IMAGES[i])));
          }
          Random random = new Random();
          label.setIcon(icons[random.nextInt(icons.length)]);
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
        return label;
      }
    
      public JComponent getPanel()
      {
        return mainPanel;
      }
      
      private static void createAndShowGUI()
      {
        JFrame frame = new JFrame("Door Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Door().getPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowGUI();
          }
        });
      }
    }

  9. #9
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    Thanks for the suggestion Fubarable, but im not to familiar with the CardLayout, i might not be able to fix some problems that could come up.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    That may not be a good reason for not using the appropriate tool. If you don't understand something, you would do well to read up on it and learn about it. I suggest that you read the CardLayout tutorial: How to Use CardLayout (The Java™ Tutorials > Creating a GUI with JFC/Swing > Laying Out Components Within a Container)

    You do have a link to the Sun Tutorials Really Big Index, right?
    The Really Big Index

  11. #11
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    That may not be a good reason for not using the appropriate tool. If you don't understand something, you would do well to read up on it and learn about it. I suggest that you read the CardLayout tutorial:
    I took your advice and read the tut. I implemented it in program and i got it to work. not to mention thats a cool layout, thanks.:D

  12. #12
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    Ok, i thought i had this workin but i guess i was wrong. i tried testing out the code and adding it to the WEST space on the boderlayout and just tried to make the button switch so i knew i had the code write. can anyone tell me y it wont work, the code is in the buildDoorPanel() method and sectioned out with slashes.
    Java Code:
    package makeDeal;
    
    import javax.swing.*;
    
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Random;
    
    public class Doors extends JFrame{
    
    	
        	private int prizeDoor,doorChosen,eliminatedDoor;
        	private final int NUM_OF_DOORS=3;
        	private final int HEIGHT=400;
        	private final int WIDTH=500;
        	private JPanel instructions,switchDoor,doorPanel,card1,card2;
        	private JButton door1;
        	private JButton door2;
        	private JButton door3;
        	private JButton change,stay,restart,test,test1;
        	private ImageIcon winImage,loseImage,door;
    		private CardLayout cardLayout;
        	private Host host;
        	private Deal newGame;
    		private Contestant con;
    		final String TEST="test";
    		final String TEST1="change";
    		JPanel cards;
    /***********************************
     * The Doors constructor initializes
     * the fields and builds a portion
     * of the GUI.    	
     ***********************************/
       
       
        public Doors(){
        	host=new Host();
        	con=new Contestant();    	
        	
        	
        	door=new ImageIcon("C:\\Users\\Owner\\Pictures\\project JPGS\\door.jpg");
        	door1=new JButton(door);
        	door2=new JButton(door);
        	door3=new JButton(door);
        	
        	    	
        	
        	instructions=new JPanel();
        	
        	
        	JLabel firstInstructions=new JLabel("Pick a door.");
        	instructions.add(firstInstructions);
        	
        	buildDoorPanel();    	
        	buildCommunicationPanel();
        	
        	winImage=new ImageIcon("C:\\Users\\Owner\\Pictures\\project JPGS\\winImage.jpg");
        	loseImage=new ImageIcon("C:\\Users\\Owner\\Pictures\\project JPGS\\loseImage.jpg");
        	
        	setVisible(true);
        	  	
        }
    	/******************************************
    	 * The buildDoorPanel builds the portion
    	 * of the frame that has the door buttons
    	 * and registers them to the ButtonListener
    	 * class.
    	 *******************************************/
        public void buildDoorPanel(){
        	JPanel panel= new JPanel();
        	JPanel blank=new JPanel();
        	panel.add(instructions);
        	
        	//Creates the look and layout of the GUI.
        	setTitle("Lets Make a Deal!");
        	setSize(WIDTH,HEIGHT);
        	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	setLayout(new BorderLayout(30,10));
        	
        	//Adds the components to the container.
        	doorPanel=new JPanel();
        	doorPanel.setLayout(new GridLayout(1,3));
        	doorPanel.add(door1);
        	doorPanel.add(door2);
        	doorPanel.add(door3);    	
        	add(doorPanel, BorderLayout.CENTER);   	
        	add(panel, BorderLayout.NORTH);
        	add(blank,BorderLayout.SOUTH);
        
        	//Registers each of the buttons.
        	door1.addActionListener(new ButtonListener());
        	door2.addActionListener(new ButtonListener());
        	door3.addActionListener(new ButtonListener());
     //////////////////////////////////////////////////////////////  
        	//cardLayout = new CardLayout();
        	cards=new JPanel();
        	card1=new JPanel();
        	card2=new JPanel();
        	
        	test=new JButton("test");
        	test1=new JButton("test1");
        	cards.setLayout(new CardLayout());
        	card1.add(test);
        	card2.add(test1);
        	cards.add(card1, TEST);
        	cards.add(card2,TEST1);
        	add(cards, BorderLayout.WEST);	
        	test.addActionListener(new CardListener());
     //////////////////////////////////////////////////////////////////   	
        	
        }
        	
        	
        	
        
       /*******************************************
        * The buildCommunicationPanel method builds
        * the buttons that prompt the user to either 
        * switch their door with the host or keep
        * the one they chose initially.
        *******************************************/
        public void buildCommunicationPanel(){
        	switchDoor=new JPanel();
        	stay=new JButton("Stay");
    		change= new JButton("Switch");
    		restart=new JButton("New Game");
    		
    		switchDoor.add(stay);
    		switchDoor.add(change);
    		switchDoor.add(restart);
    		add(switchDoor,BorderLayout.SOUTH);
    		stay.addActionListener(new CommunicationListener());
    		change.addActionListener(new CommunicationListener());
    		restart.addActionListener(new CommunicationListener());
    		
        }
        
        public int getPrizeDoor()
    	{
    		return prizeDoor;
    	}
    	
    	public void setPrizeDoor()
    	{
    		Random randNum = new Random();
    		prizeDoor=randNum.nextInt(NUM_OF_DOORS);
    	}
    /*********************************************
     * The playGame method runs the game after the 
     * door is chosen by the player.
     *********************************************/
    	public void playGame(){
    		//Initializes the doorChosen and prizeDoor variables.
    		int doorChosen=con.getDoorChosen();
    		setPrizeDoor();
    		prizeDoor=getPrizeDoor();
    		
    		//Gets the eliminated door from the host class.
    		host.setEliminatedDoor(con,prizeDoor);
    		eliminatedDoor=host.getEliminatedDoor();
    		
    	}
    /***********************************************
     * The ButtonListener inner class is used	
     * after the user chooses a door from the 
     * graphical interface.
     ***********************************************/
    
    private class ButtonListener implements ActionListener{
    	@SuppressWarnings("deprecation")
    	public void actionPerformed(ActionEvent e){
    				
    		JLabel secondInstructions=new JLabel("Would you like to keep or change doors.");			
    		instructions.add(secondInstructions);
    		
    		//This set of if else statements is used to initialize
    		//the doorChosen field of the contestant class.
    		if(eliminatedDoor<0){
    			if(e.getSource()==door1){			
    			con.setDoorChosen(0);}
    		else if(e.getSource()==door2){			
    		con.setDoorChosen(1);}
    		else if(e.getSource()==door3){			
    			con.setDoorChosen(2);}}
    		
    		//This set of if else statements turns the door eliminated
    		//by the host black and then disables the eliminated door.
    		if(eliminatedDoor==0){
    			//door1.(loseImage);			
    			door1.disable();}
    		else if(eliminatedDoor==1){
    			//door2.setCursor(Color.BLACK);
    			door2.disable();}
    		else if(eliminatedDoor==2){
    			//door3.update(loseImage);
    			door3.disable();}
    		
    		playGame();
    		
    		System.out.print("prize door"+prizeDoor+"   chosen "+doorChosen+"    eliminated      "+eliminatedDoor);
    		
    		setVisible(true);
    		
    	
    		}
    
    	
    	}
    private class CommunicationListener implements ActionListener{
    	public void actionPerformed(ActionEvent e){
    		int win;
    		
    		if(e.getSource()==restart)
    			newGame=new Deal();
    		
    		if(e.getSource()==change)
    			con.switchDoors(host);
    		System.out.println("after switch"+con.getDoorChosen());
    		
    		con.determineWin(getPrizeDoor());
    		win=con.getWins();
    		
    		if(win>0){
    			
    			door2=new JButton(winImage);
    			setVisible(true);}
    		//else{
    			//icon.setIcon(loseImage);
    			//add(icon,BorderLayout.CENTER);
    			//setVisible(true);}
    	
    		}
    }
    private class CardListener implements ActionListener{
    	public void actionPerfomed(ActionEvent e){
    		CardLayout cl=(CardLayout) (cards.getLayout());
    		if (e.getSource()==test)
    			cl.next(cards);
    	}
    
    	@Override
    	public void actionPerformed(ActionEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    }
    }

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to simplify and shrink your code and make it compilable so we can test it. Look at my code above for an example of this. Also have a look at this site to explain how to create examples for fora better: SSCCE

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I'm also curious as to what you're trying to change here with the cardlayout. Are you trying to change the door to show an image behind it when clicked? Or that "test" button over to the left?

    As an aside, here's a nice door image:

    Last edited by Fubarable; 12-06-2008 at 11:56 PM.

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Other suggestions made while wandering through your code:

    Regarding your "instructions panel", you might not want to keep adding labels to this panel. Instead consider creating a JLabel class field (visible throughout the class), you could call it "instructionsLabel", add it once to the instructions panel (I'd call it that, "instructionsPanel"), and then when you want to change the text there, simply call setText on the label:
    Java Code:
    instructionsLabel.setText("new text here");
    I'd also put the Door concept into its own class. If I am correct in what you are trying to do, I think that you want to show a button and then display an image under the button depending on if the door is a winner or a loser. Again, this may best be represented by a JPanel that uses CardLayout and holds a JButton with a door image and displays a JLabel with winner or loser under it depending on some data. I'd create a class that does just this, debug it up and down in it's own mini program, and after debugging it to the hilt, create and display 3 of these objects all in a row.

  16. #16
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Other suggestions made while wandering through your code:

    Regarding your "instructions panel", you might not want to keep adding labels to this panel. Instead consider creating a JLabel class field (visible throughout the class), you could call it "instructionsLabel", add it once to the instructions panel (I'd call it that, "instructionsPanel"), and then when you want to change the text there, simply call setText on the label:
    Java Code:
    instructionsLabel.setText("new text here");
    I'd also put the Door concept into its own class. If I am correct in what you are trying to do, I think that you want to show a button and then display an image under the button depending on if the door is a winner or a loser. Again, this may best be represented by a JPanel that uses CardLayout and holds a JButton with a door image and displays a JLabel with winner or loser under it depending on some data. I'd create a class that does just this, debug it up and down in it's own mini program, and after debugging it to the hilt, create and display 3 of these objects all in a row.

    ur exactly right as to what im trying to accomplish with this program as far as the doors being a button that switching to a picture of the prize. Sorry for the messy bunched up code ive been workin on this project for some time and im gettin a little disorganized. ill deffinitly use that JLabel idea as well as i was tryin to figure out something to make that look better but it got pushed towards the bottom of the list as the project deadline comes up.
    Last edited by timkd127; 12-07-2008 at 02:37 AM. Reason: added content

  17. #17
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    o yea the button to the left of panel is a test run so that i could get the cardLayout code down pat before i implement it throughout the program.

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You're right to get it pat on a small scale, but again, create a small class, you could call it DoorPanel or something similar, and in it have one JPanel that uses CardLayout, have it hold a JButton that shows the door image, and swap it with another image (winner or loser or either chosen randomly) that's in an ImageIcon on a JLabel. You can give this class some public methods such as setWinner(boolean winner), and even can give it an addActionListener(ActionListener al) class so that an outside class can listen for the button click. And it can have a public reset() method, again all the methods needed to allow it to interact with the main GUI program.

    Just an idea.

  19. #19
    timkd127 is offline Member
    Join Date
    Dec 2008
    Posts
    41
    Rep Power
    0

    Default

    This is what i have so far with tryin to get the cardLayout down.
    Java Code:
    package makeDeal;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    
    public class DoorPanel extends JFrame{
    	JPanel deck, card1,card2;
    	JButton door,change;
    	String BUTTON="button";
    	String PIC="pic";
    	final private String CARD1="card 1";
    	final private String CARD2="card 2";
    	final String ImagePath="C:\\Users\\Owner\\Pictures\\project JPGS\\";
    	private JLabel image;
    	ImageIcon win;
    	
    public DoorPanel(){
    	setSize(300,300);
    	setTitle("cardLayout test");
    	setDefaultCloseOperation(EXIT_ON_CLOSE);
    	setLayout(new GridLayout());
    	deck=new JPanel(new CardLayout());
    	card1=new JPanel();
    	card2=new JPanel();
    	door=new JButton("door");
    	change=new JButton("change");
    	win=new ImageIcon("winImage.jpg");
    	image=new JLabel(win);
    	buildDeck();
    	pack();
    	setVisible(true);
    }
    	
    public void buildDeck(){
    	card1.add(door);
    	card2.add(change);
    	deck.add(card1, CARD1);
    	deck.add(card2, CARD2);
    	door.addActionListener(new ButtonListener());
    	add(deck);
    
    }
    
    private class ButtonListener implements ActionListener{
    	public void buttonClick(ActionEvent e){
    		CardLayout cl = (CardLayout)(deck.getLayout());
    		if(e.getSource()==door)
    			cl.show(deck, CARD2);
    	}
    
    	@Override
    	public void actionPerformed(ActionEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    }
    
    }
    so far im unable to get the "cards" to switch. any suggestions?

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Probably not a great idea of naming a JFrame DoorPanel

    Anywho, have a look
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class DoorPanel extends JFrame
    {
      private static final String IMAGE_PATH = "src/dy08/m12/b/images/";
      JPanel deck, card1, card2;
      JButton door, change;
      String BUTTON = "button";
      String PIC = "pic";
      private static final String CARD1 = "card 1";
      private static final String CARD2 = "card 2";
      private static final String WIN_IMAGE = "happy face.jpg";
      //final String ImagePath = "C:\\Users\\Owner\\Pictures\\project JPGS\\";
      String imagePath = IMAGE_PATH;
      private JLabel image;
      ImageIcon win;
      
      CardLayout cardlayout = new CardLayout(); // make cardlayout a field of the class
    
      public DoorPanel()
      {
        setSize(300, 300);
        setTitle("cardLayout test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout());
        //deck = new JPanel(new CardLayout());
        deck = new JPanel(cardlayout); // and use the cardlayout field here 
        card1 = new JPanel();
        card2 = new JPanel();
        door = new JButton("door");
        change = new JButton("change");
        //win = new ImageIcon("winImage.jpg");
        win = new ImageIcon(WIN_IMAGE);
        image = new JLabel(win);
        buildDeck();
        pack();
        setVisible(true);
      }
    
      public void buildDeck()
      {
        card1.add(door);
        card2.add(change);
        deck.add(card1, CARD1);
        deck.add(card2, CARD2);
        ButtonListener btnListener = new ButtonListener();
        door.addActionListener(btnListener);
        
        change.addActionListener(btnListener);
        add(deck);
    
      }
    
      private class ButtonListener implements ActionListener
      {
        public void buttonClick(ActionEvent e)
        {
          //CardLayout cl = (CardLayout) (deck.getLayout());
          if (e.getSource() == door)
          {
            cardlayout.show(deck, CARD2);
          }
          else if (e.getSource() == change)
          {
            cardlayout.show(deck, CARD1);
          }
    
        }
    
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
          buttonClick(arg0);
        }
    
      }
      
      private static void createAndShowUI()
      {
        JFrame frame = new DoorPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    
    }

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •