Page 1 of 2 12 LastLast
Results 1 to 20 of 21
  1. #1
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default A few problems with a Swing GUI

    I have a JPanel called TroopPanel, that offers the user the choice of three tribes as radio buttons, then offers him a combo box with 10 units to choose from, in respect to which tribe was chosen. When he chooses a unit, its information is displayed below.
    Each of these three elements (the radio button group, the combo box, and the unit information) is on its own JPanel. These three JPanels are then added to TroopPanel with a GridBagLayout.

    TroopPanel (the main panel):
    Java Code:
    import java.awt.*;import javax.swing.*;
    
    
    public class TroopPanel extends JPanel {
    	public TroopPanel() {
    		super (new GridBagLayout());
    		
    		GridBagConstraints c = new GridBagConstraints();
    		
    		c.weightx = 0.5;
    		c.weighty = 0.0;
    		c.gridx = 0;
    		c.gridy = 0;
    		add (TribeSelection.getInstance(), c);
    		
    		c.weightx = 0.5;
    		c.weighty = 0.0;
    		c.gridx = 1;
    		c.gridy = 0;
    		add (UnitSelection.getInstance(), c);
    		
    		c.weightx = 1.0;
    		c.weighty = 1.0;
    		c.gridx = 0;
    		c.gridy = 1;
    		c.gridwidth = 2;
    		add (TroopInfo.getInstance(), c);
    	}
    }
    TribeSelection (the panel with the radio buttons):
    Java Code:
    import java.awt.*;import java.awt.event.*;
    import javax.swing.*;
    
    
    public class TribeSelection extends JPanel implements ActionListener {
    	private static final TribeSelection instance = new TribeSelection();
    	
    	private TribeSelection() {
    		setLayout (new GridLayout (3,1));
    		
    		JRadioButton romanButton = new JRadioButton ("Roman");
    		JRadioButton gaulButton = new JRadioButton ("Gaul");
    		JRadioButton teutonButton = new JRadioButton ("Teuton");
    		romanButton.setSelected (true);
    		romanButton.setActionCommand (Integer.toString (UnitList.ROMAN));
    		gaulButton.setActionCommand (Integer.toString (UnitList.GAUL));
    		teutonButton.setActionCommand (Integer.toString (UnitList.TEUTON));
    		
    		ButtonGroup group = new ButtonGroup();
    		group.add (romanButton);
    		group.add (gaulButton);
    		group.add (teutonButton);
    		
    		romanButton.addActionListener (this);
    		gaulButton.addActionListener (this);
    		teutonButton.addActionListener (this);
    		
    		add (romanButton);
    		add (gaulButton);
    		add (teutonButton);
    	}
    	
    	public static TribeSelection getInstance() { return instance; }
    	
    	public void actionPerformed (ActionEvent e) {
    		UnitSelection.getInstance().setTribe (Integer.parseInt (e.getActionCommand()));
    	}
    }
    UnitSelection (the panel with the combo box):
    Java Code:
    import java.awt.event.*;import javax.swing.*;
    
    
    public class UnitSelection extends JPanel implements ActionListener {
    	private static final UnitSelection instance = new UnitSelection();
    	
    	private int tribe = UnitList.ROMAN;
    	private String[] choices = new String[10];
    	private JComboBox units;
    	
    	private UnitSelection() {
    		refreshChoices();
    	}
    	
    	public static UnitSelection getInstance() { return instance; }
    	
    	public void refreshChoices() {
    		for (int i = 0; i < choices.length; i++) choices[i] = UnitList.getInstance().units[tribe][i].toString();
    		if (units != null) remove (units);
    		units = new JComboBox (choices);
    		add (units);
    		TroopInfo.getInstance().setUnit (UnitList.getInstance().units[tribe][0]);
    	}
    	
    	public void setTribe (int tribeIndex) {
    		tribe = tribeIndex;
    		refreshChoices();
    	}
    	
    	public void actionPerformed (ActionEvent e) {
    		JComboBox cb = (JComboBox)e.getSource();
    		TroopInfo.getInstance().setUnit (UnitList.getInstance().units[tribe][cb.getSelectedIndex()]);
    	}
    }
    TroopInfo (the panel with the unit's information - not completely finished yet, but you get the idea):
    Java Code:
    import javax.swing.*;
    
    public class TroopInfo extends JPanel {
    	private static final TroopInfo instance = new TroopInfo();
    	
    	private Unit unit = new Legionnaire();
    	private String unitName = unit.toString();
    	
    	private TroopInfo() {
    		JLabel label = new JLabel (unitName);
    		add (label);
    	}
    	
    	public static TroopInfo getInstance() { return instance; }
    	
    	public void setUnit (Unit unit) {
    		this.unit = unit;
    		refreshTroopInfo();
    	}
    	
    	public void refreshTroopInfo() {
    		
    	}
    }

    I'll make an SSCCE if necessary, but it will actually be way longer, since I'll need to include the Unit and Tribe classes, along with a few of their subclasses, etc, and I think this is enough to give you the idea of what I'm doing.

    Anyway, to the actual questions:
    1) Is there a better way to refresh the elements than the method I used (remove&add the element)?
    2) My radio buttons only trigger the refreshChoices once I click one of them and then click somewhere else in the frame. I'd like it to trigger as soon as a button is selected. I'm guessing that means I have to use a different listener instead of ActionListener, but which one?
    3) There's a problem with positioning. I want TribeSelection and UnitSelection each to get exactly half of the width of the frame, and I want the radio buttons and the combo box to be in the center of their respective panels. However when I change the tribe (and thereby resize the combo box, since the lengths of the longest unit names differ from tribe to tribe), the radio button group moves a bit to the left (if the combo box's width increases) or to the right (if the combo box's width decreases) for some reason. Why aren't the panels each getting exactly half of the frame width?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    There's almost certainly little need to make these things Singletons.
    In fact, it just looks wrong.
    You may, at some point, want to be able to show multiple Unit panels, for example.

    Anyway, no need to initialise your Unit or tribe either.
    Just handle a non-existent one (eg show a blank panel or something).

    As to your actual questions.
    1. I would ensure the combo box exists, with an empty list or default value or something. Then simply removeAllItems when you need to clear it and add the new list in (I don't think there's a general addAll() method, though). That way you're using the same combo each time.
    2. The above might cure that, as I suspect it's because there's no redraw() happening in the current situation. The above should cover that inside the JComboBox methods.
    3. Not sure about this one as I don't think I've ever used GridBag.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    OK, this is what I have now:

    Java Code:
    public class TroopPanel extends JPanel {	static TribeSelection tribeSelection = new TribeSelection();
    	static UnitSelection unitSelection = new UnitSelection();
    	static TroopInfo troopInfo = new TroopInfo();
    	
    	public TroopPanel() {
    		super (new GridBagLayout());
    		
    		GridBagConstraints c = new GridBagConstraints();
    		
    		c.weightx = 0.5;
    		c.weighty = 0.0;
    		c.gridx = 0;
    		c.gridy = 0;
    		add (tribeSelection, c);
    		
    		c.weightx = 0.5;
    		c.weighty = 0.0;
    		c.gridx = 1;
    		c.gridy = 0;
    		add (unitSelection, c);
    		
    		c.weightx = 1.0;
    		c.weighty = 1.0;
    		c.gridx = 0;
    		c.gridy = 1;
    		c.gridwidth = 2;
    		add (troopInfo, c);
    	}
    }
    Java Code:
    public class TribeSelection extends JPanel implements ActionListener {	public TribeSelection() {
    		setLayout (new GridLayout (3,1));
    		
    		JRadioButton romanButton = new JRadioButton ("Roman");
    		JRadioButton gaulButton = new JRadioButton ("Gaul");
    		JRadioButton teutonButton = new JRadioButton ("Teuton");
    		romanButton.setSelected (true);
    		romanButton.setActionCommand (Integer.toString (UnitList.ROMAN));
    		gaulButton.setActionCommand (Integer.toString (UnitList.GAUL));
    		teutonButton.setActionCommand (Integer.toString (UnitList.TEUTON));
    		
    		ButtonGroup group = new ButtonGroup();
    		group.add (romanButton);
    		group.add (gaulButton);
    		group.add (teutonButton);
    		
    		romanButton.addActionListener (this);
    		gaulButton.addActionListener (this);
    		teutonButton.addActionListener (this);
    		
    		add (romanButton);
    		add (gaulButton);
    		add (teutonButton);
    	}
    	
    	public void actionPerformed (ActionEvent e) {
    		TroopPanel.unitSelection.setTribe (Integer.parseInt (e.getActionCommand()));
    	}
    }
    Java Code:
    public class UnitSelection extends JPanel implements ActionListener {	private int tribe = UnitList.ROMAN;
    	private JComboBox units = new JComboBox();
    	
    	public UnitSelection() {
    		units.addActionListener (this);
    		add (units);
    		refreshChoices();
    	}
    	
    	public void refreshChoices() {
    		units.removeAllItems();
    		for (int i = 0; i < UnitList.getInstance().units[tribe].length; i++) units.addItem (UnitList.getInstance().units[tribe][i].toString());
    	}
    	
    	public void setTribe (int tribeIndex) {
    		tribe = tribeIndex;
    		refreshChoices();
    	}
    	
    	public void actionPerformed (ActionEvent e) {
    		JComboBox cb = (JComboBox)e.getSource();
    		if (TroopPanel.troopInfo != null) TroopPanel.troopInfo.setUnit (UnitList.getInstance().units[tribe][cb.getSelectedIndex()]);
    	}
    }
    Java Code:
    public class TroopInfo extends JPanel {
    	private Unit unit;
    	private JLabel name;
    	
    	public TroopInfo() {
    		setLayout (new GridLayout());
    	}
    	
    	public void setUnit (Unit unit) {
    		this.unit = unit;
    		refreshTroopInfo();
    	}
    	
    	public void refreshTroopInfo() {			
    		if (name == null) {
    			name = new JLabel (unit.toString());
    			add (name);
    		}
    		else name = new JLabel (unit.toString());
    	}
    }
    As you can see I now turned the panels into static objects in the TroopPanel class. That gave me a few more NPEs, but I managed to fix them, except for this one which is fixed temporarily, until I get back to it to find a better solution:
    Java Code:
    if (TroopPanel.troopInfo != null) TroopPanel.troopInfo.setUnit (UnitList.getInstance().units[tribe][cb.getSelectedIndex()]);
    Anyway, the second thing did indeed get fixed by using removeAllItems() and addItem() to refresh the combo box.
    However I am now getting an array index out of bounds exception the first time I click on one of the radio buttons to select a tribe, and the combo box becomes empty. After the first time it works normally. Why does this happen? Does removing all items trigger the ActionListener? Because I don't see why the actionPerformed method would get called before the combo box was filled with items otherwise...
    Code:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    	at troopInfo.UnitSelection.actionPerformed(UnitSelection.java:28)
    	at javax.swing.JComboBox.fireActionEvent(Unknown Source)
    	at javax.swing.JComboBox.contentsChanged(Unknown Source)
    	at javax.swing.JComboBox.intervalRemoved(Unknown Source)
    	at javax.swing.AbstractListModel.fireIntervalRemoved(Unknown Source)
    	at javax.swing.DefaultComboBoxModel.removeAllElements(Unknown Source)
    	at javax.swing.JComboBox.removeAllItems(Unknown Source)
    	at troopInfo.UnitSelection.refreshChoices(UnitSelection.java:17)
    	at troopInfo.UnitSelection.setTribe(UnitSelection.java:23)
    	at troopInfo.TribeSelection.actionPerformed(TribeSelection.java:34)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.JToggleButton$ToggleButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.awt.EventQueue$2.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)

  4. #4
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    Babump

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

  6. #6
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    Real..

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class MainWindow extends JFrame {
        public MainWindow() {
            super ("Blah");
            
            double width, height;
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            width = d.getWidth();
            height = d.getHeight();
            
            setBounds ((int)(width/4), (int)(height/6), (int)(width/2), (int)(2*height/3));
            
            add (new MyTabbedPane());
            
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setVisible (true);
        }
        
        public static void main (String[] args) {
            DataLoader.loadData();
            new MainWindow();
        }
    }
    Java Code:
    import javax.swing.*;
    
    public class MyTabbedPane extends JTabbedPane {
        public MyTabbedPane() {
            super (JTabbedPane.BOTTOM);
            addTab ("Troop Info", new TroopPanel(), "Displays information about units");
        }
    }
    Java Code:
    public class DataLoader {
        public static void loadData() {
            TribeList.getInstance();
            UnitList.getInstance();
            TribeList.getInstance().loadData();
            UnitList.getInstance().loadData();
        }
    }
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class TroopPanel extends JPanel {
        static TribeSelection tribeSelection = new TribeSelection();
        static TroopInfo troopInfo = new TroopInfo();
        static UnitSelection unitSelection = new UnitSelection();
        
        public TroopPanel() {
            super (new GridBagLayout());
            
            GridBagConstraints c = new GridBagConstraints();
            
            c.weightx = 0.5;
            c.weighty = 0.0;
            c.gridx = 0;
            c.gridy = 0;
            add (tribeSelection, c);
            
            c.weightx = 0.5;
            c.weighty = 0.0;
            c.gridx = 1;
            c.gridy = 0;
            add (unitSelection, c);
            
            c.weightx = 1.0;
            c.weighty = 1.0;
            c.gridx = 0;
            c.gridy = 1;
            c.gridwidth = 2;
            add (troopInfo, c);
        }
    }
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    
    public class TribeSelection extends JPanel implements ActionListener {
        public TribeSelection() {
            setLayout (new GridLayout (3,1));
            
            JRadioButton romanButton = new JRadioButton ("Roman");
            JRadioButton gaulButton = new JRadioButton ("Gaul");
            JRadioButton teutonButton = new JRadioButton ("Teuton");
            romanButton.setSelected (true);
            romanButton.setActionCommand (Integer.toString (UnitList.ROMAN));
            gaulButton.setActionCommand (Integer.toString (UnitList.GAUL));
            teutonButton.setActionCommand (Integer.toString (UnitList.TEUTON));
            
            ButtonGroup group = new ButtonGroup();
            group.add (romanButton);
            group.add (gaulButton);
            group.add (teutonButton);
            
            romanButton.addActionListener (this);
            gaulButton.addActionListener (this);
            teutonButton.addActionListener (this);
            
            add (romanButton);
            add (gaulButton);
            add (teutonButton);
        }
        
        public void actionPerformed (ActionEvent e) {
            TroopPanel.unitSelection.setTribe (Integer.parseInt (e.getActionCommand()));
        }
    }
    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    
    
    public class UnitSelection extends JPanel implements ActionListener {
        private int tribe = UnitList.ROMAN;
        private JComboBox units = new JComboBox();
        
        public UnitSelection() {
            units.addActionListener (this);
            add (units);
            refreshChoices();
        }
        
        public void refreshChoices() {
            units.removeAllItems();
            for (int i = 0; i < UnitList.getInstance().units[tribe].length; i++) units.addItem (UnitList.getInstance().units[tribe][i].toString());
        }
        
        public void setTribe (int tribeIndex) {
            tribe = tribeIndex;
            refreshChoices();
        }
        
        public void actionPerformed (ActionEvent e) {
            JComboBox cb = (JComboBox)e.getSource();
            TroopPanel.troopInfo.setUnit (UnitList.getInstance().units[tribe][cb.getSelectedIndex()]);
        }
    }
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    
    public class TroopInfo extends JPanel {
        private Unit unit;
        private JLabel name = new JLabel();
        
        public TroopInfo() {
            setLayout (new GridLayout());
            add (name);
        }
        
        public void setUnit (Unit unit) {
            this.unit = unit;
            refreshTroopInfo();
        }
        
        public void refreshTroopInfo() {            
            name.setText (unit.toString());
        }
    }
    Java Code:
    public abstract class Entity {
        protected String title;
        
        public String toString() {
            return (title);
        }
        
        public abstract void loadData();
    }
    Java Code:
    public class TribeList {
        private static final TribeList instance = new TribeList();
        
        public final Tribe roman, gaul;
        
        private TribeList() {
            roman = new Roman();
            gaul = new Gaul();
        }
        
        public void loadData() {
            roman.loadData();
            gaul.loadData();
        }
        
        public static TribeList getInstance() { return instance; }
    }
    Java Code:
    public abstract class Tribe extends Entity {
        protected Unit[] tribeUnits = new Unit[1];
    }
    Java Code:
    public class Roman extends Tribe {
        public Roman() {
            title = "Roman";
        }
        
        public void loadData() {
            for (int i = 0; i < tribeUnits.length; i++) tribeUnits[i] = UnitList.getInstance().units[UnitList.ROMAN][i];
        }
    }
    Java Code:
    public class Gaul extends Tribe {
        public Gaul() {
            title = "Gaul";
        }
        
        public void loadData() {
            for (int i = 0; i < tribeUnits.length; i++) tribeUnits[i] = UnitList.getInstance().units[UnitList.GAUL][i];
        }
    }
    Java Code:
    public class UnitList {
        private static final UnitList instance = new UnitList();
     
        public final Unit legionnaire;
        public final Unit phalanx;
    
    
        public final Unit[][] units;
        public final static int ROMAN = 0, GAUL = 1;
        
        private UnitList() {
            legionnaire = new Legionnaire();
            phalanx = new Phalanx();
    
    
            units = new Unit[2][1];
            units[ROMAN][0] = legionnaire;        
            units[GAUL][0] = phalanx;
        }
        
        public void loadData() {
            for (int i = 0; i < units.length; i++)
                for (int j = 0; j < units[i].length; j++) units[i][j].loadData();
        }
     
        public static UnitList getInstance() { return instance; }
    }
    Java Code:
    public abstract class Unit extends Entity {
        protected Tribe tribe;
    }
    Java Code:
    public final class Legionnaire extends Unit {
        public Legionnaire() {
            title = "Legionnaire";
        }
        
        public void loadData() {
            tribe = TribeList.getInstance().roman;
        }
    }
    Java Code:
    public final class Phalanx extends Unit {
        public Phalanx() {
            title = "Phalanx";
        }
        
        public void loadData() {
            tribe = TribeList.getInstance().gaul;
        }
    }
    This should be all the classes that are necessary.
    Last edited by Mate de Vita; 03-26-2012 at 03:13 PM.

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    It's as you suspect.
    The removeAll() results in an event being fired.
    Have your event handling code realise it might be being called during this removal routine.
    I'm surprised it's an ActionPerformed for a content change, but that's possibly just me.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    Is there a certain action command that removeAll passes that I can check for? Or how do I check whether it was removeAll or something else that fired the event?

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    Looks like (for the error you currently have) 'cb.getSelectedIndex()' is -1.
    That is, the event is not an event in which something was selected from the combo box.
    So:
    Java Code:
    if (cb.getSelectedIndex() > -1) {
       // Something has been selected in the combo box
    }
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    All right, everything works properly now, just need to fix that positioning problem now somehow.

  11. #11
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    OK, I'll ask about these positioning problems in the Swing forum at a later time. Right now I have another unrelated question.
    Is it possible to check if an object/class has a certain attribute?

    In my case, some of the Units have an additional attribute called secTrainBuilding (in truth it's not a String but rather a Building object, but for the purpose of this question I'll declare it as a String), such as this:

    Java Code:
    public final class Legionnaire extends Unit {
        public Legionnaire() {
            title = "Legionnaire";
        }
        
        public void loadData() {
            tribe = TribeList.getInstance().roman;
        }
    }
    Java Code:
    public final class Phalanx extends Unit {
        String secTrainBuilding;
    
        public Phalanx() {
            title = "Phalanx";
            secTrainBuilding = "Phalanx Brewery";
        }
        
        public void loadData() {
            tribe = TribeList.getInstance().gaul;
        }
    }
    This is my TroopInfo panel now:

    Java Code:
    import java.awt.*;import javax.swing.*;
    
    
    public class TroopInfo extends JPanel {
        private Unit unit;
        private JLabel name = new JLabel();
        private JLabel secTrainBuilding = new JLabel();
        
        public TroopInfo() {
            super (new GridLayout());
            add (name);
        }
        
        public void setUnit (Unit unit) {
            this.unit = unit;
            refreshTroopInfo();
        }
        
        public void refreshTroopInfo() {            
            name.setText (unit.toString());
        }
    }
    What I want to do is only show (ie. add) the label with secTrainBuilding when there is a secTrainBuilding in the unit's attributes (in this particular case, the label would be added if the chosen unit was Phalanx, and removed if the chosen unit was Legionnaire). I'd know how to do this with adding and removing if secTrainBuilding was declared in Unit and was simply null in all classes that wouldn't initialize it, but is there a way to do it when that's not the case?

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    I'd come up with a way of asking the Unit what labels apply to it.
    Then you can do what you want with the returned List (possibly a key into a Map of the actual labels?).
    That way all Units would have this method, and only the ones that actually have labels would return anything other than an empty List.

    ETA: Other than that you are down to using instanceof and casting, both of which tend to be a sign you've not got your model quite correct.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    Do you maybe know of a tutorial that would explain in detail how to use maps and lists? Because I'm stuck on the declaration of a list already... I did List attList = new ArrayList(); and I'm getting the warning message: List is a raw type. References to generic type List<E> should be parameterized
    And same for ArrayList.

    I have no idea what that means :(

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    Quote Originally Posted by Mate de Vita View Post
    ... I'm getting the warning message: List is a raw type. References to generic type List<E> should be parameterized
    And same for ArrayList.

    I have no idea what that means :(
    Lesson: Generics (The Java™ Tutorials > Learning the Java Language)

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    Thanks.

  16. #16
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    OK, new question. If I have a list with, say a capacity of 5, and I add one object to index 3, do the rest of the indexes have null elements?

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    By "list" do you mean a List (ie ArrayList, LinkedList etc)?
    If so, then add(int, <E>) won't let you add to the List beyond the next available slot, so add(3, "Some String") will throw an exception on a List that has less than 3 elements.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    I see...
    See, the problem I'm facing is that I need to know exactly which Labels are in the List that a Unit returns, because the placement of the Label on TroopInfo panel depends on what Label it is. For example the secTrainBuilding label should be right next to (or below or w/e) the trainBuilding label, while the specNotes label should be at the bottom of the panel.
    There is of course the contains(Object o) method, but that requires me being able to access and pass the exact object it's supposed to contain, and if I could do that, I wouldn't be needing the returned List in the first place.

  19. #19
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,797
    Rep Power
    19

    Default Re: A few problems with a Swing GUI

    How about a Map?
    The position (or whatever code does the positioning) would know where things should go, and could key into the Map to see if there's an entry there for that particular label.
    That way the non-GUI model doesn't need to know anything about positioning, just that it has these labels.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  20. #20
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    60
    Rep Power
    0

    Default Re: A few problems with a Swing GUI

    So let me just make sure I understand how a Map works.

    Let's say I define a method that returns a Map in each of the Units. In that Map I put a pair of ("Secondary", secTrainBuilding) for the units that have that attribute. Now when I do a get("Secondary") on the returned Map in the TroopInfo panel, it will return the secTrainBuilding, or null if there is no mapping for "Secondary".
    Correct?
    Last edited by Mate de Vita; 04-05-2012 at 07:06 PM.

Page 1 of 2 12 LastLast

Similar Threads

  1. problems with swing example program
    By mr_sandman in forum New To Java
    Replies: 4
    Last Post: 08-19-2011, 12:23 AM
  2. Swing Problems
    By niba10 in forum Advanced Java
    Replies: 5
    Last Post: 02-25-2011, 02:18 PM
  3. InputStream/Jar Problems/File IO Problems
    By rdjava in forum Advanced Java
    Replies: 31
    Last Post: 01-17-2011, 11:12 AM
  4. Replies: 13
    Last Post: 12-06-2010, 05:57 AM
  5. map javax.swing.text.Element to javax.swing.text.View
    By elizabeth in forum New To Java
    Replies: 1
    Last Post: 07-30-2007, 07:02 PM

Posting Permissions

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