Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重新绘制传送我的图形,而不是平滑移动它_Java_Swing_Custom Painting - Fatal编程技术网

Java 重新绘制传送我的图形,而不是平滑移动它

Java 重新绘制传送我的图形,而不是平滑移动它,java,swing,custom-painting,Java,Swing,Custom Painting,因此,在我的代码中,当我按下其中一个W、A、S或D键时,我会按所需的方向重新绘制图形。图形不是从左到右或上下平滑移动,它只是不可见,有时再次可见,但如果我放开按下的键,它将始终可见。我在另一台计算机上创建了完全相同的程序,但这个问题没有出现,但在我的个人计算机上它总是存在 import com.sun.glass.events.KeyEvent; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Sh

因此,在我的代码中,当我按下其中一个W、A、S或D键时,我会按所需的方向重新绘制图形。图形不是从左到右或上下平滑移动,它只是不可见,有时再次可见,但如果我放开按下的键,它将始终可见。我在另一台计算机上创建了完全相同的程序,但这个问题没有出现,但在我的个人计算机上它总是存在

    import com.sun.glass.events.KeyEvent;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;

/**
 *
 * @author Admin
 */
public class mainFrame extends javax.swing.JFrame {
    public static int px,py,pwid,phei,ex,ey,ewid,ehei,speed,ppx,ppy;
    /**
     * Creates new form mainFrame
     */
    public mainFrame() {
        initComponents();
        px = 150;py = 150;pwid = 50;phei = 50;speed = 10000;

    }
    public void paint(Graphics g){
        super.paint(g);
        Graphics player = (Graphics)g;
        player.drawRect(px, py, pwid, phei);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void formKeyPressed(java.awt.event.KeyEvent evt) {                                
        int keycode = evt.getKeyCode();
        if(keycode == KeyEvent.VK_D){    
            repaint(px++*speed);
        }if(keycode == KeyEvent.VK_A){    
            repaint(px--*speed);
        }if(keycode == KeyEvent.VK_W){    
            repaint(py--*speed);
        }if(keycode == KeyEvent.VK_S){    
            repaint(py++*speed);
        }
        if(px >= 400-42 || px <= 0+42){
            px = px - 1;
        }else if(py >= 300-42 || py <= 0+42){
            System.out.println("You Cant go there");
        }
    }                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new mainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}
导入com.sun.glass.events.KeyEvent;
导入java.awt.Graphics;
导入java.awt.Rectangle;
导入java.awt.Shape;
/**
*
*@author-Admin
*/
公共类大型机扩展了javax.swing.JFrame{
公共静态int-px、py、pwid、phei、ex、ey、ewid、ehei、speed、ppx、ppy;
/**
*创建新表单大型机
*/
公共主机(){
初始化组件();
px=150;py=150;pwid=50;phei=50;速度=10000;
}
公共空间涂料(图g){
超级油漆(g);
图形播放器=(图形)g;
player.drawRect(px,py,pwid,phei);
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addKeyListener(新java.awt.event.KeyAdapter(){
按下public void键(java.awt.event.KeyEvent evt){
按下formKeyPressed(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,400,短。最大值)
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0,300,短。最大值)
);
包装();
}//                         
private void formKeyPressed(java.awt.event.KeyEvent evt){
int keycode=evt.getKeyCode();
如果(keycode==KeyEvent.VK_D){
重新喷漆(px++*速度);
}如果(keycode==KeyEvent.VK_A){
重新喷漆(px--*速度);
}如果(keycode==KeyEvent.VK_W){
重新喷漆(py--*速度);
}如果(keycode==KeyEvent.VK_S){
重新喷漆(py++*速度);
}

如果(px>=400-42 | | px=300-42 | | | py这并不是
重新绘制(int)
背后的真正想法,那么您应该有一个“游戏循环”,它更新游戏的当前状态并安排重新绘制

此外,您确实应该避免覆盖顶级容器的
paint
,因为正如您所发现的,它们不是双缓冲的,在更新时可能会导致闪烁。
JFrame
还包含一系列其他组件,由于绘制的工作方式,这些组件可以独立于容器进行绘制,这意味着他们可以找到你以前画过的东西

相反,从
JPanel
开始,覆盖其
paintComponent
方法并在其中执行自定义绘制,然后将此面板添加到
JFrame

您还应该避免使用
KeyListener
,原因有很多(焦点相关问题是主要原因),而是更喜欢使用获取您的“player”对象,并为其创建一个显式类player

例如:

class Player extends JComponent {
    //unique player fields here

    /**
     * Method to draw this particular component.
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // insert content of your paint method here
    }
}
当您想将播放器组件添加到JFrame时,请使用:

this.getContentPane().add(new Player());

MadProgrammer讲述了我想说的关于键盘输入和缺少游戏循环的事情。

好吧,鉴于我对Java的知识水平很低,我正试图理解如何制作一个简单的游戏。我现在做的是如何工作,还是必须完全重新启动并创建一个JPanel专注的程序。好吧,你可以花大量时间重新发明轮子并实现你自己的双缓冲解决方案,或者你可以使用API提供的可用功能,这取决于你。有关绘画工作原理的更多细节以及“游戏循环”的简单解决方案,请参阅和[执行自定义绘画]()我非常感谢您对我所做错事的帮助。我可能还有其他问题要问,但现在我将尝试实施您当前的建议。再次感谢您。因此,对于this.getContentPaint().add(new Player());它不运行我的Player类中的任何内容。这是因为我只是一个傻瓜还是其他什么。也很抱歉这么麻烦。请尝试在paintComponent()中调试方法。JFrame应该尝试绘制每个子组件,因此只要JFrame正在绘制其组件,就会调用Player的paintComponent方法。听MadProgrammer关于“游戏循环”所说的,您需要一些持续运行并绘制组件的东西