Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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程序中的Swing线程与计时器_Java_Multithreading_Swing_Timer - Fatal编程技术网

我的Java程序中的Swing线程与计时器

我的Java程序中的Swing线程与计时器,java,multithreading,swing,timer,Java,Multithreading,Swing,Timer,我正在寻找一些指导来完成我的项目计划。这是一个简单的模拟,在运行时绘制多个图形对象,并使用按钮将另一个球添加到jpanel,就在两天前,我不得不重写我的整个代码以同时接收多个对象,昨晚我做了一些研究,发现了一个异常…更改了一些代码,然后在线程AWT EventQueue 0中又出现了一个异常,在做了更多的研究之后,许多人认为在运行时用线程在jpanel上动态绘制对象是一件痛苦的事情。。。。我应该用定时器来代替,这就是我现在的位置。网格包约束暂时可以忽略,因为它只是在此时进行布局。 我的问题是,我

我正在寻找一些指导来完成我的项目计划。这是一个简单的模拟,在运行时绘制多个图形对象,并使用按钮将另一个球添加到jpanel,就在两天前,我不得不重写我的整个代码以同时接收多个对象,昨晚我做了一些研究,发现了一个异常…更改了一些代码,然后在线程AWT EventQueue 0中又出现了一个异常,在做了更多的研究之后,许多人认为在运行时用线程在jpanel上动态绘制对象是一件痛苦的事情。。。。我应该用定时器来代替,这就是我现在的位置。网格包约束暂时可以忽略,因为它只是在此时进行布局。 我的问题是,我如何才能在运行时按一个按钮添加一个新球……对不起,忘了提一下

Ps yeh我已经试过验证JPanel了:/

感谢所有指导:)

Sim
=============
导入java.awt.*;
导入java.awt.event.*;
导入java.util.ArrayList;
导入java.util.Random;
导入javax.swing.*;
公共类Sim扩展JPanel
私有静态最终整数更新率=60;//每秒刷新的次数
公共静态整数X=640;
公共静态int Y=480;
公共静态int numberOfBall=3;
公共静态布尔值isRunning=true;
公共Sim卡(){
//这里有一些代码都被注释掉了
}
公共静态void main(字符串[]args){
//在事件调度程序线程(EDT)而不是主线程中运行GUI。
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
//设置主窗口(使用Swing的框架)
JFrame=新JFrame(“模拟”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(新的GridBagLayout());
GridBagConstraints c=新的GridBagConstraints();
c、 网格宽度=3;
c、 网格高度=3;
球=新球();
帧。添加(球);
gui=新gui();
frame.add(GUI);
frame.setPreferredSize(新尺寸(1280720));
frame.setresizeable(false);
//frame.setContentPane(新Sim());
frame.pack();
frame.setVisible(true);
新螺纹(新弹跳发动机(球)).start();
}
});
}
公共静态int随机(int最大范围){
返回(int)Math.round((Math.random()*maxRange));
}
@凌驾
公共组件(图形g){
超级组件(g);
使无效();
重新油漆();
}
桂
---------
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
公共类gui扩展了JPanel{
布尔型应填充;
公共图形用户界面(){
setLayout(新的GridBagLayout());
GridBagConstraints c=新的GridBagConstraints();
如果(应填写){
c、 填充=GridBagConstraints.HORIZONTAL;
}
AbstractButton addBallButton=新JButton(“添加球”);
addBallButton.SetMultiClickThreshold(1500);
addBallButton.addActionListener(新的ActionListener(){
@凌驾
已执行的公共无效操作(ActionEvent ActionEvent){
添加(新球((新颜色(模拟随机(255)、模拟随机(255)、模拟随机(255))、20));
for(Ball-Ball:balls.listball){
系统输出打印(“我工作”);
}
使无效();
//重新油漆();
}
});
c、 填充=GridBagConstraints.HORIZONTAL;
c、 权重x=1;
c、 权重y=0.5;
添加(添加按钮);
弹跳发动机
------------------
导入java.awt.*;
导入javax.swing.*;
公共类bounceEngine实现Runnable{
私人舞会家长;
私有整数更新率=144;
公共弹跳引擎(母球){
this.parent=parent;
}
公开募捐{
int width=Sim.X;
内部高度=模拟Y;
//随机化起始位置。。。
对于(球:getParent().getBalls()){
int x=模拟随机(宽度);
int y=模拟随机(高度);
int size=ball.getRadius();
如果(x+尺寸>宽度){
x=宽度-尺寸;
}
如果(y+尺寸>高度){
y=高度-尺寸;
}
球。设定位置(新点(x,y));
}
while(getParent().isVisible()){
//重新粉刷圆珠笔。。。
invokeLater(新的Runnable(){
@凌驾
公开募捐{
getParent().repaint();
}
});
//我知道在调用repaint方法时更新它是危险的
对于(球:getParent().getBalls())
   Sim
=============
        import java.awt.*;
        import java.awt.event.*;
        import java.util.ArrayList;
        import java.util.Random;

        import javax.swing.*;


        public class Sim extends JPanel 

            private static final int UPDATE_RATE = 60; // Number of refresh per second



            public static int X = 640;
            public static int Y = 480;

            public static int numberOfBall = 3;

            public static boolean isRunning = true;


            public Sim() {
              // have some code here all commented out
            }



            public static void main(String[] args) {

                // Run GUI in the Event Dispatcher Thread (EDT) instead of main thread.

                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        // Set up main window (using Swing's Frame)
                        JFrame frame = new JFrame("Simulation");
                        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        frame.setLayout(new GridBagLayout());
                        GridBagConstraints c = new GridBagConstraints();
                        c.gridwidth = 3;
                        c.gridheight = 3;
                        balls balls = new balls();
                        frame.add(balls);
                        gui GUI = new gui();
                        frame.add(GUI);
                        frame.setPreferredSize(new Dimension(1280,720));
                        frame.setResizable(false);
                        //frame.setContentPane(new Sim());
                        frame.pack();
                        frame.setVisible(true);

                        new Thread(new bounceEngine(balls)).start();

                    }
                });
            }

            public static int random(int maxRange) {
                return (int) Math.round((Math.random() * maxRange));
             }





            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                invalidate();
                repaint();

            }



        gui
---------

        import javax.swing.*;
        import java.awt.*;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;


        public class gui extends JPanel {
            boolean shouldFill;
            public gui(){

            setLayout(new GridBagLayout());
            GridBagConstraints c = new GridBagConstraints();
            if(shouldFill){
                c.fill = GridBagConstraints.HORIZONTAL;
                }

                AbstractButton addBallButton = new JButton("Add Ball");
                addBallButton.setMultiClickThreshhold(1500);

                addBallButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        balls.listBalls.add(new Ball((new    Color(Sim.random(255),Sim.random(255), Sim.random(255))),20));
                        for(Ball ball : balls.listBalls){
                            System.out.print("I work ");
                        }
                        invalidate();
                        //repaint();
                    }
                });
                c.fill = GridBagConstraints.HORIZONTAL;
                c.weightx = 1;
                c.weighty = 0.5;
                add(addBallButton);




    bounceEngine
------------------
        import java.awt.*;
        import javax.swing.*;
        public class bounceEngine implements Runnable {

            private balls parent;
            private int UPDATE_RATE = 144;

            public bounceEngine(balls parent) {
                this.parent = parent;

            }


            public void run() {

                int width = Sim.X;
                int height = Sim.Y;

                // Randomize the starting position...
                for (Ball ball : getParent().getBalls()) {
                    int x = Sim.random(width);
                    int y = Sim.random(height);

                    int size = ball.getRadius();

                    if (x + size > width) {
                        x = width - size;
                    }
                    if (y + size > height) {
                        y = height - size;
                    }

                    ball.setLocation(new Point(x, y));


                }

                while (getParent().isVisible()) {

                    // Repaint the balls pen...
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {


                                getParent().repaint();

                        }
                    });

                    //I know this is dangerous to update it as the repaint method is called
                    for (Ball ball : getParent().getBalls()) {
                        move(ball);
                    }

                    try{
                       Thread.sleep(1000/UPDATE_RATE);
                    }catch (InterruptedException e){

                    }

                }
            }

            public balls getParent() {
                return parent;
            }

            public void move(Ball ball) {

                Point p = ball.getLocation();
                Point speed = ball.getSpeed();
                int size = ball.getRadius();

                int vx = speed.x;
                int vy = speed.y;

                int x = p.x;
                int y = p.y;

                if (x + vx < 0  || x + (size*2) + vx > getParent().getWidth()) {
                    vx *= -1;
                }
                if (y + vy < 0  || y + (size*2) + vy > getParent().getHeight()) {
                    vy *= -1;
                }
                x += vx;
                y += vy;

                ball.setSpeed(new Point(vx, vy));
                ball.setLocation(new Point(x, y));

            }

        balls(for all the balls)
---------------------------------

        import java.awt.*;
        import java.awt.event.*;
        import java.util.ArrayList;
        import java.util.Random;
        import javax.swing.*;

        public class balls extends JPanel  {

            public static ArrayList<Ball> listBalls;

            public balls() {
                setPreferredSize(new Dimension(640,480));
                setBackground(Color.white);
                listBalls = new ArrayList<Ball>(10);


                for(int i = 0; i < Sim.numberOfBall; i++){
                    listBalls.add(new Ball((new Color(Sim.random(255),Sim.random(255), Sim.random(255))),20));

                }

            }

            public ArrayList<Ball> getBall(){
                return listBalls;

            }


            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                for (Ball ball : listBalls) {
                    ball.paint(g2d);
                }
                g2d.dispose();
            }

            public ArrayList<Ball> getBalls(){
                return listBalls;
            }

        Ball(for 1 ball object blank class with basic constructor)
----------------------------------------------------------------------

        import java.awt.*;

        public class Ball {

            private Color color;
            private Point location;
            private int radius;
            private Point speed;


            public Ball(Color color, int radius) {

                setColor(color);

                speed = new Point(5 - Sim.random(20), 5 - Sim.random(20));
                this.radius = radius;

            }


            public int getRadius() {
                return radius;
            }

            public void setColor(Color color) {
                this.color = color;
            }

            public void setLocation(Point location) {
                this.location = location;
            }

            public Color getColor() {
                return color;
            }

            public Point getLocation() {
                return location;
            }

            public Point getSpeed() {
                return speed;
            }

            public void setSpeed(Point speed) {
                this.speed = speed;
            }



            protected void paint(Graphics2D g2d) {

                Point p = getLocation();
                if (p != null) {
                    g2d.setColor(getColor());
                    g2d.fillOval(p.x, p.y, radius*2, radius*2);
                }

            }
        }