首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绘画JFrame难度

绘画JFrame难度
EN

Stack Overflow用户
提问于 2014-05-30 02:36:48
回答 2查看 40关注 0票数 2

在我的代码中,我试图用JFrame绘制,但它没有正确地绘制。我告诉框架画在我创建它的开始,但它是正常的灰色的颜色,一旦它被创建。我认为这可能与我正在重新油漆它的事实有关,如果是这样,我如何确保它被重新涂成黄色?有人能试着找出为什么我的代码没有绘制JFrame黄色吗?谢谢!

代码语言:javascript
复制
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);
        }


}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-30 02:40:58

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

票数 4
EN

Stack Overflow用户

发布于 2014-05-30 02:40:15

使BallPanel透明..。

代码语言:javascript
复制
bp.setOpaque(false);

不要在paintComponent方法中决定组件的状态,这些决策应该在您的actionPerformed方法中进行

绘画是为了绘画,paintComponent可能因为许多原因而被调用,许多原因你无法控制。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23946171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档