Results 1 to 13 of 13
  1. #1
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default having issues getting my action listener to listen to my combo boxes

    So, i have my final project for my programming class and I'm making pong. This is ten times harder than i thought it would be, especially since our teacher left us on do loops and then dropped this project on us. Anyway, i need my ComboListener to update the variables and send them back to the interface so it can display a play button. unfortunately it isn't updating the variables and my friends having the same issue, some guidance on this would be nice because our teacher isn't much help. here's what i have so far.

    the interface or JFrame:

    XML Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class PongInterfaceViewer extends JFrame
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	public static void main(String[]args) throws IOException
    	{
    		ActionListener listener = (ActionListener) new ComboListener();
    		PlayerCombo pong2 = new PlayerCombo(listener);
    		SpeedCombo pong3 = new SpeedCombo(listener);
    		JFrame frame = new JFrame();
    		BackGround component = new BackGround( );
    		frame.getContentPane( ).add(component);
    		JPanel controlPanel = new JPanel();
    		controlPanel.setLayout(new GridLayout(1,2));
    		controlPanel.add(pong2.getfacenameCombo1());
    		controlPanel.add(pong3.getfacenameCombo2());
    		frame.add(controlPanel, BorderLayout.SOUTH);
    		frame.setSize(850,590);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ComboListener pong4 = new ComboListener();
    		int player = pong4.getPlayer();
    		int speed = pong4.getSpeed();
    		while (speed!=5 && player!=2)
    		{
    			player = pong4.getPlayer();
    			speed = pong4.getSpeed();
    			System.out.println(speed);
    			System.out.println(player);
    		}
    	}
    }
    the background:

    XML Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    
    
    public class BackGround extends JComponent
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public BackGround () throws IOException
    	{
          	String inputFileName = "welcomescreen.gif";
          	backgroundImage = ImageIO.read(new File(inputFileName));
    	}
    	 public void paintComponent(Graphics g) 
    	{
    		 super.paintComponents(g);
    
    		 g.drawImage(backgroundImage, 0, 0, null);
    	}
    	private Image backgroundImage;
    }
    the speed combo box:

    XML Code:
    import java.awt.event.ActionListener;
    
    import javax.swing.JComboBox;
    
    public class SpeedCombo 
    {
    	public SpeedCombo (ActionListener listener)
    	{
    		facenameCombo2 = new JComboBox();
    		facenameCombo2.addItem("1 speed");
    		facenameCombo2.addItem("3 speed");
    		facenameCombo2.addItem("5 speed");
    		facenameCombo2.addItem("bullet speed");
    		facenameCombo2.setEditable(false);
    		facenameCombo2.addActionListener(listener);
    	}
    	public JComboBox getfacenameCombo2()
    	{
    		return facenameCombo2;
    	}
    	private JComboBox facenameCombo2;
    }
    the player combo box:

    XML Code:
    import java.awt.event.ActionListener;
    
    import javax.swing.JComboBox;
    
    public class PlayerCombo 
    {
    	public PlayerCombo(ActionListener listener)
    	{
    		facenameCombo1 = new JComboBox();
    		facenameCombo1.addItem("1 Player");
    		facenameCombo1.addItem("2 Player");
    		facenameCombo1.setEditable(false);
    		facenameCombo1.addActionListener(listener);
    	}
    	public JComboBox getfacenameCombo1()
    	{
    		return facenameCombo1;
    	}
    	private JComboBox facenameCombo1;
    }
    finally the action listener (in this case its the ComboListener):

    XML Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;
    
    public class ComboListener implements ActionListener
    {
    	public void actionPerformed(ActionEvent evt) 
    	{
    	    JComboBox cb = (JComboBox) evt.getSource();
    	    Object obj = cb.getSelectedItem();
    		updatePlayer((String) obj);
    		updateSpeed((String) obj);
    	}
    	public void updateSpeed(String Speed)
    	{
    		if (Speed.equals("1 speed"))
    			speed = 5;
    		else if (Speed.equals("3 speed"))
    			speed = 10;
    		else if (Speed.equals("5 speed"))
    			speed = 15;
    		else
    			speed = 20;
    	}
    	public int getSpeed()
    	{
    		return speed;
    	}
    	public void updatePlayer(String Speed)
    	{
    		if (Speed.equals("1 Player"))
    			player = 2;
    		else
    			player = 2;
    	}
    	public int getPlayer()
    	{
    		return player;
    	}
    	private int player;
    	private int speed;
    }
    I was getting null pointer exception before, but i was able to get past that so it displays everything. Still, it wont change the variable for speed and int in the JFrame class (ponginterfaceviewer). Some tips would be nice or somewhere on the web that i can read would be really helpful thanks (by the way, i put a print statement in to check the variable, but i want the button to go there in the end).

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

    Default

    You have a bit of code to go through, and I can't state that I've gone through it all, and also I'm at work and without a useable Java compiler, but let me see if I can tease anything out for you.

    In your PongInterfaceViewer
    • First off, I like how you are trying to separate your view and your control.
    • You're getting your player and your speed from pong4 at program creation and by polling, but not in an event-driven way, though this can work, except,...
    • You've got a while (true) game loop ( in your main method at while (speed !=5 && player != 2)) which usually doesn't play nice with Swing's EDT. Better to use a Swing Timer for a game loop, however,...
    • I'm not even sure why you're polling the comboboxes as you do and would probably use a different approach entirely. Wouldn't you only display the comboboxes and get user input prior to each new game? If so, then there's no need to poll them and you certainly wouldn't want to extract the speed and player from them on program creation as you do or even giving them a listener. Rather you might consider not adding listeners to the combo boxes at all but displaying them as you're doing or in a dialog window, and then give the gui a "Start Game" button and an ActionListener for the button, and only get the selected information from the combo boxes when the player presses this button. Then get after you've gotten this information get rid of the this introductory portion of your GUI and start your game proper.
    • This class should not extend JFrame.


    Much luck!
    Last edited by Fubarable; 04-27-2011 at 12:27 AM.

  3. #3
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    wow thanks for the speedy response and you shone a light i hadn't even thought of, thank you. Your right ill try what you said and as far as extending the class goes, I took an example from our classes text books and tried to morph it around my pong program. The end result gave me this and ill post back when i try it out.

  4. #4
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    well i know the actionlistener is running, because i put in a run statement at the end of the listener to print the variables and its printing, but now it wont change the variables to what i want them for each. I'm going to post my current listener.

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JComboBox;
    
    public class ComboListener implements ActionListener,Runnable
    {
    	public void actionPerformed(ActionEvent evt) 
    	{
    		PlayerCombo pong2 = new PlayerCombo();
    		SpeedCombo pong3 = new SpeedCombo();
    		JComboBox player = pong2.getfacenameCombo1();
    		JComboBox speed = pong3.getfacenameCombo2();
    		String speed1 = (String) speed.getSelectedItem();
    		String player1 = (String) player.getSelectedItem();
    		updateSpeed(speed1);
    		updatePlayer(player1);
    		run();
    	}
    	public void updateSpeed(String Speed)
    	{
    		if (Speed.equals("1 speed"))
    			speed = 5;
    		else if (Speed.equals("3 speed"))
    			speed = 10;
    		else if (Speed.equals("5 speed"))
    			speed = 15;
    		else
    			speed = 20;
    	}
    	public int getSpeed()
    	{
    		return speed;
    	}
    	public void updatePlayer(String Speed)
    	{
    		if (Speed.equals("1 Player"))
    			player = 2;
    		else
    			player = 2;
    	}
    	public int getPlayer()
    	{
    		return player;
    	}
    	private int player;
    	private int speed;
    	public void run() 
    	{
    		System.out.println(getSpeed());
    		System.out.println(getPlayer());
    	}
    }
    Last edited by dbomb; 04-27-2011 at 01:44 AM.

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

    Default

    Quote Originally Posted by dbomb View Post
    well i know the actionlistener is running, because i put in a run statement at the end of the listener to print the variables and its printing, but now it wont change the variables to what i want them for each. I'm going to post my current listener.
    Maybe I didn't stress highly enough, but my most important point in my post above was point 4, that your design is off, that you shouldn't even be adding ActionListeners to your combo boxes, but that instead you should simply extract the data from the combo boxes when the user presses a button indicating that he's done setting them.

  6. #6
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    do you mean something like this?

    Get selected Item from JComboBox : JComboBox**Swing**Java Tutorial

    I know it uses a JList instead of a JComboBox, but similar idea right?

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

    Default

    I think I would create a class that held both JComboBoxes and had two public methods, getSpeed() and getPlayer() that returned the selected item from the speed and player combo boxes respectively. I wouldn't have the loop or polling as you do. I'd possibly display this class in a JOptionPane or other modal JDialog and when the dialog was complete, extract the player count and speed via the two public methods.

  8. #8
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    Again, i copied this model from our java book, but i tried skewing the design when i really had no idea what i was doing. Now, i feel like im getting close. Thanks for working through this with me. Plus, my last resort is just using JOptionPane.showInputDialog("enter player here");. Which I might have to move on soon, but this sounds pretty close to being ironed out, ill post back soon when i remodel my program.

  9. #9
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    So, I fiddled around with the combo box thing and came to the conclusion that it is ten times harder than I wanted this to be. My program came to this (right now it just echo prints the variables, but it will pass them on to my actual Pong class).

    the interface (does not extend JFrame anymore):

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class PongInterfaceViewer 
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public static void main(String[]args) throws IOException
    	{
    		ComboListener pong3 = new ComboListener();
    		JButton play = new JButton("Play");
    		play.addActionListener(pong3);
    		JFrame frame = new JFrame();
    		BackGround component = new BackGround( );
    		frame.getContentPane( ).add(component);
    		JPanel controlPanel = new JPanel();
    		controlPanel.setLayout(new GridLayout(1,1));
    		controlPanel.add(play);
    		frame.add(controlPanel, BorderLayout.SOUTH);
    		frame.setSize(850,590);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    }
    the background (which didnt change):

    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    
    
    public class BackGround extends JComponent
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public BackGround () throws IOException
    	{
          	String inputFileName = "welcomescreen.gif";
          	backgroundImage = ImageIO.read(new File(inputFileName));
    	}
    	 public void paintComponent(Graphics g) 
    	{
    		 super.paintComponents(g);
    
    		 g.drawImage(backgroundImage, 0, 0, null);
    	}
    	private Image backgroundImage;
    }
    finally the dreaded listener class (which is still labeled ComboListener, even though I dont use combo boxes):

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JOptionPane;
    
    public class ComboListener implements ActionListener,Runnable
    {
    	public void actionPerformed(ActionEvent evt) 
    	{
    		run();
    	}
    	public void run() 
    	{
    		int p = 1;
    		int s = 1;
    		System.out.println("the number of players is restricted to: 1-2");
    		System.out.println("the ball speed is restricted to: 1-20");
    		int player1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter the number of players: "));
    		while (p == 1)
    			if (player1 >= 1 && player1 <=2)
    			{
    				player = 2;
    				p = 2;
    			}
    			else
    				player1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a number between 1 and 2: "));
    		int speed1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter the ball speed: "));
    		while (s == 1)
    			if (speed1 >= 1 && speed1 <= 20)
    			{
    				speed = speed1;
    				s = 2;
    			}
    			else 
    				speed1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a number between 1 and 20: "));
    		
    		System.out.println("the number of players is: " + player);
    		System.out.println("the ball speed is: " + speed);
    	}
    	private int player;
    	private int speed;
    }

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

    Default

    You can still use JComboBoxes and use a JOptionPane to simply get user information. For instance you could create a class that holds two JComboBoxes along with two getter methods to extract the selected items from the combo boxes:

    Java Code:
    import javax.swing.Box;
    import javax.swing.JComboBox;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    class ComboPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public static final String[] DAYS = { 
            "Sunday", "Monday", "Tuesday", "Wednesday", 
            "Thursday", "Friday", "Saturday" };
        public static final String[] NUMBERS = { "One", "Two", "Three", "Four" };
    
        private JComboBox dayCombo = new JComboBox(DAYS);
        private JComboBox numberCombo = new JComboBox(NUMBERS);
    
        public ComboPanel() {
            add(new JLabel("Day:"));
            add(dayCombo);
            add(Box.createHorizontalStrut(15));
            add(new JLabel("Number:"));
            add(numberCombo);
        }
    
        // getter method for dayCombo
        public String getDay() {
            return dayCombo.getSelectedItem().toString();
        }
    
        // getter method for numberCombo
        public String getNumber() {
            return numberCombo.getSelectedItem().toString();
        }
    }

    Then you could display the JPanel above in a JOptionPane and call the getter methods after the option pane is through:

    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    
    public class TestComboPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private JTextField dayField = new JTextField(12);
        private JTextField numberField = new JTextField(12);
        private ComboPanel comboPanel = new ComboPanel();
    
        public TestComboPanel() {
            dayField.setFocusable(false);
            numberField.setFocusable(false);
    
            JButton showCombosBtn = new JButton("Show Combos");
            showCombosBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
    
                    // create a JOptionPane and add the ComboPanel JPanel into it.
                    int result = JOptionPane.showConfirmDialog(TestComboPanel.this,
                            comboPanel, "Choices", JOptionPane.OK_CANCEL_OPTION, 
                            JOptionPane.PLAIN_MESSAGE);
                    if (result == JOptionPane.OK_OPTION) {
    
                        // then extract the selected items via the getter methods
                        dayField.setText(comboPanel.getDay());
                        numberField.setText(comboPanel.getNumber());
                    }
                }
            });
    
            add(showCombosBtn);
            add(dayField);
            add(numberField);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createGui();
                }
            });
        }
    
        private static void createGui() {
            JFrame frame = new JFrame("My App");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new TestComboPanel());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }

  11. #11
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    Ok, I see what you were trying to tell me before and thank you for helping along with this process. I have one final question though, How can I run my actual game after the user interface is done? In the run class you posted it only called on the interface to compile all of these components together. Should I put a run statement at the end of the GUI method or should I create a second actionListener to track a play button instead of the "show combo" button?

  12. #12
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    So, I wanted to keep the relatively same design in my project, because i wanted the background image. So, this is my final code, unless you have any suggestions.

    my viewer class:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class PongInterfaceViewer 
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public static void main(String[]args) throws IOException
    	{
    		JFrame frame = new JFrame();
    		BackGround component = new BackGround( );
    		frame.getContentPane( ).add(component);
    		
    		PongComboBoxes PongComboBoxes = new PongComboBoxes();
    		
    		ComboListener pong3 = new ComboListener();
    		JButton play = new JButton("Play");
    		play.addActionListener(pong3);
    		
    		JPanel ControlPanel = new JPanel();
    		ControlPanel.setLayout(new GridLayout(1,3));
    		ControlPanel.add(PongComboBoxes.addPlayer());
    		ControlPanel.add(play);
    		ControlPanel.add(PongComboBoxes.addSpeed());
    		
    		frame.add(ControlPanel, BorderLayout.SOUTH);
    		frame.setSize(850,590);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    }
    the background catching class:

    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    
    public class BackGround extends JComponent
    {
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	
    	public BackGround () throws IOException
    	{
          	String inputFileName = "welcomescreen.gif";
          	backgroundImage = ImageIO.read(new File(inputFileName));
    	}
    	 public void paintComponent(Graphics g) 
    	{
    		 super.paintComponents(g);
    		 g.drawImage(backgroundImage, 0, 0, null);
    	}
    	private Image backgroundImage;
    }
    my combo listener class (which i should probably rename as button listener, because its a pretty confusing name):

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class ComboListener implements ActionListener,Runnable
    {
    	public void actionPerformed(ActionEvent evt) 
    	{
    		run();
    	}
    	public void run() 
    	{
    		player = PongComboBoxes.getPlayer();
    		speed = PongComboBoxes.getSpeed();
    		
    		System.out.println("the number of players is: " + player);
    		System.out.println("the ball speed is: " + speed);
    	}
    	private String player;
    	private String speed;
    }
    the combo boxes:

    Java Code:
    import java.awt.Component;
    
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    
    class PongComboBoxes extends JPanel
    {
        public Component addPlayer() 
        {
            return PlayerCombo;
        }
        public Component addSpeed()
        {
        	return SpeedCombo;
        }
        public static String getPlayer() 
        {
            return (String) PlayerCombo.getSelectedItem();
        }
        public static String getSpeed() 
        {
            return (String) SpeedCombo.getSelectedItem();
        }
        public static final String[] PLAYER = {"1 Player", "2 Players"};
        public static final String[] SPEED = {"slow", "medium", "fast", "bullet speed"};
        
        private static JComboBox PlayerCombo = new JComboBox(PLAYER);
        private static JComboBox SpeedCombo = new JComboBox(SPEED);
        
        private static final long serialVersionUID = 1L;
    }

  13. #13
    dbomb is offline Member
    Join Date
    Apr 2011
    Posts
    13
    Rep Power
    0

    Default

    so much code for something the user will probably only spend a few seconds at, but it looks nice as it is.

Similar Threads

  1. Replies: 2
    Last Post: 04-20-2011, 11:42 PM
  2. Comparing two combo boxes
    By Wednesday Bass in forum AWT / Swing
    Replies: 2
    Last Post: 03-27-2011, 12:28 PM
  3. Replies: 4
    Last Post: 08-11-2010, 12:47 PM
  4. multiple combo boxes
    By simo_mon in forum AWT / Swing
    Replies: 1
    Last Post: 07-22-2010, 11:57 AM
  5. [SOLVED] Combo Boxes Automation
    By dbashby in forum New To Java
    Replies: 3
    Last Post: 03-27-2009, 12:39 AM

Posting Permissions

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