JButton que no aparecen correctamente sobre GIF

EkLuthra:

Tengo un programa que se supone ser esencialmente una pantalla de título para algunos juegos. El fondo es un GIF (no estoy seguro si eso es contribuir al problema), y tengo que tener algo de JButtonsque permiten que corra los juegos reales. El problema es que los JButtonúnicos aparece a veces cuando pasa sobre ella (y para una fracción de segundo, por cierto), de lo contrario es invisible. Funciona muy bien, va al juego y todo, es simplemente invisible.

He tratado de ver si el problema es el hecho de que estoy usando un archivo GIF, así como el paintComponent()método, aunque, simplemente no se presentó cuando utilicé un archivo JPEG.

Aquí está el código:

public class TestingGrounds extends JFrame{
     //declarations
     JButton snakeButton;
     JPanel snakeButtonPanel;
     JFrame window;
     Container con;
     TitleScreenHandler tsHandler = new TitleScreenHandler();
     //constructor
     public TestingGrounds(){
          //main JFrame
          window = new JFrame("Title Screen");
          window.add(new ImagePanel());
          window.setResizable(false);
          window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          window.setSize(1831, 1030);
          window.setVisible(true);
          window.setLocationRelativeTo(null);
          window.setLayout(null);

          con = window.getContentPane();

          //panel for the button to go to the snake game
          snakeButtonPanel =  new JPanel();
          snakeButtonPanel.setBounds(100,100,600,150);

          //button to go to snake game
          snakeButton = new JButton("Snake");
          snakeButton.setBackground(Color.BLACK);
          snakeButton.setForeground(Color.WHITE);
          snakeButton.setFont(new Font("Times New Roman", Font.ITALIC, 30));
          snakeButton.addActionListener(tsHandler);
          snakeButton.setFocusPainted(false);
          //adding button to panel
          snakeButtonPanel.add(snakeButton);
          //adding panel to container
          con.add(snakeButtonPanel);
          //setting the panel as visible
          snakeButtonPanel.setVisible(true);

     }
     //main method for running constructor
     public static void main(String[] args) {
          new TestingGrounds();
     }

     //what to do if the button is pressed
     public class TitleScreenHandler implements ActionListener {
          public void actionPerformed(ActionEvent event){
               //goes to main game screen if start button is pressed
               new SnakeGame();
          }
     }
}
//class for using the gif
class ImagePanel extends JPanel {
     Image image;
     public ImagePanel() {
          image = Toolkit.getDefaultToolkit().createImage("C:/Users/eklut/Desktop/Coding/ICS4U1/src/graphicsstuff/snek/source.gif");
     }

     public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.drawImage(image, 0, 0, this);
     }
}

Lo siento, sé que es una buena cantidad de código, pero me siento como si tuviera para mostrar todos de la misma ya que no estoy muy seguro de que el problema se deriva de.

Yo esperaba que el botón para mostrar a lo largo de la gif, pero casi parece como si estuviera sucediendo en torno a la otra manera

Andrew Thompson:

Esto incluye MCVE tantos cambios que es mejor que pasar por el código y ver los comentarios.

introducir descripción de la imagen aquí

Tenga en cuenta que el código utiliza una animación GIF como el BG. Yo diría que se utilizó para demostrar explícitamente que se trataba de un GIF, pero la verdad es que la página de imágenes de ejemplo sólo contiene archivos GIF animados. El formato no es muy bueno para cualquier otra cosa, dado un PNG apoyará translucidez y mucho más colores que un archivo GIF.

import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import javax.swing.*;
import java.net.URL;

//public class TestingGrounds extends JFrame {
public class TestingGrounds {

    //declarations
    JButton snakeButton;
    JPanel snakeButtonPanel;
    JFrame window;
    TitleScreenHandler tsHandler = new TitleScreenHandler();

    //constructor
    public TestingGrounds() {
        //main JFrame
        window = new JFrame("Title Screen");
        try {
            JPanel imagePanel = new ImagePanel();
            imagePanel.setLayout(new BorderLayout());
            window.add(imagePanel);
            //window.setResizable(false);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Don't guess sizes needed. They will be wrong on other 
            // PLAFs or platforms.
            //window.setSize(850, 600);

            // should be last
            //window.setVisible(true);
            window.setLocationRelativeTo(null);
            //window.setLayout(null);

            //con = window.getContentPane();
            //panel for the button to go to the snake game
            snakeButtonPanel = new JPanel(new GridBagLayout());
            snakeButtonPanel.setOpaque(false);
            //snakeButtonPanel.setBounds(100, 100, 600, 150);

            //button to go to snake game
            snakeButton = new JButton("Snake");
            snakeButton.setMargin(new Insets(10,40,10,40));
            snakeButton.setBackground(Color.BLACK);
            snakeButton.setForeground(Color.WHITE);
            snakeButton.setFont(new Font("Times New Roman", Font.ITALIC, 30));
            snakeButton.addActionListener(tsHandler);
            snakeButton.setFocusPainted(false);
            //adding button to panel
            snakeButtonPanel.add(snakeButton);
            //adding panel to container
            //con.add(snakeButtonPanel);
            // Adding the container to imagePanel
            imagePanel.add(snakeButtonPanel);

            //setting the panel as visible
            snakeButtonPanel.setVisible(true);

            window.pack();
            window.setVisible(true);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    //main method for running constructor
    public static void main(String[] args) {
        new TestingGrounds();
    }

    //what to do if the button is pressed
    public class TitleScreenHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            //goes to main game screen if start button is pressed
            //new SnakeGame();
            JOptionPane.showMessageDialog(snakeButton, "Snake Game");
        }
    }
}
//class for using the gif

class ImagePanel extends JPanel {

    Image image;

    public ImagePanel() throws MalformedURLException {
        image = Toolkit.getDefaultToolkit().createImage(
                new URL("https://i.stack.imgur.com/OtTIY.gif"));
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 1);
        try {
            mt.waitForAll();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }

    @Override
    public Dimension getPreferredSize() {
        // this allows us to pack() the window around the image
        return (new Dimension(image.getWidth(this), image.getHeight(this)));
    }
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=332414&siteId=1
Recomendado
Clasificación