JFrame背景图像不会工作

时间:2014-01-24 03:25:31

标签: java swing jframe draw shape

我已经尝试了一切来获取背​​景图像,它或者只是一个灰色背景,或者显示没有播放器的图像,或者没有图像的播放器。出于某种原因,我无法画出背景?任何帮助将不胜感激!谢谢!

package main;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class grow extends JPanel implements ActionListener, KeyListener{
double x = 0, y = 0, velx = 0, vely = 0;
Timer t = new Timer(5, this);

public grow(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}

public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 g2d.setRenderingHint(RenderingHints.KEY_RENDERING,      RenderingHints.VALUE_RENDER_QUALITY);
g2d.setPaint(Color.blue);
g2d.fill(new Ellipse2D.Double(x, y, 70, 70));


}

public void actionPerformed(ActionEvent e) {
repaint();
x += velx;
y += vely;

}

public void up(){
vely = -2;
velx = 0;
}
public void down(){
vely = 2;
velx = 0;
}
public void left(){
vely = 0;
velx = -2;
}

public void right(){
vely = 0;
velx = 2;
} 




 public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP){
    up();
}
if(code == KeyEvent.VK_DOWN){
    down();
}

if(code == KeyEvent.VK_RIGHT){
    right();
}

if(code == KeyEvent.VK_LEFT){
    left();
}

}
public void stop(){
velx = 0;
vely = 0;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP){
    stop();
}
if(code == KeyEvent.VK_DOWN){
    stop();
}

if(code == KeyEvent.VK_RIGHT){
    stop();
}

if(code == KeyEvent.VK_LEFT){
    stop(); 
    }

}

public void keyTyped(KeyEvent e) {

}

}

这是我的类,它显示了jframe:

package main;

import java.awt.Color;
import java.awt.Component;

import javax.swing.JFrame;

public class playerandframe{

static grow g = new grow();
public static void main(String args[]){
    JFrame j = new JFrame("|The Wizards Of Lleon|");
    j.add(g);
    j.setSize(600,600);
    j.setVisible(true);
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

1 个答案:

答案 0 :(得分:1)

  1. 使用key bindings代替KeyListener,因为您可能遇到KeyListener的焦点问题。键绑定更适合使用Swing应用程序的键事件。您可以看到示例here
  2. 只需在同一paintComponent方法中绘制背景图像。我目前只看到其中一件事正在被绘制。
  3. 使用正确的java命名约定。班级名称应使用大写字母。
  4. @Override getPreferredSize()班级JPanelgrow)而不是设置框架的尺寸,而是使用frame.pack()代替frame.setSize()。包装框架将遵循您给面板的首选尺寸

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(600, 600);
    }
    
    .... and 
    frame.pack(); // in the main