views:

1603

answers:

3

I need to display different drawings on a JPanel. I have put the drawing files into an array, but when I changed it using a button, the JPanel only displays first drawing and doesn't change to the next drawing...

I have called panel.revalidate(), but it doesnt work.

This is the segment of the code that I used but not working. The JPanel display was static.

    String[] a = {"image1.txt","image2.txt","image3.txt"};
    List<String> files = Arrays.asList(a);


    public void actionPerformed(ActionEvent e) {
 if (e.getSource() == answer1){
  fileNumber++;
  //call other class for painting (files=array files, fileNumber=index of the array) 
  draw = new drawingPanel(files,fileNumber);
  panel.add(draw);
 }
 panel.revalidate();
 panel.repaint();
}
+1  A: 

Are you only displaying one drawing at a time? If so, you may want to try using a CardLayout, so you can switch between drawings easily. See http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html for an example.

I had a similar issue the other day attempting to dynamically display different buttons on my UI depending which tab of a JTabbedPane the user picked. CardLayout was just the thing to make things easy.

ssakl
yes, one drawing at a time.My program quite similar with the example that u suggest to have a look. How ever I still cant change the drawing...this is so confusing me. Let me show the segement of the code in Answer.
Jessy
ssakl
SO limits comments to 300 characters, so I'll continue here. Search the linked code for "cardPanel" to see what I'm doing there. Hopefully you'll be able to adapt it for your (slightly more complex) needs.
ssakl
Hi ssakl...thanks for the example. I now can display the drawing after add the code removeAll() before draw.
Jessy
A: 

This is the segment of the code that I used but not working. The JPanel display was static.

    String[] a = {"image1.txt","image2.txt","image3.txt"};
List<String> files = Arrays.asList(a);


    public void actionPerformed(ActionEvent e) {
 if (e.getSource() == answer1){
  fileNumber++;
  draw = new drawingPanel(files,fileNumber); //call other class for painting (files=array files, fileNumber=index of the array) 
  panel.add(draw);
  }
 panel.revalidate();
 panel.repaint();
 }
Jessy
A: 

You might try keeping a reference to your drawingPanel and calling remove() on the existing drawingPanel before re-adding it. According to the JPanel JavaDoc, the layout is FlowLayout by default - which will not replace the image like you are intending, but will instead place the next drawingPanel to the right of the previous one. (what happens when you resize the window?)

By the way, how do you handle the case where you get past the last image in the array?

Mike
Jessy
Oh, I missed to answer you question. When I pass the last image, I add the system.exit code to close it.
Jessy