我如何在java swing中左右,上,下移动形状

时间:2014-11-22 08:40:51

标签: java swing

我试图用按钮移动形状,但我没有得到它。这是我的抽奖课

class MyCanvas extends JComponent {


      public void paint(Graphics g) {

        g.setColor(Color.RED);
        g.fill3DRect(20, 20, 200, 200,true);
      }

    }
 class MyCanvas1 extends JComponent {


      public void paint(Graphics g) {

        g.setColor(Color.RED);
        g.drawRect(20, 20, 200, 200);
      }
    }

我通过以下代码成功绘图 - >

public class ButtonListener implements ActionListener
  {



    public void actionPerformed(ActionEvent e) {
        if(check)
        {

            if(e.getSource()==btnNewButton)
            {
                MyCanvas can=new MyCanvas();
                me s=new me();
                can.setSize(400, 500);
                panel_3.add(can);
                panel_3.repaint();
                addComponent(can);
                s.can;
                choice=true;

            }
       }
      else
      {
       if(e.getSource()==btnNewButton)
            {
                panel_3.removeAll();
                MyCanvas1 can=new MyCanvas1();
                can.setSize(500, 500);
                panel_3.add(can);
                panel_3.repaint();
                addComponent(can);
            }
       }

它对我来说很好。现在我有另外4个按钮,我想通过点击按钮移动形状。我尝试了一些方法,但没有一个能为我工作。任何建议我怎么做。我应该创建任何新的动作事件或类。

2 个答案:

答案 0 :(得分:2)

首先...

了解绘画如何在Swing中发挥作用,请参阅Painting in AWT and SwingPerforming Custom Painting

建议您覆盖paintComponent而不是paint并始终确保拨打super.paintComponent

public class MyCanvas extends JComponent {

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fill3DRect(20, 20, 200, 200,true);
    }

}

其次...

有很多方法可以实现这一点,就个人而言,我只是使用Graphics2D and Shapes APIs,但有些事情告诉我,对你来说不够好,所以。 ..

不是试图使用基于组件的形状(并且必须与布局管理器对抗),而是创建一个描述" drawable"元素,可以画的东西......

public interface Drawable {
    public Rectangle getBounds();
    public void setBounds(Rectangle bounds);
    public Color getColor();
    public void setColor(Color color);
    public void draw(Graphics2D g2d);
}

这描述了可以绘制的内容,颜色在哪里以及颜色

接下来,维护ListDrawables并使用paintComponent方法绘制它们......

public class MyCanvas extends JComponent {

    private List<Drawable> drawables;

    public MyCanvas() {
        drawables = new ArrayList<>(25);
    }

    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }

    public void add(Drawable drawable) {
        drawables.add(drawable);
        repaint();
    }

    public void remove(Drawable drawable) {
        drawables.remove(drawable);
        repaint();
    }

    public int getDrawableCount() {
        return drawables.size();
    }

    public Drawable getDrawableAt(int index) {
        return drawables.get(index);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g.create();
        for (Drawable d : drawables) {
            d.draw(g2d);
        }
        g2d.dispose();
    }

}

现在你有一些可以画画的东西和可以画它们的东西......

第三...

制作一些东西。我从一个抽象的Drawable开始,它涵盖了所有常见的东西,让生活更轻松......

public abstract class AbstractDrawable {
    private Rectangle bounds;
    private Color color

    public AbstractDrawable(Rectangle bounds, Color color) {
        setBounds(bounds);
        setColor(color);
    }

    public Rectangle getBounds() {
        return bounds;
    }
    public void setBounds(Dimension bounds) {
        this.bounds = bounds;
    }
    public Color getColor() {
        return color;
    }
    public void setColor(Color color) {
        this.color = color;
    }
    public abstract void draw(Graphics2D g2d);
}

你可以疯了......

public class DrawableRectangle {

    public AbstractDrawable(Rectangle bounds, Color color) {
        super(bounds, color);
    }

    public abstract void draw(Graphics2D g2d) {
        g2d.setColor(getColor());
        g2d.fill(getBounds());
    }
}

和/或...

public class Drawable3DRectangle {

    public AbstractDrawable(Rectangle bounds, Color color) {
        super(bounds, color);
    }

    public abstract void draw(Graphics2D g2d) {
        g2d.setColor(getColor());
        Rectangle bounds = getBounds();
        g2d.fill3DRect(bounds.x, bounds.y, bounds.width, bounds.height);
    }
}

第四...

把它们放在一起......

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DrawableShapes {

    public static void main(String[] args) {
        new DrawableShapes();
    }

    public DrawableShapes() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private MyCanvas canvas;

        public TestPane() {
            setLayout(new BorderLayout());
            canvas = new MyCanvas();
            add(canvas);

            canvas.add(new Drawable3DRectangle(new Rectangle(20, 20, 100, 100), Color.RED));
            canvas.add(new DrawableRectangle(new Rectangle(20, 140, 100, 100), Color.RED));

        }

    }

}

好的,所以这画了两个drawables,但是如何移动它们?

基本上,您获取对要移动的Drawable的引用,例如......

Drawable drawable = canvas.getDrawableAt(0);

然后你修改它的位置......

drawable.getBounds().x += 5;
drawable.getBounds().y += 5;

然后重新绘制MyCanvas实例...

canvas.repaint();

答案 1 :(得分:0)

我为你写了一个快速代码来获取这个想法 您可以使用Component setLocation(int x,int y)来完成此操作;获取当前x和y位置可以使用JComponent getX()和getY()方法。

例如comp.setLocation(comp.getX(),comp.getY());

public class Move extends JFrame implements ActionListener {

    JComponent b = new JButton("Move me");
    JButton a = new JButton("Move that");
    Random rd = new Random();

    public Move() throws HeadlessException {
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(a);
        add(b);
        a.addActionListener(this);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        repaint();
    }

    public static void main(String[] args) {
        new Move();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        int r = rd.nextInt(400);
        b.setLocation(b.getX(), r);
    }

}