简体   繁体   English

Java Awt和Swing

[英]Java Awt & Swing

Pong.Java 傍爪哇

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Pong {
    private static final int WIDTH = 900, HEIGHT = 700;
    JFrame win = new JFrame();
    Paddle paddleOne = new Paddle(1);
    Paddle paddleTwo = new Paddle(2);
    Graphics g;

    Pong(){
        init();
    }

    void init(){
        win.setTitle("PONG");
        win.setSize(WIDTH, HEIGHT);
        win.addKeyListener(keyListener);
        win.setLocationRelativeTo(null);
        win.getContentPane().setBackground(Color.black);
        win.setVisible(true);
        win.getContentPane().validate();
        win.repaint();
    }


    public void paintComponent(Graphics g){
        g.setColor(Color.white);
        g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());

        System.out.println("drawn");
    }

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            switch(key){
            case 87:
                System.out.println("Player 1 Up");
                break;
            case 83:
                System.out.println("Player 1 Down");
                break;
            case 38:
                System.out.println("Player 2 Up");
                break;
            case 40:
                System.out.println("Player 2 Down");
                break;
            }

            win.getContentPane().validate();
            win.repaint();

        }

        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

    };

    public static void main(String[] args) {
        Pong p = new Pong();
    }
}

Paddle.Java 桨Java

public class Paddle{
private int WIDTH = 50, HEIGHT = 150, X, Y;


int playerNum;

Paddle(int playerNum){
    if(playerNum == 1){
        X = 10;
        Y = 10;
    }else if (playerNum == 2){
        X = 500;
        Y = 10;
    }
}

public void setX(int x){
    X = x;
}

public void setY(int y){
    Y = y;
}

public int getWIDTH() {
    return WIDTH;
}

public int getHEIGHT() {
    return HEIGHT;
}

public int getX() {
    return X;
}

public int getY() {
    return Y;
}

}

I'm relatively new to Java programming, or more specifically Awt & Swing, what my question is, why isn't my rectangle drawing? 我是Java编程的新手,更具体地说是Awt&Swing,我的问题是,为什么不绘制矩形图? Any help is appreciated. 任何帮助表示赞赏。 Thank you so much! 非常感谢!

You need to overriding paintComponents to draw. 您需要重写paintComponents进行绘制。 Here is your Pong.java 这是您的Pong.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Pong {
    private static final int WIDTH = 900, HEIGHT = 700;
    JFrame win = new JFrame();
    Paddle paddleOne = new Paddle(1);
    Paddle paddleTwo = new Paddle(2);
    Graphics g;

    Pong() {
        init();
    }

    void init() {
        win.setTitle("PONG");
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        win.setSize(WIDTH, HEIGHT);
        win.addKeyListener(keyListener);
        win.setLocationRelativeTo(null);
        win.add(new Panel(paddleOne));
        win.getContentPane().setBackground(Color.black);
        win.setVisible(true);
        win.getContentPane().validate();
        win.repaint();
    }

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            switch (key) {
            case 87:
                System.out.println("Player 1 Up");
                break;
            case 83:
                System.out.println("Player 1 Down");
                break;
            case 38:
                System.out.println("Player 2 Up");
                break;
            case 40:
                System.out.println("Player 2 Down");
                break;
            }

            win.getContentPane().validate();
            win.repaint();

        }

        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Pong();

            }
        });
    }
}

Here Panel.java in where paintComponent overridden. 这里的Panel.java中的paintComponent被覆盖。

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Panel extends JPanel{
    private Paddle paddleOne;
    public Panel(Paddle pdl) {
        paddleOne = pdl;
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.white);
        g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());

        //System.out.println("drawn");   //Should not put something here which may overhead.
    }

} 

In order for something to be painted within in Swing, it first must extend from something Swing know's how to paint, this commonly means a JComponent (or more typically a JPanel ). 为了在Swing中绘制某些内容,首先必须从Swing知道如何绘制的内容开始扩展,这通常意味着JComponent (或更常见的是JPanel )。

Then you can override one of the paint methods, which is called by the painting subsystem, in this case, it's generally preferred to override paintComponent , but don't forget to call super.paintComponent before you do any custom painting, or you're setting yourself up for some weird and generally unpredictable painting issues. 然后,您可以覆盖绘画子系统调用的绘画方法之一,在这种情况下,通常首选重写paintComponent ,但不要忘记在进行任何自定义绘画之前调用super.paintComponent ,否则为一些怪异且通常无法预测的绘画问题做好准备。

Take a look at Painting in AWT and Swing and Performing Custom Painting for more details. 有关更多详细信息,请参阅AWT中的绘画以及“摇摆执行自定义绘画 ”。

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Pongo {

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

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

    public class PongPane extends JPanel {

        private static final int WIDTH = 900, HEIGHT = 700;
        Paddle paddleOne = new Paddle(1);
        Paddle paddleTwo = new Paddle(2);

        public PongPane() {
            setBackground(Color.BLACK);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.white);
            g.fillRect(paddleOne.getX(), paddleOne.getY(), paddleOne.getHEIGHT(), paddleOne.getWIDTH());

            //System.out.println("drawn");   //Should not put something here which may overhead.
        }

    }

    public class Paddle {

        private int WIDTH = 50, HEIGHT = 150, X, Y;

        int playerNum;

        Paddle(int playerNum) {
            if (playerNum == 1) {
                X = 10;
                Y = 10;
            } else if (playerNum == 2) {
                X = 500;
                Y = 10;
            }
        }

        public void setX(int x) {
            X = x;
        }

        public void setY(int y) {
            Y = y;
        }

        public int getWIDTH() {
            return WIDTH;
        }

        public int getHEIGHT() {
            return HEIGHT;
        }

        public int getX() {
            return X;
        }

        public int getY() {
            return Y;
        }
    }
}

I would also discourage the use of KeyListener within this context and inside advice the use of the key bindings API, it doesn't suffer from the same focus related issues that KeyListener does. 我还将不鼓励在此上下文中使用KeyListener ,并且建议不要使用键绑定API,因为它不会像KeyListener那样受到与焦点相关的问题的困扰。 See How to Use Key Bindings for more details 有关更多详细信息,请参见如何使用键绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM