【问题标题】:Painting JFrame Difficulty绘画 JFrame 难度
【发布时间】:2014-07-19 17:11:20
【问题描述】:

在我的代码中,我试图通过JFrame 进行绘制,但绘制不正确。我告诉框架在我创建它的开始处绘制,但是一旦创建它它就是正常的灰色。我认为这可能与我正在重新粉刷它有关,如果是这样,我如何确保它被重新粉刷成黄色?有人可以尝试弄清楚为什么我的代码没有绘制JFrame Yellow 吗?谢谢!

public class EvolutionColor {

    public static void main(String args[]) {
        JFrame frame = new JFrame("Bouncing Ball");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        BallPanel bp = new BallPanel();
        frame.add(bp);
        frame.setSize(600, 600); // set frame size
        frame.setVisible(true); // display frame
        frame.setBackground(Color.YELLOW);
    }

    class BallPanel extends JPanel implements ActionListener {

        private int delay = 10;
        protected Timer timer;

        private int x = 0;        // x position
        private int y = 0;        // y position
        private int radius = 15;  // ball radius

        private int dx = 2;       // increment amount (x coord)
        private int dy = 2;       // increment amount (y coord)

        public BallPanel() {
            timer = new Timer(delay, this);
            timer.start();       // start the timer
        }

        public void actionPerformed(ActionEvent e) {
            repaint();
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g); // call superclass's paintComponent 
            g.setColor(Color.red);

// check for boundaries
            if (x < radius) {
                dx = Math.abs(dx);
            }
            if (x > getWidth() - radius) {
                dx = -Math.abs(dx);
            }
            if (y < radius) {
                dy = Math.abs(dy);
            }
            if (y > getHeight() - radius) {
                dy = -Math.abs(dy);
            }

// adjust ball position
            x += dx;
            y += dy;
            g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
        }


}

【问题讨论】:

  • 旁白:我将创建一个Ball 类来保存球对象的状态,并在Ball 类中拥有一个操作和绘制它的方法。如果您想要的不仅仅是一个球,这使得它更易于维护。请参阅示例here。也看看Initial Threads。 Swing 应用程序应该在 EDT 上运行

标签: java swing colors jpanel paintcomponent


【解决方案1】:

不要将 JFrame 设置为黄色,将 BallPanel 对象设置为黄色。

【讨论】:

  • @user3474775:很高兴它可以工作,但我非常同意 MadProgrammer ——您的 paintComponent 方法中不应包含程序逻辑,因为您无法完全控制何时甚至是否调用它。逻辑应该在 Timer 中,paintComponent 方法应该只用于绘画和绘画。
【解决方案2】:

使BallPanel透明...

bp.setOpaque(false);

不要在paintComponent 方法中对组件的状态做出决定,这些决定应该在actionPerformed 方法中做出

绘画是为了绘画,paintComponent 可能因多种原因而被调用,其中许多原因是您无法控制的

【讨论】:

    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 2018-12-04
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多