java - 使用另一个类中的 jbutton 调用带有绘制和线程的 main 方法

标签 java swing

伙计们,我在这里有两堂课。当我使用其他类中的 jbutton 调用类游戏的主要方法时,只会出现一个带有白屏的框架。这是代码。谢谢您的帮助。第一类

@SuppressWarnings("serial")
public class Game extends JPanel {

    Ball ball = new Ball(this);
    Racquet racquet = new Racquet(this);
    int score = 0;
    int speed = 1;


    private int getScore() {


        return score;
    }
    private int getSpeed(){

        return speed;
    }

    public Game() {


        addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                racquet.keyReleased(e);
            }

            @Override
            public void keyPressed(KeyEvent e) {
                racquet.keyPressed(e);
            }
        });
        setFocusable(true);

    }

    public void move() {
        ball.move();
        racquet.move();
    }

    @Override
    public void paint(Graphics g) {


        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);


        ball.paint(g2d);
        racquet.paint(g2d);

        g2d.setColor(Color.black);
        g2d.setFont(new Font("Showcard Gothic", Font.BOLD, 20));

        g2d.drawString(String.valueOf("Your Score:" + getScore()), 340, 30);


        g2d.drawString(String.valueOf("Game Speed:" + getSpeed()), 340, 220);
        g2d.drawLine(300, 400, 300, -50);



    }


    public void gameOver() {

        JOptionPane.showMessageDialog(this, "your score is: " + getScore(),
                "Game Over", JOptionPane.YES_NO_OPTION);
        System.exit(ABORT);
    }




    public static void main(String[] args) throws InterruptedException {

        JFrame frame = new JFrame("Mini Tennis");

        Game game = new Game();

        frame.add(game);
        frame.setSize(550, 400);

        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while (true) {
            game.move();
            game.repaint();
            Thread.sleep(10);

    }
}
} 

二等

public class Main extends JFrame implements ActionListener{

    JPanel mainPanel;
    JLabel title;
    Color bgColor = new Color(51,137,237);
    JButton startBtn, regBtn, viewBtn, exitBtn;
    public Main(){

    setSize(550, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    mainPanel();
    setVisible(true);

    }
    void mainPanel(){

        mainPanel = new JPanel();
        add(mainPanel);
        mainPanel.setBackground(bgColor);
        mainPanel.setLayout(null);

        title = new JLabel("Ball Catcher");
        mainPanel.add(title);
        title.setBounds(130,1,500,200);
        title.setForeground(Color.white);
        title.setFont(new Font("Showcard Gothic", Font.BOLD, 35));

        startBtn = new JButton("START");
        mainPanel.add(startBtn);
        startBtn.setBounds(200,150,130,40);
        startBtn.addActionListener(this);
        startBtn.setForeground(Color.WHITE);
        startBtn.setFont(new Font("Showcard Gothic", Font.BOLD, 20));
        startBtn.setBackground(bgColor);

        regBtn = new JButton("REGISTER");
        mainPanel.add(regBtn);
        regBtn.setBounds(200,200,130,40);
        regBtn.setForeground(Color.WHITE);
        regBtn.addActionListener(this);
        regBtn.setFont(new Font("Showcard Gothic", Font.BOLD, 15));
        regBtn.setBackground(bgColor);

        viewBtn = new JButton("VIEW SCORE");
        mainPanel.add(viewBtn);
        viewBtn.setBounds(200,250,130,40);
        viewBtn.setForeground(Color.WHITE);
        viewBtn.setFont(new Font("Showcard Gothic", Font.BOLD, 15));
        viewBtn.setBackground(bgColor);

        exitBtn = new JButton("EXIT");
        mainPanel.add(  exitBtn);
        exitBtn.setBounds(200,300,130,40);
        exitBtn.setForeground(Color.WHITE);
        exitBtn.setFont(new Font("Showcard Gothic", Font.BOLD, 15));
        exitBtn.setBackground(bgColor);


    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == startBtn){
            String[] args={};
           try {
            Game.main(args);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        }

        if(e.getSource() == regBtn){

            new Register();
            dispose();

        }

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

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());


                    break;  
                }
            }
        } catch (Exception ex) 
        {

        }
        new Main();
    }
}

最佳答案

您的代码存在很多问题,太多了,无法全部解决,但其中包括:

  • 重写 JPanel 的绘制方法。
  • 在调用此 super 的paintComponent(??)的绘制方法内
  • 从正在运行的类中调用另一个类的 main 方法。
  • 在 Swing gui 中使用 while (true)...
  • ...等

关于你的主要问题——不要调用另一个类的 main 方法,因为这样做你会抛出所有的 OOP。相反,创建一个实例并调用实例的非静态方法。顺便说一下,您的代码由于 while (true) 阻塞了 Swing 事件线程而卡住。相反,请使用 Swing 计时器。但最重要的是,扔掉这段代码并重新开始。

改进建议:

  • 使用 Swing Timer对于 Swing 动画,而不是 while (true)
  • 不要在 main 方法内部运行游戏循环,因为它对于游戏循环来说太重要了。让它在控制游戏的主类中运行。 main 方法主要用于设置玩家,然后让他们开始交互,仅此而已。
  • 不要调用其他类的静态主方法。
  • 而是尝试创建干净的 OOP 兼容类,这些类不需要这些拼凑来运行。
  • 在输入代码之前写下您的代码规范和计划。先整理一下思路。
  • 阅读 Swing Graphics。教程:here
  • 重写 JPanel 的 paintComponent(...) 方法,并确保在其中调用相同 super 方法。<
  • 避免使用空布局,因为它们会导致 GUI 脆弱,在大多数平台上看起来都很糟糕,并且很难调试、增强或更改。

关于java - 使用另一个类中的 jbutton 调用带有绘制和线程的 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22239023/

相关文章:

java - 如何从 Java 类中的函数访问主类对象?

java - 删除数据库中不存在的记录时无法捕获 org.hibernate.StaleObjectStateException

java - 合并两个正则表达式

java - GUI...为什么我的按钮不响应第一个 if 并且总是前往下一个选项

java - 如何将 int 数组作为单个 3 位输入读取?

java - 我的涉及 JFrame 的代码有什么问题

java - Android ObjectAnimator 与 ViewPropertyAnimator

java - 在 netbeans 8.2 中添加 Glassfish Server 5.0

java - 如何在 Swing 组件调整大小时出现 "do something"?

java - 除非满足条件,否则阻止从按钮组中的特定切换按钮进行切换