Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.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_Jframe_Repaint - Fatal编程技术网

Java 如何使重绘变慢?

Java 如何使重绘变慢?,java,swing,jframe,repaint,Java,Swing,Jframe,Repaint,我正在制作一个Java应用程序,我想知道是否有办法让jframe上的重绘速度变慢。让我详细说明一下,该应用程序有一个jframe,并调用另一个jframe来显示一个图形,该图形必须从一侧移动到另一侧,但它的速度可以让您实际看到移动 编辑* 为了让自己清楚,我添加了一段代码 import javax.swing.JFrame; import javax.swing.JLabel; public class NewJFrame extends javax.swing.JFrame {

我正在制作一个Java应用程序,我想知道是否有办法让jframe上的重绘速度变慢。让我详细说明一下,该应用程序有一个jframe,并调用另一个jframe来显示一个图形,该图形必须从一侧移动到另一侧,但它的速度可以让您实际看到移动

编辑* 为了让自己清楚,我添加了一段代码

import javax.swing.JFrame;
import javax.swing.JLabel;


public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * 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() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(152, 152, 152)
                .addComponent(jButton1)
                .addContainerGap(191, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(63, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        String position="";
        JFrame frame1=new JFrame();
        JLabel label1=new JLabel();
        label1.setText("Hello!");
        frame1.add(label1);
        frame1.setSize(400,300);
        frame1.setVisible(true);
        for(int i=1;i<20;i++){
            label1.setLocation(i, i);
            frame1.repaint();
            position+="The label is at position: "+label1.getLocation()+"\n";
            jTextArea1.setText(position);
        }
    }

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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() {
               NewJFrame frame= new NewJFrame();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}
import javax.swing.JFrame;
导入javax.swing.JLabel;
公共类NewJFrame扩展了javax.swing.JFrame{
/**
*创建新表单NewJFrame
*/
公共NewJFrame(){
初始化组件();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
// 
私有组件(){
jButton1=newjavax.swing.JButton();
jScrollPane1=newjavax.swing.JScrollPane();
jTextArea1=newjavax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText(“开始”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
jTextArea1.设置列(20);
jTextArea1.设置行(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(152152152)
.addComponent(jButton1)
.addContainerGap(191,简称最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47,47,47)
.addComponent(jButton1)
.addGap(18,18,18)
.addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED\u SIZE,149,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(63,简称最大值))
);
包装();
}// 
私有void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
字符串位置=”;
JFrame frame1=新JFrame();
JLabel label1=新的JLabel();
标签1.setText(“你好!”);
框架1.添加(标签1);
框架1.设置尺寸(400300);
frame1.setVisible(true);
对于(int i=1;i
  • 应严格禁止EDT上的睡眠
  • 如果你想使用
    睡眠
    ,你应该直接考虑摆动计时器
  • 现在,如果你想看一个如何轻松改变移动元件速度的例子,你不需要改变摆动计时器的频率,但实际上要改变移动元件的速度。50Hz的频率通常对人来说就足够了

    下面是一个小的演示代码:

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSlider;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    public class TestAnimation2 {
    
        private static final int NB_OF_IMAGES_PER_SECOND = 50;
        private static final int WIDTH = 800;
        private static final int HEIGHT = 600;
    
        private static final int MIN = 0;
        private static final int MAX = 100;
    
        private double speed = convert(50);
    
        private double dx;
        private double dy;
    
        private double x = WIDTH / 2;
        private double y = HEIGHT / 2;
    
        private JFrame frame;
        private CirclePanel circle;
        private Runnable job;
    
        private long lastMove = System.currentTimeMillis();
    
        protected void initUI() throws MalformedURLException {
            frame = new JFrame(TestAnimation2.class.getSimpleName());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(null);
            circle = new CirclePanel();
            circle.setSize(20, 20);
            frame.add(circle);
            frame.setSize(WIDTH, HEIGHT);
            dx = speed;
            dy = speed;
            final JSlider slider = new JSlider(MIN, MAX);
            slider.addChangeListener(new ChangeListener() {
    
                @Override
                public void stateChanged(ChangeEvent e) {
                    speed = convert(slider.getValue());
                    if (dx > 0) {
                        dx = speed;
                    } else {
                        dx = -speed;
                    }
                    if (dy > 0) {
                        dy = speed;
                    } else {
                        dy = -speed;
                    }
    
                }
            });
            slider.setValue(50);
            slider.setLocation(0, 0);
            slider.setSize(slider.getPreferredSize());
            frame.add(slider);
            frame.setVisible(true);
            Timer t = new Timer(1000 / NB_OF_IMAGES_PER_SECOND, new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    move();
                }
            });
            t.start();
        }
    
        protected double convert(double sliderValue) {
            return sliderValue + 1;
        }
    
        protected void move() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    x += dx;
                    y += dy;
                    if (x + circle.getWidth() > frame.getContentPane().getWidth()) {
                        x = frame.getContentPane().getWidth() - circle.getWidth();
                        dx = -speed;
                    } else if (x < 0) {
                        x = 0;
                        dx = speed;
                    }
                    if (y + circle.getHeight() > frame.getContentPane().getHeight()) {
                        y = frame.getContentPane().getHeight() - circle.getHeight();
                        dy = -speed;
                    } else if (y < 0) {
                        y = 0;
                        dy = speed;
                    }
                    circle.setLocation((int) x, (int) y);
                    circle.repaint();
                }
            });
        }
    
        public static class CirclePanel extends JPanel {
    
            public CirclePanel() {
                super();
                setOpaque(false);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.RED);
                g.fillOval(0, 0, getWidth(), getHeight());
            }
        }
    
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
                UnsupportedLookAndFeelException {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        new TestAnimation2().initUI();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    
    导入java.awt.Color;
    导入java.awt.Graphics;
    导入java.awt.event.ActionEvent;
    导入java.awt.event.ActionListener;
    导入java.net.MalformedURLException;
    导入javax.swing.JFrame;
    导入javax.swing.JPanel;
    导入javax.swing.JSlider;
    导入javax.swing.SwingUtilities;
    导入javax.swing.Timer;
    导入javax.swing.UnsupportedLookAndFeelException;
    导入javax.swing.event.ChangeEvent;
    导入javax.swing.event.ChangeListener;
    公共类测试2{
    每秒图像的私有静态最终int NB_=50;
    专用静态最终整数宽度=800;
    专用静态最终内部高度=600;
    私有静态最终int MIN=0;
    专用静态最终整数最大值=100;
    专用双速=转换(50);
    私人双dx;
    私人双重身份;
    专用双x=宽度/2;
    私人双y=高度/2;
    私有JFrame;
    专用电路板电路;
    私人经营性工作;
    private long lastMove=System.currentTimeMillis();
    受保护的void initUI()引发错误的FormedUrlexception{
    frame=newjframe(TestAnimation2.class.getSimpleName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(空);
    圆圈=新的圆圈面板();
    圆形。设置尺寸(20,20);
    框架。添加(圆圈);
    框架尺寸(宽度、高度);
    dx=速度;
    dy=速度;
    最终JSlider滑块=新JSlider(最小、最大);
    slider.addChangeListener(新的ChangeListener(){
    @凌驾
    公共无效状态已更改(更改事件e){
    速度=转换(slider.getValue());
    如果(dx>0){
    dx=速度;
    }否则{
    dx=速度;
    }
    如果(dy>0){
    dy=速度;
    }否则{
    dy=速度;
    }
    }
    });
    滑块设置值(50);
    滑块。设置位置(0,0);
    slider.setSize(slider.getPreferredSize());
    frame.add(滑块);
    frame.setVisible(true);
    定时器t=新定时器(每秒1000个/NB\u个图像,新ActionListener(){
    @凌驾
    已执行的公共无效操作(操作事件e){
    move();
    }
    });
    t、 start();
    }
    受保护的双转换(双滑动值){
    返回sliderValue+1;
    }
    受保护的无效移动(){
    SwingUtilities.invokeLater(新的Runnable(){
    @凌驾
    公开募捐{
    x+=dx;