java - JFrame 重绘();错误

标签 java swing compiler-errors jframe repaint

所以,我目前正在制作一个根据键盘命令移动的球。我的问题是,当我调用 repaint(); 时,它给我一个错误,指出它“无法从类型 Component 对非静态方法 repaint() 进行静态引用”。我做错了什么?

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

public class App extends JFrame{

    JFrame f = new JFrame();
    public static int keyVal = 0, x = 10, y = 10;
    public static void main(String[] args) {
        new App();   
        Ball();
        while(true){
        System.out.println(keyVal);
        try{
            Thread.sleep(50);
        }
        catch(Exception e){}

        }
    }

    public static void Ball(){
        while(true){
            if(keyVal == 65){
            x = x -1;
            }
            else if(keyVal == 68){
            x = x + 1;
            }
        repaint();
        //repaint(x, y, 10, 20);
        }
    }

    public App(){
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setTitle("Pong");
        f.setSize(30,40);

        f.setLocationRelativeTo(null);

        f.addKeyListener(new KeyListener(){
            public void keyPressed(KeyEvent e){
                keyVal = e.getKeyCode();
            }

            public void keyReleased(KeyEvent e){
                keyVal = 0;
            }

            public void keyTyped(KeyEvent e){}
        });
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
    }

    class MyPanel extends JPanel {
        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
        }

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

        public void paintComponent(Graphics g) {
            super.paintComponent(g);       
            System.out.println("test");
            g.setColor(Color.orange);
            g.fillRect(x, y, 10, 20);
        }  
    }    
}

最佳答案

  1. 您的类已经是 JFrame 子类。无需创建另一个 JFrame。取出JFrame f = new JFrame(),所有f.method(..)只需使用method(..)

  2. 不要使用while(true)Thread.sleep()。你会遇到问题。相反,请查看 How to use a Swing Timer 。这是一个简单的example 。您还可以通过简单的 google 搜索找到许多其他示例,了解如何使用 Swing Timer

  3. 无需为框架setSize(),您已经pack()它了。

  4. 您应该查看 How to use Key Bindings 。如果不是现在,您会发现使用 KeyListener 存在焦点问题等。

  5. Event Dispatch Thead 运行您的程序,像这样

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                new App();
            }
        });
    }
    
<小时/>

免费赠品

javax.swing.Timer 的简单实现如下所示

public App() {
    ...
    Timer timer = new Timer(50, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // do something
        }
    });
}

这是计时器的基本构造

Timer( int dalay, ActionListener listener )

延迟是每次触发事件时延迟的毫秒数。所以在上面的代码中,每 50 毫秒就会发生一些事情。这将实现您尝试使用 Thread.sleep 执行的操作。您可以从 actionPerformed

内部调用 repaint() <小时/>

这是代码的简单重构,您可以测试一下

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class App extends JFrame {

    private MyPanel panel = new MyPanel();
    public static int keyVal = 0, x = 10, y = 10;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new App();
            }
        });
    }

    public App() {
        Timer timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                    x = x + 5;

                panel.repaint();
            }
        });
        timer.start();

        add(panel);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Pong");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    class MyPanel extends JPanel {

        public MyPanel() {
            setBorder(BorderFactory.createLineBorder(Color.black));
        }

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

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            System.out.println("test");
            g.setColor(Color.orange);
            g.fillRect(x, y, 10, 20);
        }
    }
}

关于java - JFrame 重绘();错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340018/

相关文章:

java - javax.swing.plaf.synth.SynthContext.getPainter 处的 NullPointerException

java - 防止 FlowLayout 垂直居中

ios - objective c 隐式转换丢失整数精度 'NSUInteger'

compiler-errors - 此文件不属于任何项目 在 clion 中打开项目时代码洞察可能无法正常工作

compiler-errors - Fortran问题: Argument of “xx” is one type at (2) but is some other type at (1)

java - Android Studio -- 无法应用插件 [id 'appengine']

在 Mac OS X 10.5.8 上安装 Java 6 后,Java 版本显示为 1.5

java - 通过JOptionPane输入一个有字符限制的字符串

java - JFreeChart DialPlot 减少标题差距

java - 如何在 Java Swing 中创建二维 SplitPane