如何将图像在JApplet中垂直移动?

时间:2021-08-31 12:06:02

I have displayed an image(ball) inside the JApplet, now I want the image to move in a vertical way (up and down). The problem is I don't know how to do it.

我在JApplet中显示了一个图像(球),现在我想让图像以垂直的方式移动(上下)。问题是我不知道该怎么做。

Could someone has an idea about this matter?

有人知道这件事吗?

4 个解决方案

#1


3  

You need to set the position of that image to some calculated value (means you caculate the vertical position using time, speed and maybe other restrictions).

您需要将该图像的位置设置为一些计算值(表示您使用时间、速度和其他限制来计算垂直位置)。

How you'd set that position depends on how you draw the image.

如何设置这个位置取决于你如何绘制图像。

Example, based on drawing in the applet's (or a nested component's) paint(Graphics g) method:

例如,基于applet's(或嵌套组件的)绘图(图形g)方法:

//first calculate the y-position
int yPos += timeSinceLastPaint * speed; //increment the position
if( (speed > 0 && yPos > someMaxY) || (speed < 0 && yPos <0 ) ) {
  speed *= -1; //if the position has reached the bottom (max y) or the top invert the direction  
}


//in your paint(Graphics g) method:
g.drawImage(image, yPos, x, null);

Then you'd have to constantly repaint the applet.

然后你必须不断地重新油漆小应用程序。

More information on animations in applets can be found here: http://download.oracle.com/javase/tutorial/uiswing/components/applet.html

更多关于applet动画的信息可以在这里找到:http://download.oracle.com/javase/tutorial/uiswing/components/applet.html。

#2


3  

another example for javax.swing.Timer with moving Ojbects created by paintComponent(Graphics g), and I have lots of Start, not some blurred Mikado :-)

另一个例子javax.swing。由paintComponent(图形g)创建的移动Ojbects的计时器,我有很多开始,而不是一些模糊的Mikado:-)

如何将图像在JApplet中垂直移动?

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class AnimationBackground {

    private Random random = new Random();
    private JFrame frame = new JFrame("Animation Background");
    private final MyJPanel panel = new MyJPanel();
    private JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
    private JPanel stopPanel = new JPanel();
    private JPanel startPanel = new JPanel();

    public AnimationBackground() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        panel.setBackground(Color.BLACK);
        for (int i = 0; i < 50; i++) {
            Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
            star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
            star.setxIncr(-3 + random.nextInt(7));
            star.setyIncr(-3 + random.nextInt(7));
            panel.add(star);
        }
        panel.setLayout(new GridLayout(10, 1));
        label.setForeground(Color.WHITE);
        panel.add(label);
        stopPanel.setOpaque(false);
        stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.stopAnimation();
            }
        }));
        panel.add(stopPanel);
        startPanel.setOpaque(false);
        startPanel.add(new JButton(new AbstractAction("Start moving...") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.startAnimation();
            }
        }));
        panel.add(startPanel);
        frame.add(panel);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationBackground aBg = new AnimationBackground();
            }
        });
    }

    private class Star extends Polygon {

        private static final long serialVersionUID = 1L;
        private Point location = null;
        private Color color = Color.YELLOW;
        private int xIncr, yIncr;
        static final int WIDTH = 500, HEIGHT = 500;

        Star(Point location) {
            int x = location.x;
            int y = location.y;
            this.location = location;
            this.addPoint(x, y + 8);
            this.addPoint(x + 8, y + 8);
            this.addPoint(x + 11, y);
            this.addPoint(x + 14, y + 8);
            this.addPoint(x + 22, y + 8);
            this.addPoint(x + 17, y + 12);
            this.addPoint(x + 21, y + 20);
            this.addPoint(x + 11, y + 14);
            this.addPoint(x + 3, y + 20);
            this.addPoint(x + 6, y + 12);
        }

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

        public void move() {
            if (location.x < 0 || location.x > WIDTH) {
                xIncr = -xIncr;
            }
            if (location.y < 0 || location.y > WIDTH) {
                yIncr = -yIncr;
            }
            translate(xIncr, yIncr);
            location.setLocation(location.x + xIncr, location.y + yIncr);
        }

        public void setxIncr(int xIncr) {
            this.xIncr = xIncr;
        }

        public void setyIncr(int yIncr) {
            this.yIncr = yIncr;
        }

        public Color getColor() {
            return color;
        }
    }

    private class MyJPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ArrayList<Star> stars = new ArrayList<Star>();
        private Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (Star star : stars) {
                    star.move();
                }
                repaint();
            }
        });

        public void stopAnimation() {
            if (timer.isRunning()) {
                timer.stop();
            }
        }

        public void startAnimation() {
            if (!timer.isRunning()) {
                timer.start();
            }
        }

        @Override
        public void addNotify() {
            super.addNotify();
            timer.start();
        }

        @Override
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        }

        MyJPanel() {
            this.setPreferredSize(new Dimension(512, 512));
        }

        public void add(Star star) {
            stars.add(star);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Star star : stars) {
                g.setColor(star.getColor());
                g.fillPolygon(star);
            }
        }
    }
}

#3


3  

How to move the image inside the JApplet ..?

如何在JApplet中移动图像?

Pretty much exactly the same way you might do it in a JFrame, JComponent or JPanel or...

和你在JFrame, JComponent, JPanel或者…

Or to put that another way, nothing to do with applets and everything to do with Graphics2D. For more details, see the 2D Graphics Trail of the Java Tutorial.

或者换种说法,与applet无关,和Graphics2D无关。有关更多细节,请参见Java教程的2D图形轨迹。

When you've figured how to move an image and paint it to a Graphics2D, implement that logic in a JComponent or JPanel's paintComponent(Graphics) method and drop the component with moving image into a JApplet or JFrame (or a JPanel etc.).

当您考虑如何移动图像并将其绘制到Graphics2D时,在JComponent或JPanel的paintComponent(图形)方法中实现该逻辑,并将组件移动到JApplet或JFrame(或JPanel等)中。


For the animation side of it, use a javax.swing.Timer as seen in this example. This example does not extend any component. Instead, it creates a BufferedImage and adds it to a JLabel that is displayed to the user. When the timer fires, the code grabs the Graphics object of the image, and proceeds from there to draw the bouncing lines.

对于动画方面,使用javax.swing。这个例子中的计时器。此示例不扩展任何组件。相反,它创建一个BufferedImage并将其添加到显示给用户的JLabel中。当计时器触发时,代码将抓取图像的图形对象,并从中提取出反弹的行。

如何将图像在JApplet中垂直移动?

import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;

class LineAnimator {

    public static void main(String[] args) {
        final int w = 640;
        final int h = 480;
        final RenderingHints hints = new RenderingHints(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON
            );
        hints.put(
            RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY
            );
        final BufferedImage bi = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB);
        final JLabel l = new JLabel(new ImageIcon(bi));
        final BouncingLine[] lines = new BouncingLine[100];
        int factor = 1;
        for (int ii=0; ii<lines.length; ii++) {
            lines[ii] = new BouncingLine(w*factor,h*factor);
        }
        final Font font = new Font("Arial", Font.BOLD, 30);
        ActionListener al = new ActionListener() {

            int count = 0;
            long lastTime;
            String fps = "";
            private final BasicStroke stroke = new BasicStroke(6);

            public void actionPerformed(ActionEvent ae) {
                count++;
                Graphics2D g = bi.createGraphics();
                g.setRenderingHints(hints);
                g.setColor(new Color(55,12,59));
                g.fillRect(0,0,w,h);
                g.setStroke(stroke);

                for (int ii=0; ii<lines.length; ii++) {
                    lines[ii].move();
                    lines[ii].paint(g);
                }

                if ( System.currentTimeMillis()-lastTime>1000 ) {
                    lastTime = System.currentTimeMillis();
                    fps = count + " FPS";
                    count = 0;
                }
                g.setColor(Color.YELLOW);
                g.setFont(font);
                g.drawString(fps,5,h-5);

                l.repaint();
                g.dispose();
            }
        };
        Timer timer = new Timer(25,al);
        timer.start();

        JOptionPane.showMessageDialog(null, l);
        //System.exit(0);
        timer.stop();
    }
}

class BouncingLine {
    private final Color color;
    private static final Random random = new Random();
    Line2D line;
    int w;
    int h;
    int x1;
    int y1;
    int x2;
    int y2;

    BouncingLine(int w, int h) {
        line = new Line2D.Double(random.nextInt(w),random.nextInt(h),random.nextInt(w),random.nextInt(h));
        this.w = w;
        this.h = h;
        this.color = new Color(
            random.nextInt(255)
            ,random.nextInt(255)
            ,random.nextInt(255)
            ,64+random.nextInt(128)
            );
        x1 = (random.nextBoolean() ? 1 : -1);
        y1 = (random.nextBoolean() ? 1 : -1);
        x2 = -x1;
        y2 = -y1;
    }

    public void move() {
        int tx1 = 0;
        if (line.getX1()+x1>0 && line.getX1()+x1<w) {
            tx1 = (int)line.getX1()+x1;
        } else {
            x1 = -x1;
            tx1 = (int)line.getX1()+x1;
        }
        int ty1 = 0;
        if (line.getY1()+y1>0 && line.getY1()+y1<h) {
            ty1 = (int)line.getY1()+y1;
        } else {
            y1 = -y1;
            ty1 = (int)line.getY1()+y1;
        }
        int tx2 = 0;
        if (line.getX2()+x2>0 && line.getX2()+x2<w) {
            tx2 = (int)line.getX2()+x2;
        } else {
            x2 = -x2;
            tx2 = (int)line.getX2()+x2;
        }
        int ty2 = 0;
        if (line.getY2()+y2>0 && line.getY2()+y2<h) {
            ty2 = (int)line.getY2()+y2;
        } else {
            y2 = -y2;
            ty2 = (int)line.getY2()+y2;
        }
        line.setLine(tx1,ty1,tx2,ty2);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(color);
        //line.set
        g2.draw(line);
    }
}

Update 1

I want to do it in JApplet(1) using the image(2), is it possible(3)?

我想在JApplet(1)中使用image(2),是否可能(3)?

  1. The examples by mKorbel and myself feature either an image in a JLabel or custom rendering in a JPanel. In our case, we added the components to a JOptionPane & a JFrame. Either example could be just as easily added to a JApplet, or a JDialog, or as part of another panel, or.. See the Laying Out Components Within a Container lesson & Using Top-Level Containers in the Java Tutorial for more details.
  2. mKorbel和我自己的例子要么是JLabel中的图像,要么是JPanel中的自定义呈现。在我们的例子中,我们将组件添加到JOptionPane和JFrame中。任何一个示例都可以很容易地添加到JApplet、JDialog或作为另一个面板的一部分。请参阅在容器教程中列出组件,并在Java教程中使用*容器了解更多细节。
  3. Instead of the stars or lines in our examples, ..paint your image. My example goes so far as to demonstrate how to get the position to bounce around within the bounds of the container.
  4. 而不是我们例子中的星星或线条。油漆你的形象。我的示例甚至演示了如何在容器的范围内实现反弹。
  5. Sure it is possible, but "Batteries not included". Our intention is to give you some ideas that you can then adapt to your bouncing ball applet. I doubt anyone is going to create an example for you, using balls, in an applet. Though if you post an SSCCE that shows your intent and what you tried, I (and others) would often run with that source. If you want more specific answers, ask a more specific SSCCE. ;)
  6. 当然,这是可能的,但“不包括电池”。我们的目的是给你一些想法,让你能适应你的弹跳球小应用。我怀疑有人会在applet中为你创建一个例子。不过,如果你发布了一个显示你的意图和你所尝试的东西的SSCCE,我(和其他人)经常会使用这个源。如果你想要更具体的答案,可以问一个更具体的SSCCE。,)

#4


3  

I want to do it in JApplet.

我想在JApplet中做。

Why not both? You can have a hybrid application/applet as shown in this animation.

为什么不两个呢?您可以使用这个动画中所示的混合应用程序/applet。

#1


3  

You need to set the position of that image to some calculated value (means you caculate the vertical position using time, speed and maybe other restrictions).

您需要将该图像的位置设置为一些计算值(表示您使用时间、速度和其他限制来计算垂直位置)。

How you'd set that position depends on how you draw the image.

如何设置这个位置取决于你如何绘制图像。

Example, based on drawing in the applet's (or a nested component's) paint(Graphics g) method:

例如,基于applet's(或嵌套组件的)绘图(图形g)方法:

//first calculate the y-position
int yPos += timeSinceLastPaint * speed; //increment the position
if( (speed > 0 && yPos > someMaxY) || (speed < 0 && yPos <0 ) ) {
  speed *= -1; //if the position has reached the bottom (max y) or the top invert the direction  
}


//in your paint(Graphics g) method:
g.drawImage(image, yPos, x, null);

Then you'd have to constantly repaint the applet.

然后你必须不断地重新油漆小应用程序。

More information on animations in applets can be found here: http://download.oracle.com/javase/tutorial/uiswing/components/applet.html

更多关于applet动画的信息可以在这里找到:http://download.oracle.com/javase/tutorial/uiswing/components/applet.html。

#2


3  

another example for javax.swing.Timer with moving Ojbects created by paintComponent(Graphics g), and I have lots of Start, not some blurred Mikado :-)

另一个例子javax.swing。由paintComponent(图形g)创建的移动Ojbects的计时器,我有很多开始,而不是一些模糊的Mikado:-)

如何将图像在JApplet中垂直移动?

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class AnimationBackground {

    private Random random = new Random();
    private JFrame frame = new JFrame("Animation Background");
    private final MyJPanel panel = new MyJPanel();
    private JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
    private JPanel stopPanel = new JPanel();
    private JPanel startPanel = new JPanel();

    public AnimationBackground() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        panel.setBackground(Color.BLACK);
        for (int i = 0; i < 50; i++) {
            Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
            star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
            star.setxIncr(-3 + random.nextInt(7));
            star.setyIncr(-3 + random.nextInt(7));
            panel.add(star);
        }
        panel.setLayout(new GridLayout(10, 1));
        label.setForeground(Color.WHITE);
        panel.add(label);
        stopPanel.setOpaque(false);
        stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.stopAnimation();
            }
        }));
        panel.add(stopPanel);
        startPanel.setOpaque(false);
        startPanel.add(new JButton(new AbstractAction("Start moving...") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                panel.startAnimation();
            }
        }));
        panel.add(startPanel);
        frame.add(panel);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationBackground aBg = new AnimationBackground();
            }
        });
    }

    private class Star extends Polygon {

        private static final long serialVersionUID = 1L;
        private Point location = null;
        private Color color = Color.YELLOW;
        private int xIncr, yIncr;
        static final int WIDTH = 500, HEIGHT = 500;

        Star(Point location) {
            int x = location.x;
            int y = location.y;
            this.location = location;
            this.addPoint(x, y + 8);
            this.addPoint(x + 8, y + 8);
            this.addPoint(x + 11, y);
            this.addPoint(x + 14, y + 8);
            this.addPoint(x + 22, y + 8);
            this.addPoint(x + 17, y + 12);
            this.addPoint(x + 21, y + 20);
            this.addPoint(x + 11, y + 14);
            this.addPoint(x + 3, y + 20);
            this.addPoint(x + 6, y + 12);
        }

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

        public void move() {
            if (location.x < 0 || location.x > WIDTH) {
                xIncr = -xIncr;
            }
            if (location.y < 0 || location.y > WIDTH) {
                yIncr = -yIncr;
            }
            translate(xIncr, yIncr);
            location.setLocation(location.x + xIncr, location.y + yIncr);
        }

        public void setxIncr(int xIncr) {
            this.xIncr = xIncr;
        }

        public void setyIncr(int yIncr) {
            this.yIncr = yIncr;
        }

        public Color getColor() {
            return color;
        }
    }

    private class MyJPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ArrayList<Star> stars = new ArrayList<Star>();
        private Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (Star star : stars) {
                    star.move();
                }
                repaint();
            }
        });

        public void stopAnimation() {
            if (timer.isRunning()) {
                timer.stop();
            }
        }

        public void startAnimation() {
            if (!timer.isRunning()) {
                timer.start();
            }
        }

        @Override
        public void addNotify() {
            super.addNotify();
            timer.start();
        }

        @Override
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        }

        MyJPanel() {
            this.setPreferredSize(new Dimension(512, 512));
        }

        public void add(Star star) {
            stars.add(star);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Star star : stars) {
                g.setColor(star.getColor());
                g.fillPolygon(star);
            }
        }
    }
}

#3


3  

How to move the image inside the JApplet ..?

如何在JApplet中移动图像?

Pretty much exactly the same way you might do it in a JFrame, JComponent or JPanel or...

和你在JFrame, JComponent, JPanel或者…

Or to put that another way, nothing to do with applets and everything to do with Graphics2D. For more details, see the 2D Graphics Trail of the Java Tutorial.

或者换种说法,与applet无关,和Graphics2D无关。有关更多细节,请参见Java教程的2D图形轨迹。

When you've figured how to move an image and paint it to a Graphics2D, implement that logic in a JComponent or JPanel's paintComponent(Graphics) method and drop the component with moving image into a JApplet or JFrame (or a JPanel etc.).

当您考虑如何移动图像并将其绘制到Graphics2D时,在JComponent或JPanel的paintComponent(图形)方法中实现该逻辑,并将组件移动到JApplet或JFrame(或JPanel等)中。


For the animation side of it, use a javax.swing.Timer as seen in this example. This example does not extend any component. Instead, it creates a BufferedImage and adds it to a JLabel that is displayed to the user. When the timer fires, the code grabs the Graphics object of the image, and proceeds from there to draw the bouncing lines.

对于动画方面,使用javax.swing。这个例子中的计时器。此示例不扩展任何组件。相反,它创建一个BufferedImage并将其添加到显示给用户的JLabel中。当计时器触发时,代码将抓取图像的图形对象,并从中提取出反弹的行。

如何将图像在JApplet中垂直移动?

import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;

class LineAnimator {

    public static void main(String[] args) {
        final int w = 640;
        final int h = 480;
        final RenderingHints hints = new RenderingHints(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON
            );
        hints.put(
            RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY
            );
        final BufferedImage bi = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB);
        final JLabel l = new JLabel(new ImageIcon(bi));
        final BouncingLine[] lines = new BouncingLine[100];
        int factor = 1;
        for (int ii=0; ii<lines.length; ii++) {
            lines[ii] = new BouncingLine(w*factor,h*factor);
        }
        final Font font = new Font("Arial", Font.BOLD, 30);
        ActionListener al = new ActionListener() {

            int count = 0;
            long lastTime;
            String fps = "";
            private final BasicStroke stroke = new BasicStroke(6);

            public void actionPerformed(ActionEvent ae) {
                count++;
                Graphics2D g = bi.createGraphics();
                g.setRenderingHints(hints);
                g.setColor(new Color(55,12,59));
                g.fillRect(0,0,w,h);
                g.setStroke(stroke);

                for (int ii=0; ii<lines.length; ii++) {
                    lines[ii].move();
                    lines[ii].paint(g);
                }

                if ( System.currentTimeMillis()-lastTime>1000 ) {
                    lastTime = System.currentTimeMillis();
                    fps = count + " FPS";
                    count = 0;
                }
                g.setColor(Color.YELLOW);
                g.setFont(font);
                g.drawString(fps,5,h-5);

                l.repaint();
                g.dispose();
            }
        };
        Timer timer = new Timer(25,al);
        timer.start();

        JOptionPane.showMessageDialog(null, l);
        //System.exit(0);
        timer.stop();
    }
}

class BouncingLine {
    private final Color color;
    private static final Random random = new Random();
    Line2D line;
    int w;
    int h;
    int x1;
    int y1;
    int x2;
    int y2;

    BouncingLine(int w, int h) {
        line = new Line2D.Double(random.nextInt(w),random.nextInt(h),random.nextInt(w),random.nextInt(h));
        this.w = w;
        this.h = h;
        this.color = new Color(
            random.nextInt(255)
            ,random.nextInt(255)
            ,random.nextInt(255)
            ,64+random.nextInt(128)
            );
        x1 = (random.nextBoolean() ? 1 : -1);
        y1 = (random.nextBoolean() ? 1 : -1);
        x2 = -x1;
        y2 = -y1;
    }

    public void move() {
        int tx1 = 0;
        if (line.getX1()+x1>0 && line.getX1()+x1<w) {
            tx1 = (int)line.getX1()+x1;
        } else {
            x1 = -x1;
            tx1 = (int)line.getX1()+x1;
        }
        int ty1 = 0;
        if (line.getY1()+y1>0 && line.getY1()+y1<h) {
            ty1 = (int)line.getY1()+y1;
        } else {
            y1 = -y1;
            ty1 = (int)line.getY1()+y1;
        }
        int tx2 = 0;
        if (line.getX2()+x2>0 && line.getX2()+x2<w) {
            tx2 = (int)line.getX2()+x2;
        } else {
            x2 = -x2;
            tx2 = (int)line.getX2()+x2;
        }
        int ty2 = 0;
        if (line.getY2()+y2>0 && line.getY2()+y2<h) {
            ty2 = (int)line.getY2()+y2;
        } else {
            y2 = -y2;
            ty2 = (int)line.getY2()+y2;
        }
        line.setLine(tx1,ty1,tx2,ty2);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(color);
        //line.set
        g2.draw(line);
    }
}

Update 1

I want to do it in JApplet(1) using the image(2), is it possible(3)?

我想在JApplet(1)中使用image(2),是否可能(3)?

  1. The examples by mKorbel and myself feature either an image in a JLabel or custom rendering in a JPanel. In our case, we added the components to a JOptionPane & a JFrame. Either example could be just as easily added to a JApplet, or a JDialog, or as part of another panel, or.. See the Laying Out Components Within a Container lesson & Using Top-Level Containers in the Java Tutorial for more details.
  2. mKorbel和我自己的例子要么是JLabel中的图像,要么是JPanel中的自定义呈现。在我们的例子中,我们将组件添加到JOptionPane和JFrame中。任何一个示例都可以很容易地添加到JApplet、JDialog或作为另一个面板的一部分。请参阅在容器教程中列出组件,并在Java教程中使用*容器了解更多细节。
  3. Instead of the stars or lines in our examples, ..paint your image. My example goes so far as to demonstrate how to get the position to bounce around within the bounds of the container.
  4. 而不是我们例子中的星星或线条。油漆你的形象。我的示例甚至演示了如何在容器的范围内实现反弹。
  5. Sure it is possible, but "Batteries not included". Our intention is to give you some ideas that you can then adapt to your bouncing ball applet. I doubt anyone is going to create an example for you, using balls, in an applet. Though if you post an SSCCE that shows your intent and what you tried, I (and others) would often run with that source. If you want more specific answers, ask a more specific SSCCE. ;)
  6. 当然,这是可能的,但“不包括电池”。我们的目的是给你一些想法,让你能适应你的弹跳球小应用。我怀疑有人会在applet中为你创建一个例子。不过,如果你发布了一个显示你的意图和你所尝试的东西的SSCCE,我(和其他人)经常会使用这个源。如果你想要更具体的答案,可以问一个更具体的SSCCE。,)

#4


3  

I want to do it in JApplet.

我想在JApplet中做。

Why not both? You can have a hybrid application/applet as shown in this animation.

为什么不两个呢?您可以使用这个动画中所示的混合应用程序/applet。