Question

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();
}
Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top