首頁 > Java > java教程 > 儘管使用了 repaint(),為什麼我的擴充 JPanel 的 PaintComponent() 方法沒有被呼叫?

儘管使用了 repaint(),為什麼我的擴充 JPanel 的 PaintComponent() 方法沒有被呼叫?

DDD
發布: 2024-12-14 21:38:14
原創
976 人瀏覽過

Why Isn't My Extended JPanel's paintComponent() Method Being Called Despite Using repaint()?

程式無法存取擴充 JPanel 類別的 PaintComponent() 方法

問題

提供的程式碼具有 JFrame 及其對應的 JPanel 擴充。當重複呼叫 JPanel 的 repaint() 方法時,它無法執行 paintComponent() 方法。這導致懷疑 imageDimension 物件可能是問題的根源。

解決方案

雖然提供的上下文沒有明確引用位元組數組,但它看起來目標是創建灰度縮圖並將它們分配給組件的圖示。下面的範例程式碼提供了一種將現有範例圖示轉換為灰階並使用 setIcon() 更新元件的方法。這種方法可以應用於任何圖像。

值得注意的是,上述灰階轉換可以使用 ColorConvertOp 或透過更新元件本身而不是其圖示來實現。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

導入java.awt.*;<br>導入javax.swing.*;<p>public class IconExample {</p><pre class="brush:php;toolbar:false">public static void main(String[] args) {

    // Create a list of icons

    List<Icon> icons = new ArrayList<>();

    icons.add(new ImageIcon("image1.png"));

    icons.add(new ImageIcon("image2.png"));

 

    // Create a panel to hold the icons

    JPanel panel = new JPanel();

    panel.setLayout(new GridLayout(1, icons.size()));

 

    // Add the icons to the panel

    for (Icon icon : icons) {

        panel.add(new JLabel(icon));

    }

 

    // Create a frame for the panel

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(300, 300);

    frame.add(panel);

 

    // Make the frame visible

    frame.setVisible(true);

 

    // Create a timer to update the icons

    Timer timer = new Timer(1000, new ActionListener() {

        @Override

        public void actionPerformed(ActionEvent e) {

            // Shuffle the icons

            Collections.shuffle(icons);

 

            // Update the icons in the panel

            for (int i = 0; i < icons.size(); i++) {

                panel.getComponent(i).setIcon(icons.get(i));

            }

 

            // Repaint the panel

            panel.repaint();

        }

    });

 

    // Start the timer

    timer.start();

}

登入後複製

}

此範例說明了Collections.shuffle 隨機化圖示順序並每秒更新面板中的圖示。 repaint() 方法確保變更在螢幕上可見,並且圖示不斷更新。

透過提供這種替代方法,我們證明了與

相關的問題PaintComponent() 方法可能與imageDimension 物件無關,而是源自於原始圖形和圖像處理的特定實作代碼。

以上是儘管使用了 repaint(),為什麼我的擴充 JPanel 的 PaintComponent() 方法沒有被呼叫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板