JLabel not showing up no matter what I do

回眸只為那壹抹淺笑 提交于 2019-12-12 02:22:03

问题


I have tried a ton of different things to try to get the JLabel to show but I don't understand why it is not working. I have tried resizing it, though that is not what i want to do, I have tried other classes, but I would prefer to stick with this one, and it is starting to get really frustrating. If you have any ideas please help. But please try to keep them simple and explain very clearly as I am still quite new to java. I have only been going for about three or four months. Here is my code:

package com.thefallenpaladin;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * Created by darkp_000 on 11/4/2015.
 */
@SuppressWarnings("serial")
public class Game extends JPanel implements KeyListener,MouseListener {

    public boolean mainMenu = true;

    public int winWidth = 700;  //Window Stats
    public int winHeight = 600;

    public int buttonOneX = 60; // Button Stats
    public int buttonOneY = 240;
    public int buttonOneW = 100;
    public int buttonOneH = 75;
    public boolean buttonOne = false;

    public int mouseX; // not set because it is set in mouseClicked
    public int mouseY;

    public static void main(String[] args) {
        Game game = new Game();

        JFrame window = new JFrame("I hate this");
        JLabel onePlayer = new JLabel();
        onePlayer.setLocation(0,0/*game.buttonOneX +         game.buttonOneX/2,game.buttonOneY + game.buttonOneY/2*/);
        window.add(game);

        window.setFocusable(true);
        window.setResizable(false);
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setSize(700,600); //TODO
        window.setVisible(true);

        game.requestFocusInWindow();
        game.add(onePlayer);
        game.addKeyListener(game);
        game.addMouseListener(game);


        window.setLocationRelativeTo(null);

        while(true) { // Main Game loop
            onePlayer.setText("One Player");
            game.repaint();
            game.customUpdate();
        } 
    }

    public void customUpdate() {
        if(mouseX > buttonOneX && mouseX < buttonOneX+buttonOneX && mouseY >     buttonOneY && mouseY < buttonOneY+buttonOneY && mainMenu) {
            buttonOne = true;
            System.out.print("Starting Game");
        }
    }

    public void paint(Graphics g) {
        if(mainMenu) {
            g.setColor(Color.CYAN); // Set main menu
            g.fillRect(0,0,winWidth,winHeight);
            g.setColor(Color.GREEN);
            g.fillRect(buttonOneX,buttonOneY,buttonOneW,buttonOneH);
        }
        if(buttonOne) {
            mainMenu = false;
            g.setColor(Color.GREEN);
            g.fillRect(0,0,winWidth,winHeight);
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {
        System.out.println(e);
    }

    public void keyReleased(KeyEvent e) {

    }

    public void mouseClicked(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {
//        System.out.println(e);
        mouseX = e.getX();
        mouseY = e.getY();

}

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }
    }

回答1:


Okay so you've made a couple of basic mistakes...

First, JLabel onePlayer = new JLabel(); creates an empty label, with no size (0x0) and since labels are transparent by default, you'd not see it

Next, you've overridden paint of a top level container (JFrame), but failed to honor the paint chain effectively preventing any of the child components from ever getting painted

public void paint(Graphics g) {
    if (mainMenu) {
        g.setColor(Color.CYAN); // Set main menu
        g.fillRect(0, 0, winWidth, winHeight);
        g.setColor(Color.GREEN);
        g.fillRect(buttonOneX, buttonOneY, buttonOneW, buttonOneH);
    }
    if (buttonOne) {
        mainMenu = false;
        g.setColor(Color.GREEN);
        g.fillRect(0, 0, winWidth, winHeight);
    }
}

So, if I remove your paint method and change JLabel onePlayer = new JLabel(); to JLabel onePlayer = new JLabel("I'm a label"); I get this output...

Also...

while (true) { // Main Game loop
    onePlayer.setText("One Player");
    game.repaint();
    game.customUpdate();
}

has the potential to try screw up your program, you have no guarantee's in what thread your main method is been called and you should not make assumptions.

Start by creating a custom component, extending from something like JPanel and override it's paintComponent method, place your custom painting there. In fact, you should have a panel for each state of your game (menu, running, settings, etc).

Add these to your frame (probably using a CardLayout to enable you to easily switch between them)

Use either a Thread or Swing Timer as a main game loop, one which you create explicitly.

Have a look at Painting in AWT and Swing, Performing Custom Painting, How to Use CardLayout and How to use Swing Timers for some more details

As a "conceptual" example...

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class AwesomeGame {

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

    public AwesomeGame() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new ContentPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface NavigationController {
        public void letsPlay();
    }

    public class ContentPane extends JPanel implements NavigationController {

        private CardLayout cardLayout;
        private GamePane gamePane;

        public ContentPane() {
            cardLayout = new CardLayout();
            setLayout(cardLayout);
            add(new MenuPane(this), "TheMenu");
            add((gamePane = new GamePane()), "TheGame");
            cardLayout.show(this, "TheMenu");
        }

        @Override
        public void letsPlay() {
            cardLayout.show(this, "TheGame");
            gamePane.play();
        }

    }

    public class MenuPane extends JPanel {

        public MenuPane(NavigationController navigationController) {
            JLabel label = new JLabel("My Super Dupa Awesome Game!");
            label.setFont(label.getFont().deriveFont(Font.BOLD, 48));
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(label, gbc);

            JButton play = new JButton("Play Now!");
            play.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    navigationController.letsPlay();
                }
            });
            add(play, gbc);

            setBackground(Color.GREEN);
        }

    }


    public class GamePane extends JPanel {

        public GamePane() {
            setBackground(Color.BLUE);
        }

        public void play() {
            Timer timer = new Timer(500, new ActionListener() {
                int count;
                @Override
                public void actionPerformed(ActionEvent e) {
                    count++;
                    if (count % 2 == 0) {
                        setForeground(Color.BLACK);
                    } else {
                        setForeground(Color.RED);
                    }
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String text = "I bet you're blowen away by it's awesomness!";
            FontMetrics fm = g2d.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(text)) / 2;
            int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
            g2d.drawString(text, x, y);
            g2d.dispose();
        }

    }
}


来源:https://stackoverflow.com/questions/33536829/jlabel-not-showing-up-no-matter-what-i-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!