Reputation: 27
I am implementing a program for a Component Design course and am currently struggling with what should be simple use of a Jlist. The program draws shapes and should display them in a JList in a ScrollPane in the BorderLayout.West of the frame.
The current program shows the ScrollPane but will not display objects I add to the shapeListModel like it should. I am wondering it I am missing something or if something is flat out wrong with my code. Currently this is all the code that partains to the JList creation, assigning, and updating.
//Class Variable Declaration
protected ArrayList<Shape> shapes = new ArrayList<Shape>();
private JScrollPane shapeScrollPane = new JScrollPane();
private JList<String> shapeList;
protected DefaultListModel<String> shapeListModel;
//Creation of JList objects and what not
shapeListModel = new DefaultListModel<String>();
//This element is added aimply to try and get one to show up on my JList,
shapeListModel.addElement("SERIOUSLY FRUSTRATED");
//It does not just so you know
shapeList = new JList<String>(shapeListModel);
shapeList.setModel(shapeListModel);
//Adding JList to ScrollPane and setting size
shapeScrollPane.add(shapeList);
shapeScrollPane.setPreferredSize(new Dimension(250,600));
//Clarifying JList actions
shapeList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
shapeList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
shapeList.setVisibleRowCount(-1);
shapeList.addListSelectionListener(this);**
//This is called everytime a new shape is created and adds it to the Arraylist
//shapes and the DefaultListModel shapeListModel
shapes.add(newShape);
shapeListModel.addElement(newShape.toString());
I apologize for my poorly formatted question a few moments ago. I have been stuck on this for approximately 4 hours, the last two hours spent searching for answers online. I am now resulting to asking anyone if they see an issue within the code I have.
Upvotes: 0
Views: 3302
Reputation: 347214
You don't "add" components a scroll pane. You need to set it's view ports view instead.
Don't do this...
shapeScrollPane.add(shapeList);
Do this...
shapeScrollPane.setViewportView(shapeList);
Check out
Also, this shapeList.setVisibleRowCount(-1)
scares me to no end.
Updated
You also don't need to this...
shapeList = new JList<String>(shapeListModel);
shapeList.setModel(shapeListModel);
This is more then sufficient...
shapeList = new JList<String>(shapeListModel);
Updated
Also, if this is the same code that was used in a previously closed question...
This canvas.getGraphics()
terrifies me!! If your instructor gave you this code, then they shouldn't be teaching you!
Upvotes: 3