主頁 > 資料庫 > 在JPanel加載時單擊JButton時,JLabel不可見

在JPanel加載時單擊JButton時,JLabel不可見

2022-09-15 15:12:16 資料庫

當我單擊主面板上的背景選擇器時,加載 JPanel 需要一段時間,我想在加載背景選擇器面板時顯示加載 JLabel,然后在面板最終顯示時消失。我試圖在我的按鈕動作監聽器中實作這一點。但是由于某種原因,當我從動作偵聽器中洗掉 backgroundPanel() 方法時(單擊 JButton 時未加載面板,而只是顯示了 JLabel),單擊按鈕時會顯示標簽,但通常會顯示標簽沒有出現。我不明白為什么。

視窗類:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;

/**
 *
 */
public class Window {

public static JFrame frame;
GameWindow game;
BackgroundSelector background;
static DifficultySelector difficulty;
public static MainBackgroundImage main; // start window
JProgressBar progressBar = new JProgressBar();
private boolean loaded = false;

public Window() throws IOException {

    frame = new JFrame("Brick Builder Game"); // creates JFrame

    game = new GameWindow(); // creates new GAME window
    main = new MainBackgroundImage(); // creates MAIN screen
    background = new BackgroundSelector(); // creates BACKGROUND SELECTOR window
    difficulty = new DifficultySelector(); // creates DIFFICULTY SELECTOR window

    main.setLayout(null);

    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    frame.setSize(500,500);
    frame.setVisible(true);
    frame.setResizable(false);

    frame.getContentPane().add(main); // adds MAIN screen to frame


    JButton start = new JButton();
    Image startImg = ImageIO.read(getClass().getResource("start.png"));
    start.setIcon(new ImageIcon(startImg));
    start.setBounds(150,270,200,40);
    start.setOpaque(false);
    start.setBorderPainted(false);

    JButton backgroundSelector = new JButton();
    Image selectorImg = ImageIO.read(getClass().getResource("selector.png"));
    backgroundSelector.setIcon(new ImageIcon(selectorImg));
    backgroundSelector.setBounds(150, 320,200,40);
    backgroundSelector.setOpaque(false);
    backgroundSelector.setBorderPainted(false);


    JButton quit = new JButton();
    Image quitImg = ImageIO.read(getClass().getResource("quit.png"));
    quit.setIcon(new ImageIcon(quitImg));
    quit.setBounds(150,370,200,40);
    quit.setOpaque(false);
    quit.setBorderPainted(false);

    JLabel loading = new JLabel();
    loading.setBounds(150,400,100,20);

    main.repaint();

    start.setBackground(Color.white);
    backgroundSelector.setBackground(Color.white);
    quit.setBackground(Color.white);

    start.setFocusable(false);
    quit.setFocusable(false);
    backgroundSelector.setFocusable(false);
    start.setAlignmentX(Component.CENTER_ALIGNMENT);
    quit.setAlignmentX(Component.CENTER_ALIGNMENT);
    backgroundSelector.setAlignmentX(Component.CENTER_ALIGNMENT);
    
    main.add(start); // adds JButton
    main.add(quit);
    main.add(backgroundSelector);
    main.add(loading);
    main.add(progressBar);

    start.addActionListener(e -> difficultyPanel());

    quit.addActionListener(e -> {
        frame.dispose();
    });

    backgroundSelector.addActionListener(e -> {
        loading.setText("Loading...");
        backgroundPanel();
    });

    //backgroundSelector.addActionListener(e -> backgroundPanel());
}

public static void mainPanel(){
    frame.getContentPane().removeAll();
    frame.getContentPane().add(main);
    frame.validate();
}

public void backgroundPanel(){
    //loaded = false;
    frame.getContentPane().removeAll();
    background = new BackgroundSelector();
    frame.getContentPane().add(background);
    frame.revalidate();
}

public void difficultyPanel(){
    frame.getContentPane().removeAll();
    difficulty = new DifficultySelector();
    frame.getContentPane().add(difficulty);
    frame.requestFocusInWindow();
    frame.revalidate();
}

    public static void main (String[]args) throws IOException {
        new Window();
    }
}

背景選擇器類:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyListener;

/**
 * This class creates the background selector JPanel which allows the player to choose a background
 * of their choice. A choice of 6 backgrounds is given to the player to choose from.
 *
 */
public class BackgroundSelector extends JPanel{

    DifficultySelector difficulty = new DifficultySelector();

    private final ClassLoader cl = Thread.currentThread().getContextClassLoader();
    private final Image image = Toolkit.getDefaultToolkit().getImage(cl.getResource("black.jpg"));

    JLabel label;

    // creates the radioButtons which display the backgrounds to choose from
    JRadioButton radioButton;
    JRadioButton radioButton2;
    JRadioButton radioButton3;
    JRadioButton radioButton4;
    JRadioButton radioButton5;
    JRadioButton radioButton6;

    public static boolean option1 = false;
    public static boolean option2 = false;
    public static boolean option3 = false;
    public static boolean option4 = false;
    public static boolean option5 = false;
    public static boolean option6 = false;

    /**
 * Constructor which adds the radio buttons to a button group and displays them on the JPanel using a flow layout.
 *
 */
public BackgroundSelector(){

    label = new JLabel("Please select a background", JLabel.CENTER);
    label.setFont(new Font("Verdana", Font.BOLD, 18));
    label.setForeground(Color.white);

    setLayout(new FlowLayout());
    ButtonGroup group = new ButtonGroup();
    group.add(radioButton);
    group.add(radioButton2);
    group.add(radioButton3);
    group.add(radioButton4);
    group.add(radioButton5);
    group.add(radioButton6);

    option1();
    option2();
    option3();
    option4();
    option5();
    option6();
    add(label);
}


/**
 * Paints background image of panel to black chalk image.
 * @param g
 */
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    image.getScaledInstance(500, 500,Image.SCALE_SMOOTH);
    while(!prepareImage(image, this)) {
        prepareImage(image, this);
    }
    g.drawImage(image,0,0,null);
}

/**
 * Converts the url to an image which will be used as the icon for the JRadioButton.
 *
 * @param url The url of the image.
 * @return The image with a specific height and width.
 */
public String URL(String url){
    return "<html><body><img src='"   url   "'width=128 height=128>";
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the space background.
 *
 */
public void option1() {
    String url = URL("https://www.nasa.gov/sites/default/files/styles/full_width/public/thumbnails/image/main_image_star-forming_region_carina_nircam_final-1280.jpg");
    radioButton = new JRadioButton(url);
    add(radioButton);
    radioButton.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("space.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option1 = true;
    });
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the bricks background.
 *
 */
public void option2(){
    String url = URL("https://appgrooves.com/cdn/mc/GAME_ARCADE/7_w1200.jpg");
    radioButton2 = new JRadioButton(url);
    add(radioButton2);
    radioButton2.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("space.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option2 = true;
    });
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the stars background.
 *
 */
public void option3(){
    String url = URL("https://upload.wikimedia.org/wikipedia/commons/2/26/Oldest_star_in_solar_neighbourhood.jpg");
    radioButton3 = new JRadioButton(url);
    add(radioButton3);
    radioButton3.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("stars.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option3 = true;
    });
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the bubbles background.
 *
 */
public void option4(){
    String url = URL("https://cdn.pocket-lint.com/assets/images/131835-phones-news-feature-cropped-best-iphone-wallpapers-image72-7pqcs1gy9h.jpg");
    radioButton4 = new JRadioButton(url);
    add(radioButton4);
    radioButton4.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("stars.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option4 = true;
    });
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the forest background.
 *
 */
public void option5(){
    String url = URL("https://images.hdqwalls.com/download/blue-forest-minimal-4k-kz-2048x2048.jpg");
    radioButton5 = new JRadioButton(url);
    add(radioButton5);
    radioButton5.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("stars.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option5 = true;
    });
}

/**
 * Adds radioButton to the JPanel, when clicked, creates a new game with the japanese purple background.
 *
 */
public void option6(){
    String url = URL("https://www.pixelstalk.net/wp-content/uploads/images5/Cool-Japanese-Backgrounds-HD-Free-download.jpg");
    radioButton6 = new JRadioButton(url);
    add(radioButton6);
    radioButton6.addActionListener(e -> {
        Window.frame.getContentPane().removeAll();
        //game.changeFilepath("stars.jpg");
        Window.frame.getContentPane().add(difficulty);
        Window.frame.requestFocusInWindow();
        Window.frame.revalidate();
        option6 = true;
    });
}

}

uj5u.com熱心網友回復:

只需將以下方法添加到背景選擇器:) 并在視窗中的 background() 方法上呼叫它

public void resetLayout() {
    radioButton.setSelected(false);
    radioButton2.setSelected(false);
    radioButton3.setSelected(false);
    radioButton4.setSelected(false);
    radioButton5.setSelected(false);
    radioButton6.setSelected(false);
}

真的很丑,可能會更好,但有效!

uj5u.com熱心網友回復:

無法運行代碼會導致一些假設。

根據您的描述,我會說您在加載影像時阻塞了事件調度執行緒,這將阻止 UI 更新。

有關更多詳細資訊,請參閱在 JPanel 加載時單擊 JButton 時,JLabel 不可見

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new MainPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class MainPane extends JPanel {

        public interface Observer {
            public void start();
            public void quit();
            public void didLoadBackground(BufferedImage img);
        }

        enum View {
            MAIN, START
        }

        private BufferedImage background;
        private CardLayout cardLayout;

        public MainPane() throws IOException {
            cardLayout = new CardLayout();
            setLayout(cardLayout);
            background = ImageIO.read(getClass().getResource("/images/Mando01.jpeg"));
            add(new OptionsPane(new Observer() {
                @Override
                public void start() {
                    show(View.START);
                }

                @Override
                public void quit() {
                    SwingUtilities.windowForComponent(MainPane.this).dispose();
                }

                @Override
                public void didLoadBackground(BufferedImage img) {
                    JOptionPane.showMessageDialog(MainPane.this, "You have a pretty picture", "Notice", JOptionPane.INFORMATION_MESSAGE);
                }
            }), View.MAIN);

            add(new GamePane(), View.START);
        }       

        public void add(Component component, View view) {
            add(component, view.name());
        }

        public void show(View view) {
            cardLayout.show(this, view.name());
        }

        @Override
        public Dimension getPreferredSize() {
            if (background != null) {
                return new Dimension(background.getWidth(), background.getHeight());
            }
            return super.getPreferredSize();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background == null) {
                return;
            }
            int x = (getWidth() - background.getWidth()) / 2;
            int y = (getHeight() - background.getHeight()) / 2;
            g.drawImage(background, x, y, this);
        }
    }

    public class OptionsPane extends JPanel {
        private MainPane.Observer observer;
        public OptionsPane(MainPane.Observer observer) {
            setOpaque(false);
            setLayout(new GridBagLayout());
            JButton start = new JButton("Start");
            start.setOpaque(false);
            start.setBorderPainted(false);
            start.setForeground(Color.WHITE);

            JButton backgroundSelector = new JButton("Background");
            backgroundSelector.setOpaque(false);
            backgroundSelector.setBorderPainted(false);
            backgroundSelector.setForeground(Color.WHITE);

            JButton quit = new JButton("Quit");
            quit.setOpaque(false);
            quit.setBorderPainted(false);
            quit.setForeground(Color.WHITE);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weighty = 1;
            gbc.anchor = GridBagConstraints.SOUTH;
            gbc.insets = new Insets(4, 4, 4, 4);

            add(start, gbc); // adds JButton
            gbc.weighty = 0;
            gbc.gridy  ;
            add(backgroundSelector, gbc);
            gbc.gridy  ;
            add(quit, gbc);

            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    observer.start();
                }
            });

            quit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    observer.quit();
                }
            });

            backgroundSelector.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // This "could" use the glassPane, but that's
                    // an additional complexity
                    JPanel panel = new JPanel(new GridBagLayout());
                    JLabel label = new JLabel("Loading...");
                    label.setHorizontalAlignment(JLabel.CENTER);
                    JProgressBar progressBar = new JProgressBar(0, 100);

                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = GridBagConstraints.REMAINDER;
                    gbc.insets = new Insets(2, 2, 2, 2);
                    gbc.fill = gbc.HORIZONTAL;

                    panel.setBorder(new EmptyBorder(8, 8, 8, 8));
                    panel.add(label, gbc);
                    panel.add(progressBar, gbc);

                    gbc = new GridBagConstraints();
                    gbc.gridx = 0;
                    gbc.gridy = 0;
                    gbc.gridwidth = gbc.REMAINDER;
                    gbc.gridheight = gbc.REMAINDER;

                    add(panel, gbc);

                    revalidate();
                    repaint();

                    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {
                        @Override
                        protected BufferedImage doInBackground() throws Exception {
                            for (int progress = 0; progress <= 100; progress  ) {
                                Thread.sleep(50);
                                setProgress(progress);
                            }
                            return null;
                        }
                    };
                    worker.addPropertyChangeListener(new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            String name = evt.getPropertyName();
                            if (worker.getState() == SwingWorker.StateValue.DONE) {
                                remove(panel);
                                revalidate();
                                repaint();
                                try {
                                    observer.didLoadBackground(worker.get());
                                } catch (InterruptedException | ExecutionException ex) {
                                    ex.printStackTrace();
                                    JOptionPane.showMessageDialog(OptionsPane.this, "Failed to load image", "Error", JOptionPane.ERROR_MESSAGE);
                                }
                            } else if ("progress".equalsIgnoreCase(name)) {
                                progressBar.setValue((int)evt.getNewValue());
                            }
                        }

                    });
                    worker.execute();
                }
            });
        }
    }

    public class GamePane extends JPanel {
        public GamePane() {
            setOpaque(false);
            setLayout(new GridBagLayout());
            add(new JLabel("Let's get this party started"));
        }        
    }
}

現在,如果您在加載影像時需要進度反饋,這是一個更復雜的解決方案,有關更多詳細資訊,請參閱Using JProgressBar while convert image to byte array

好的,但現在我遇到了另一個問題。使用卡片布局時,我無法添加按鍵監聽器、setFocusable 或 requestFocusableInWindow,因此當我開始游戲時我的撥片不會移動

停止使用KeyListener,這不是您想要實作的適當機制,而是使用鍵系結API,這將消除對所有相關KeyListener黑客的需要

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new MainPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class MainPane extends JPanel {

        public interface Observer {
            public void start();

            public void quit();

            public void didLoadBackground(BufferedImage img);
        }

        enum View {
            MAIN, START
        }

        private BufferedImage background;
        private CardLayout cardLayout;

        public MainPane() throws IOException {
            cardLayout = new CardLayout();
            setLayout(cardLayout);
            background = scaled(ImageIO.read(getClass().getResource("/images/Mando01.jpeg")));
            add(new OptionsPane(new Observer() {
                @Override
                public void start() {
                    show(View.START);
                }

                @Override
                public void quit() {
                    SwingUtilities.windowForComponent(MainPane.this).dispose();
                }

                @Override
                public void didLoadBackground(BufferedImage img) {
                    JOptionPane.showMessageDialog(MainPane.this, "You have a pretty picture", "Notice", JOptionPane.INFORMATION_MESSAGE);
                }
            }), View.MAIN);

            add(new GamePane(), View.START);
        }

        protected BufferedImage scaled(BufferedImage original) {
            BufferedImage scaled = new BufferedImage(original.getWidth() / 2, original.getHeight() / 2, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = scaled.createGraphics();
            g2d.transform(AffineTransform.getScaleInstance(0.5, 0.5));
            g2d.drawImage(original, 0, 0, this);
            g2d.dispose();
            return scaled;
        }

        public void add(Component component, View view) {
            add(component, view.name());
        }

        public void show(View view) {
            cardLayout.show(this, view.name());
        }

        @Override
        public Dimension getPreferredSize() {
            if (background != null) {
                return new Dimension(background.getWidth(), background.getHeight());
            }
            return super.getPreferredSize();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background == null) {
                return;
            }
            int x = (getWidth() - background.getWidth()) / 2;
            int y = (getHeight() - background.getHeight()) / 2;
            g.drawImage(background, x, y, this);
        }
    }

    public class OptionsPane extends JPanel {
        private MainPane.Observer observer;

        public OptionsPane(MainPane.Observer observer) {
            setOpaque(false);
            setLayout(new GridBagLayout());
            JButton start = new JButton("Start");
            start.setOpaque(false);
            start.setBorderPainted(false);
            start.setForeground(Color.WHITE);

            JButton backgroundSelector = new JButton("Background");
            backgroundSelector.setOpaque(false);
            backgroundSelector.setBorderPainted(false);
            backgroundSelector.setForeground(Color.WHITE);

            JButton quit = new JButton("Quit");
            quit.setOpaque(false);
            quit.setBorderPainted(false);
            quit.setForeground(Color.WHITE);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weighty = 1;
            gbc.anchor = GridBagConstraints.SOUTH;
            gbc.insets = new Insets(4, 4, 4, 4);

            add(start, gbc); // adds JButton
            gbc.weighty = 0;
            gbc.gridy  ;
            add(backgroundSelector, gbc);
            gbc.gridy  ;
            add(quit, gbc);

            start.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    observer.start();
                }
            });

            quit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    observer.quit();
                }
            });

            backgroundSelector.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // This "could" use the glassPane, but that's
                    // an additional complexity
                    JPanel panel = new JPanel(new GridBagLayout());
                    JLabel label = new JLabel("Loading...");
                    label.setHorizontalAlignment(JLabel.CENTER);
                    JProgressBar progressBar = new JProgressBar(0, 100);

                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = GridBagConstraints.REMAINDER;
                    gbc.insets = new Insets(2, 2, 2, 2);
                    gbc.fill = gbc.HORIZONTAL;

                    panel.setBorder(new EmptyBorder(8, 8, 8, 8));
                    panel.add(label, gbc);
                    panel.add(progressBar, gbc);

                    gbc = new GridBagConstraints();
                    gbc.gridx = 0;
                    gbc.gridy = 0;
                    gbc.gridwidth = gbc.REMAINDER;
                    gbc.gridheight = gbc.REMAINDER;

                    add(panel, gbc);

                    revalidate();
                    repaint();

                    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {
                        @Override
                        protected BufferedImage doInBackground() throws Exception {
                            for (int progress = 0; progress <= 100; progress  ) {
                                Thread.sleep(50);
                                setProgress(progress);
                            }
                            return null;
                        }
                    };
                    worker.addPropertyChangeListener(new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            String name = evt.getPropertyName();
                            if (worker.getState() == SwingWorker.StateValue.DONE) {
                                remove(panel);
                                revalidate();
                                repaint();
                                try {
                                    observer.didLoadBackground(worker.get());
                                } catch (InterruptedException | ExecutionException ex) {
                                    ex.printStackTrace();
                                    JOptionPane.showMessageDialog(OptionsPane.this, "Failed to load image", "Error", JOptionPane.ERROR_MESSAGE);
                                }
                            } else if ("progress".equalsIgnoreCase(name)) {
                                progressBar.setValue((int) evt.getNewValue());
                            }
                        }

                    });
                    worker.execute();
                }
            });
        }
    }

    public class GamePane extends JPanel implements DeltaAction.Observer {

        public class Box {
            private Shape box = new Rectangle2D.Double(0, 0, 50, 50);
            private Point p = new Point();

            public void paint(Graphics2D g2d) {
                g2d = (Graphics2D) g2d.create();
                g2d.setColor(Color.BLUE);
                g2d.translate(p.getX(), p.getY());
                g2d.fill(box);
                g2d.dispose();
            }

            public Point getLocation() {
                return new Point(p);
            }

            public void setLocation(Point p) {
                this.p = p;
            }

            public Rectangle2D getBounds() {
                return new Rectangle2D.Double(p.getX(), p.getY(), box.getBounds2D().getHeight(), box.getBounds2D().getHeight());
            }
        }

        protected enum KeyInput {
            PRESSED_UP, RELEASED_UP,
            PRESSED_DOWN, RELEASED_DOWN,
            PRESSED_LEFT, RELEASED_LEFT,
            PRESSED_RIGHT, RELEASED_RIGHT;
        }

        private Box box = new Box();
        private int xDelta = 0;
        private int yDelta = 0;

        private Timer timer;

        public GamePane() {
            setOpaque(false);
            setLayout(new GridBagLayout());
            add(new JLabel("Let's get this party started"));

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), KeyInput.PRESSED_UP);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), KeyInput.RELEASED_UP);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), KeyInput.PRESSED_DOWN);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), KeyInput.RELEASED_DOWN);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), KeyInput.PRESSED_LEFT);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), KeyInput.RELEASED_LEFT);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), KeyInput.PRESSED_RIGHT);
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), KeyInput.RELEASED_RIGHT);

            am.put(KeyInput.PRESSED_UP, new DeltaAction(DeltaAction.Direction.UP, true, this));
            am.put(KeyInput.RELEASED_UP, new DeltaAction(DeltaAction.Direction.UP, false, this));
            am.put(KeyInput.PRESSED_DOWN, new DeltaAction(DeltaAction.Direction.DOWN, true, this));
            am.put(KeyInput.RELEASED_DOWN, new DeltaAction(DeltaAction.Direction.DOWN, false, this));
            am.put(KeyInput.PRESSED_LEFT, new DeltaAction(DeltaAction.Direction.LEFT, true, this));
            am.put(KeyInput.RELEASED_LEFT, new DeltaAction(DeltaAction.Direction.LEFT, false, this));
            am.put(KeyInput.PRESSED_RIGHT, new DeltaAction(DeltaAction.Direction.RIGHT, true, this));
            am.put(KeyInput.RELEASED_RIGHT, new DeltaAction(DeltaAction.Direction.RIGHT, false, this));

            timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Point location = box.getLocation();
                    location.x  = xDelta;
                    location.y  = yDelta;
                    box.setLocation(location);

                    Rectangle2D bounds = box.getBounds();
                    if (bounds.getX() < 0) {
                        location.x = 0;
                    } else if (bounds.getX()   bounds.getWidth() > getWidth()) {
                        location.x = (int)(getWidth() - bounds.getWidth());
                    }
                    if (bounds.getY() < 0) {
                        location.y = 0;
                    } else if (bounds.getY()   bounds.getHeight()> getHeight()) {
                        location.y = (int)(getHeight() - bounds.getHeight());
                    }

                    box.setLocation(location);
                    repaint();
                }
            });

            addComponentListener(new ComponentAdapter() {
                @Override
                public void componentHidden(ComponentEvent e) {
                    timer.stop();
                }

                @Override
                public void componentShown(ComponentEvent e) {
                    System.out.println("Hello");
                    timer.start();
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            box.paint(g2d);
            g2d.dispose();
        }

        @Override
        public void directionApplied(DeltaAction.Direction direction, boolean activate) {
            switch (direction) {
                case UP:
                    yDelta = activate ? -4 : 0;
                    break;
                case DOWN:
                    yDelta = activate ? 4 : 0;
                    break;
                case LEFT:
                    xDelta = activate ? -4 : 0;
                    break;
                case RIGHT:
                    xDelta = activate ? 4 : 0;
                    break;
            }
        }

    }

    public class DeltaAction extends AbstractAction {
        public interface Observer {
            public void directionApplied(Direction direction, boolean activate);
        }

        public enum Direction {
            UP, DOWN, LEFT, RIGHT;
        }

        private Direction direction;
        private boolean activate;
        private Observer observer;

        public DeltaAction(Direction direction, boolean activate, Observer observer) {
            this.direction = direction;
            this.activate = activate;
            this.observer = observer;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            observer.directionApplied(direction, activate);
        }
    }
}

我的卡片布局有很多錯誤,它破壞了我的整個應用程式

CardLayout這與您選擇如何設計原始應用程式無關。布局是您的朋友,花時間學習如何使用它們

如果背景面板已經添加到卡片窗格中,我不知道如何更新它,我能想到的唯一方法是銷毀它并每次添加一個新面板(這是我所擁有的,但需要很長時間才能加載)

然后不要 - 這是我的全部觀點,你需要改變你對問題的看法。

要更改背景窗格的背景影像,您需要做的就是更改對面板正在使用的背景影像的參考。

我有一個“基本”窗格,它將使用BorderLayout并包含“背景”窗格。然后“背景”窗格將對其進行CardLayout設定,然后它將成為所有其他組件的父容器。

當用戶選擇一個新影像時,您將利用“觀察者模式”生成一個回傳到“基本”窗格的通知,然后將新影像分配給背景窗格。

我已經沒有空間發布任何新的更新,所以這是我可以通過一個簡單的要點提供的最后一個

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/508252.html

標籤:爪哇 摇摆 面板 按钮

上一篇:JGoodiesBinding:如何系結兩個ValueModel?

下一篇:將模板類宣告為朋友

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • GPU虛擬機創建時間深度優化

    **?桔妹導讀:**GPU虛擬機實體創建速度慢是公有云面臨的普遍問題,由于通常情況下創建虛擬機屬于低頻操作而未引起業界的重視,實際生產中還是存在對GPU實體創建時間有苛刻要求的業務場景。本文將介紹滴滴云在解決該問題時的思路、方法、并展示最終的優化成果。 從公有云服務商那里購買過虛擬主機的資深用戶,一 ......

    uj5u.com 2020-09-10 06:09:13 more
  • 可編程網卡芯片在滴滴云網路的應用實踐

    **?桔妹導讀:**隨著云規模不斷擴大以及業務層面對延遲、帶寬的要求越來越高,采用DPDK 加速網路報文處理的方式在橫向縱向擴展都出現了局限性。可編程芯片成為業界熱點。本文主要講述了可編程網卡芯片在滴滴云網路中的應用實踐,遇到的問題、帶來的收益以及開源社區貢獻。 #1. 資料中心面臨的問題 隨著滴滴 ......

    uj5u.com 2020-09-10 06:10:21 more
  • 滴滴資料通道服務演進之路

    **?桔妹導讀:**滴滴資料通道引擎承載著全公司的資料同步,為下游實時和離線場景提供了必不可少的源資料。隨著任務量的不斷增加,資料通道的整體架構也隨之發生改變。本文介紹了滴滴資料通道的發展歷程,遇到的問題以及今后的規劃。 #1. 背景 資料,對于任何一家互聯網公司來說都是非常重要的資產,公司的大資料 ......

    uj5u.com 2020-09-10 06:11:05 more
  • 滴滴AI Labs斬獲國際機器翻譯大賽中譯英方向世界第三

    **桔妹導讀:**深耕人工智能領域,致力于探索AI讓出行更美好的滴滴AI Labs再次斬獲國際大獎,這次獲獎的專案是什么呢?一起來看看詳細報道吧! 近日,由國際計算語言學協會ACL(The Association for Computational Linguistics)舉辦的世界最具影響力的機器 ......

    uj5u.com 2020-09-10 06:11:29 more
  • MPP (Massively Parallel Processing)大規模并行處理

    1、什么是mpp? MPP (Massively Parallel Processing),即大規模并行處理,在資料庫非共享集群中,每個節點都有獨立的磁盤存盤系統和記憶體系統,業務資料根據資料庫模型和應用特點劃分到各個節點上,每臺資料節點通過專用網路或者商業通用網路互相連接,彼此協同計算,作為整體提供 ......

    uj5u.com 2020-09-10 06:11:41 more
  • 滴滴資料倉庫指標體系建設實踐

    **桔妹導讀:**指標體系是什么?如何使用OSM模型和AARRR模型搭建指標體系?如何統一流程、規范化、工具化管理指標體系?本文會對建設的方法論結合滴滴資料指標體系建設實踐進行解答分析。 #1. 什么是指標體系 ##1.1 指標體系定義 指標體系是將零散單點的具有相互聯系的指標,系統化的組織起來,通 ......

    uj5u.com 2020-09-10 06:12:52 more
  • 單表千萬行資料庫 LIKE 搜索優化手記

    我們經常在資料庫中使用 LIKE 運算子來完成對資料的模糊搜索,LIKE 運算子用于在 WHERE 子句中搜索列中的指定模式。 如果需要查找客戶表中所有姓氏是“張”的資料,可以使用下面的 SQL 陳述句: SELECT * FROM Customer WHERE Name LIKE '張%' 如果需要 ......

    uj5u.com 2020-09-10 06:13:25 more
  • 滴滴Ceph分布式存盤系統優化之鎖優化

    **桔妹導讀:**Ceph是國際知名的開源分布式存盤系統,在工業界和學術界都有著重要的影響。Ceph的架構和演算法設計發表在國際系統領域頂級會議OSDI、SOSP、SC等上。Ceph社區得到Red Hat、SUSE、Intel等大公司的大力支持。Ceph是國際云計算領域應用最廣泛的開源分布式存盤系統, ......

    uj5u.com 2020-09-10 06:14:51 more
  • es~通過ElasticsearchTemplate進行聚合~嵌套聚合

    之前寫過《es~通過ElasticsearchTemplate進行聚合操作》的文章,這一次主要寫一個嵌套的聚合,例如先對sex集合,再對desc聚合,最后再對age求和,共三層嵌套。 Aggregations的部分特性類似于SQL語言中的group by,avg,sum等函式,Aggregation ......

    uj5u.com 2020-09-10 06:14:59 more
  • 爬蟲日志監控 -- Elastc Stack(ELK)部署

    傻瓜式部署,只需替換IP與用戶 導讀: 現ELK四大組件分別為:Elasticsearch(核心)、logstash(處理)、filebeat(采集)、kibana(可視化) 下載均在https://www.elastic.co/cn/downloads/下tar包,各組件版本最好一致,配合fdm會 ......

    uj5u.com 2020-09-10 06:15:05 more
最新发布
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:33:24 more
  • MySQL中binlog備份腳本分享

    關于MySQL的二進制日志(binlog),我們都知道二進制日志(binlog)非常重要,尤其當你需要point to point災難恢復的時侯,所以我們要對其進行備份。關于二進制日志(binlog)的備份,可以基于flush logs方式先切換binlog,然后拷貝&壓縮到到遠程服務器或本地服務器 ......

    uj5u.com 2023-04-20 08:28:06 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:27:27 more
  • 快取與資料庫雙寫一致性幾種策略分析

    本文將對幾種快取與資料庫保證資料一致性的使用方式進行分析。為保證高并發性能,以下分析場景不考慮執行的原子性及加鎖等強一致性要求的場景,僅追求最終一致性。 ......

    uj5u.com 2023-04-20 08:26:48 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:26:35 more
  • 云時代,MySQL到ClickHouse資料同步產品對比推薦

    ClickHouse 在執行分析查詢時的速度優勢很好的彌補了MySQL的不足,但是對于很多開發者和DBA來說,如何將MySQL穩定、高效、簡單的同步到 ClickHouse 卻很困難。本文對比了 NineData、MaterializeMySQL(ClickHouse自帶)、Bifrost 三款產品... ......

    uj5u.com 2023-04-20 08:26:29 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:25:13 more
  • Redis 報”OutOfDirectMemoryError“(堆外記憶體溢位)

    Redis 報錯“OutOfDirectMemoryError(堆外記憶體溢位) ”問題如下: 一、報錯資訊: 使用 Redis 的業務介面 ,產生 OutOfDirectMemoryError(堆外記憶體溢位),如圖: 格式化后的報錯資訊: { "timestamp": "2023-04-17 22: ......

    uj5u.com 2023-04-20 08:24:54 more
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:24:03 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:23:11 more