Java JFrame的大小并不完整

时间:2013-02-28 22:38:43

标签: java swing concurrency jframe paint

我正在尝试编写游戏,但我无法完全按照我需要的大窗口进行编程。 第一个println给我720和第二个732,窗口真的比720大。 如何让游戏显示高720像素呢?

xCopterGame.java

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

public class xCopterGame extends JFrame implements MouseListener{

  private static final long serialVersionUID = 1L;

  Board panel=null;
  public xCopterGame(){
    panel = new Board();
    setTitle("Pong");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    panel.setPreferredSize(new Dimension(1280,720));
    getContentPane().add(panel);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
    setResizable(false);

    System.out.println(panel.getHeight());

    panel.yCopter = getHeight()/2-15;

    panel.addMouseListener(this);
    addMouseListener(this);
  }

  public void mousePressed(MouseEvent e) {
    panel.mousePressed(e);
  }

  public void mouseReleased(MouseEvent e) {
    panel.mouseReleased(e);
  }

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


  public void mouseClicked(MouseEvent e) {

  }
  public void mouseEntered(MouseEvent e) {

  }
  public void mouseExited(MouseEvent e) {

  }
}

Board.java

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

public class Board extends JPanel implements Runnable{
  private static final long serialVersionUID = 1L;

  Thread th=null;
  boolean mousePressed = false, firstClick = false;
  int yCopter;

  public Board(){
    th = new Thread(this);
    th.start();
  }

  public void paint(Graphics g){
    super.paint(g);
    this.setBackground(Color.black);
    g.setColor(Color.white);
    g.fillRect(80, yCopter, 30, 30);

    g.setColor(Color.gray);
    for(int i=0; i<37; i++){
      g.drawLine(0, i*20, this.getWidth(), i*20);
    }

    g.fillRect(100, 715, 30, 5);
    g.fillRect(100, 0, 30, 5);       
    System.out.println(this.getHeight());
  }

  public void run() {
    while(true){
      if(mousePressed == true)
        yCopter--;
      if(mousePressed == false && firstClick == true)
        yCopter++;

   //   repaint();

      try { 
        Thread.sleep(10); 
      } 
      catch(InterruptedException ex) {

      }
    }
  }

  public void mousePressed(MouseEvent e) {
    mousePressed = true;
    firstClick = true;
  }
  public void mouseReleased(MouseEvent e) {
    mousePressed = false;
  }
}

2 个答案:

答案 0 :(得分:3)

setResizable()可能会影响框架的插图。最好在setResizable()之后调用pack()。试试这个电话订单:

setResizable(false);
pack();
setVisible(true);

供参考,请参阅@HovercraftFullOfEels的this分析

您可能还会发现Should I avoid the use of set[Preferred|Maximum|Minimum]Size methods in Java Swing?有帮助。

答案 1 :(得分:0)

我注意到你只是设置Board首选大小。如果您想为窗口强制使用特定尺寸,只需拨打JFrame.setSize()的{​​{1}}方法即可。

我鼓励你去看看link。当您使用xCopterGame时,还有其他方法可以实现Swing UI而无需处理此类问题。