Java图形未在OS X中显示 [英] Java Graphics Not Displaying In OS X

查看:40
本文介绍了Java图形未在OS X中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名计算机科学专业的学生,​​使用的是2009年中期运行OS X Yosemite 10.10.3的MacBook Pro.最近,我在面向对象的编程课程中进行了一个课堂活动,我们逐步创建了一个交互式Java程序,用户只需单击一个足球,然后观看它被踢到绿色背景的球门柱上,便会逐步进行.

I'm a Computer Science student who uses a mid-2009 MacBook Pro running OS X Yosemite 10.10.3. I recently had a class activity in my Object-Oriented programming class where we went step-by-step in creating an interactive Java program in which the user simply clicks a football and watch it get kicked over the goalpost with a green background.

但是,即使我的Java代码与同学的Windows计算机的代码完全匹配,也没有语法错误,但是在程序正常运行的同时,我的程序仍存在一些问题:

However, even though my Java code matched the code of my classmates' Windows computers with no syntax errors, there are some problems with my program properly running while theirs work perfectly fine:

使用标题和绿色背景打开应用程序窗口时,足球和球门柱均不显示.但是,如果我手动拉伸窗口,它们会重新显示.我尝试更改窗口尺寸以查看是否导致其无效.

While the window for the application opens with the title and green background, neither the football nor goalpost is displayed. However, if I manually stretch the window, they show back up. I've tried changing the window dimensions to see if that was causing it to no avail.

单击足球时,足球和球门柱都消失了并且没有返回,而不是按照预期的方向移向球门柱.即使我再次尝试手动拉伸窗口,也只会显示绿色背景.

When the football is clicked, instead of moving towards the goalpost as intended, both the football and goalpost vanish and don't return. Only the green background is displayed, even when I try manually stretching the window again.

我仍将代码提交给我的讲师,该讲师在他的计算机上工作正常(他也不理解问题,因为他不使用OS X).我试图在其他两个IDE上运行代码,以查看Eclipse是否是问题所在,但它们均产生了相同的结果.如果这是OS X或计算机专有的问题,我该如何解决?

I still submitted the code to my instructor, which worked fine on his computer (he doesn't understand the problem either since he doesn't use OS X). I tried to run the code on two other IDE's to see if Eclipse was the problem, but they all produced the same results. If this is an OS X or computer-exclusive problem, how am I able to get around this?

这是我当前的代码:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;


public class Football extends JFrame {

   final int WINDOW_WIDTH = 800;
   final int WINDOW_HEIGHT = 400;

   private int x = 40;                // Ball's X coordinate
   private int y = 300;               // Ball's Y coordinate
   private final int WIDTH = 35;      // Ball's width
   private final int HEIGHT = 60;     // Ball's height

   private final int X_MOVE = 14;     // Pixels to move ball
   private final int Y_MOVE = 4;

   private final int TIME_DELAY = 25; // Time delay
   private Timer timer;               // Timer object

   /**
      init method
   */

   public Football() {
       setTitle("Football");
       setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);

       // Set Background to a Dark Green
       getContentPane().setBackground(new Color(0, 220, 50));         

       // initTimer();
       addMouseListener(new FbMouseListener());
   }

   public void paint(Graphics g)
   {
      // Call the superclass paint method.
      super.paint(g);  
      // Set the color to Brown
      g.setColor(new Color(129, 74, 25));

      // Draw the football
      g.fillOval(x, y, WIDTH, HEIGHT);

      // Draw the Goalpost
      g.setColor(Color.YELLOW);
      g.fillRect(670, 240, 5, 140);
      g.fillRect(610, 80, 5, 140);
      g.fillRect(740, 120, 5, 140);
      // Need Thicker line
      Graphics2D g2 = (Graphics2D) g;
      g2.setStroke(new BasicStroke(5));
      g2.drawLine(612, 220, 742, 260);
   }

   private class TimerListener implements ActionListener
   {
       public void actionPerformed(ActionEvent e) {
        // Update the ball's position
        y -= Y_MOVE;
        x += X_MOVE;

        // Force a call to the paint method
        repaint();  
    }

   }

   public void initTimer()
   {
       timer = new Timer(TIME_DELAY, new TimerListener());
       timer.start();
   }

   private class FbMouseListener implements MouseListener
   {
       public void mouseClicked(MouseEvent e)
       {
           if (e.getX() >= x && e.getX() <= (x + WIDTH) && e.getY() >= y && e.getY() <= (y + HEIGHT))
           {
               initTimer();
           }
       }

       public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

       }

       public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

       }

       public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

       }

       public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

       }
   }

   public static void main(String[] args)
   {
        Football fb = new Football();
   }

}

任何帮助或建议都将不胜感激,因为我想确保这不会影响我将来创建的任何程序.

Any help or suggestions would be appreciated, as I would like to make sure this doesn't affect any future programs I create.

推荐答案

通常,覆盖诸如 JFrame 之类的顶级容器的 paint 是一个坏主意,JFrame 包含一堆子组件,这些子组件可以独立于父组件进行绘制,在这里似乎是这种情况

Generally, overriding paint of a top level container like JFrame is a bad idea, JFrame contains a bunch of child components that can be painted independently of the parent, which seems to be the case here

如您所见,框架和用户之间至少还有3个其他组件

As you can see, there are (at least) 3 other components in between the frame and the user

通常,您应该创建一个自定义类,该类继承自 JPanel 之类的内容,并覆盖它的 paintComponent 并在那里进行自定义绘制.

Generally, you should create a custom class which extends from something like JPanel and override it's paintComponent and perform your custom painting there.

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Football {

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

    public Football() {
        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("Football");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new FootballPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class FootballPane extends JPanel {

        public static final int WINDOW_WIDTH = 800;
        public static final int WINDOW_HEIGHT = 400;

        private int x = 40;                // Ball's X coordinate
        private int y = 300;               // Ball's Y coordinate
        private static final int WIDTH = 35;      // Ball's width
        private static final int HEIGHT = 60;     // Ball's height

        private static final int X_MOVE = 14;     // Pixels to move ball
        private static final int Y_MOVE = 4;

        private static  final int TIME_DELAY = 25; // Time delay
        private Timer timer;               // Timer object

        /**
         * init method
         */
        public FootballPane() {

            // Set Background to a Dark Green
            setBackground(new Color(0, 220, 50));

            // initTimer();
            addMouseListener(new FbMouseListener());

        }

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

        @Override
        protected void paintComponent(Graphics g) {
            // Call the superclass paint method.
            super.paintComponent(g); 

            // Set the color to Brown
            g.setColor(new Color(129, 74, 25));

            // Draw the football
            g.fillOval(x, y, WIDTH, HEIGHT);

            // Draw the Goalpost
            g.setColor(Color.YELLOW);
            g.fillRect(670, 240, 5, 140);
            g.fillRect(610, 80, 5, 140);
            g.fillRect(740, 120, 5, 140);
            // Need Thicker line
            Graphics2D g2 = (Graphics2D) g;
            g2.setStroke(new BasicStroke(5));
            g2.drawLine(612, 220, 742, 260);
        }

        private class TimerListener implements ActionListener {

            public void actionPerformed(ActionEvent e) {
                // Update the ball's position
                y -= Y_MOVE;
                x += X_MOVE;

                // Force a call to the paint method
                repaint();
            }

        }

        public void initTimer() {
            timer = new Timer(TIME_DELAY, new TimerListener());
            timer.start();
        }

        private class FbMouseListener implements MouseListener {

            public void mouseClicked(MouseEvent e) {
                if (e.getX() >= x && e.getX() <= (x + WIDTH) && e.getY() >= y && e.getY() <= (y + HEIGHT)) {
                    initTimer();
                }
            }

            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }
        }

    }

}

请参见 AWT和Swing中的绘画执行自定义绘画以获取更多详细信息

See Painting in AWT and Swing and Performing Custom Painting for more details

这篇关于Java图形未在OS X中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆