1

这一直让我发疯。我无法让这个矩形出现。我是编程新手,我正在尝试在 2D 中重新创建乒乓球作为一种学习体验。这是代码:

package ping;
import javax.swing.*;

public class Pong extends JFrame implements MouseListener {

/**
 * 
 */
private static final long serialVersionUID = 1L;
/**
 * @param args
 */
public Pong(String title) {
    this.setTitle(title);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.getContentPane().setBackground(Color.RED);
    this.getContentPane().setLayout(null);
    this.setSize(500, 500);
    Paddles a = new Paddles(), b = new Paddles();
    a.setBounds(225, 25, 50, 10); b.setBounds(225, 475, 50, 10);
    this.getContentPane().add(a); this.getContentPane().add(b);
    a.setVisible(true); b.setVisible(true);
    this.getContentPane().addMouseListener(this);
    this.setVisible(true);
}
public static void main(String[] args) {
    // TODO Auto-generated method stub
        Pong game = new Pong("Java Pong");}

然后是桨类:

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;
public class Paddles extends JComponent {

/**
 * 
 */
private static final long serialVersionUID = 1L;
public Paddles() {}
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.drawRect(0,0,0,0);
    g.fillRect(0,0,0,0);
    System.out.println("paintworks");
    System.out.println(Integer.toString(this.getY()));
}

}

提前致谢!

4

2 回答 2

4

你有一个零大小的矩形

这是更新的方法。

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLACK);
    g.drawRect(this.x,this.y,10,10);   // look at the api this command is redundant
    g.fillRect(this.x,this.y,10,10);   // as fill rect will overdraw it anyway.
    System.out.println("paintworks");
    System.out.println(Integer.toString(this.getY()));
}
于 2013-06-12T00:31:21.683 回答
1
g.drawRect(0,0,0,0);
g.fillRect(0,0,0,0);

这两条线都表示要绘制没有大小的东西。最后两个参数应指示宽度和高度。

有关更多详细信息,请参阅javadoc

于 2013-06-12T00:18:35.700 回答