Change current card in card layout with slide effect in swing

后端 未结 3 1511
梦如初夏
梦如初夏 2021-01-25 05:24

I\'m trying to change current visible in card layout with slide effect. But I see a flick at the start of slide which I\'m not able to debug/solve. How can I avoid that flick?

3条回答
  •  萌比男神i
    2021-01-25 05:42

    The main problem is that you are stepping on CardLayout's toes. CardLayout both manages bounds (location and size) and visibility of your components, so your loop here:

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            label2.setLocation(label1.getX() + 10 - label1.getWidth(), label1.getY());
            label1.setLocation(label1.getX() + 10, label1.getY());
            label2.setVisible(true);
        }
    

    is conflicting with what CardLayout does. By default, CardLayout will automatically show the first component you added and hide all the others. It also sets up the bounds of all components to the same bounds.

    At the end of the first iteration, the visibility of label2 changes (from false to true) which eventually triggers your CardLayout to reperform the layout of your components which sets the bounds of all the components to the same bounds which is why you are seeing the overlapping. CardLayout is not meant to have multiple components visible simultaneously.

    Note that you are running all this off the EDT (Event Dispatching Thread) which is really a bad idea. It can cause deadlocks and unpredictable behaviour (such as the one you are seeing here).

提交回复
热议问题