Написал программу добавления и удаления фигур - Java

Узнай цену своей работы

Формулировка задачи:

НО НЕМОГУ РАЗОБРАТЬСЯ В ОДНОМ.ВСЮ ГОЛОВУ СЛОМАЛ.Как сделать так чтобы фигуры при добавлении ещё и ДВИГАЛИСЬ.Пробовал задавать Timer но ничего не выходит при нажатии добавления((((((((((((((((((((((Студент 2 курса. Помогите пожалуйста буду очень благодарен!!!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;

public class FramePaint extends JFrame {
    private static int counter = 0;
    private int nSShape = 1;
    private static Random rnd = new Random();
    private double scale;
    private Timer timer;
 
    private JButton jButton = new JButton("Circle");
    private JButton jButton2 = new JButton("Rect");
    private JButton jButton3 = new JButton("Delete");

    private class SShape {
        private Color color;
        private double x; // 0..100%
        private double y; // 0..100%
        private double length; // 0..100%
        private boolean type;
 
        public SShape(Color color, double x, double y, double radius, boolean type) {
            this.color = color;
            this.x = x;
            this.y = y;
            this.length = radius;
            this.type = type;
            scale = 1.0;
           // timer = new Timer(100, (ActionListener) this);
        }
 
        public Color getColor() {
            return color;
        }
 
        public double getX() {
            return x;
        }
 
        public double getY() {
            return y;
        }
 
        public double getLength() {
            return length;
        }
 
        public boolean isType() {
            return type;
        }
 
        public void setType(boolean type) {
            this.type = type;
        }
    }
 
    private class SJPanel extends JPanel {  // панель со своим потоком и локальной фоновой задаче
        private final int id = counter++;
        private Color color;
        private double radius;
        List list = new ArrayList<>();
 
        private SShape genSShape() {
            Color color = new Color(rnd.nextInt(0xFFFFFF));
            double x = rnd.nextDouble()*0.9;
            double y = rnd.nextDouble()*0.9;
            double length = rnd.nextDouble()*0.9;  // диаметр или длина
            boolean type = rnd.nextBoolean();
            return new SShape(color, x, y, length, type);
 
        }
 
        public synchronized void addSShape(boolean type) {
            SShape sShape = genSShape();
            sShape.setType(type);
            list.add(sShape);
            
            repaint();
        }
 
        public synchronized void removeSShape() {
            if (list.size() > 0) {
                list.remove(list.size()-1); // remove last
                repaint();
            }
        }
 
        public SJPanel(int size) {      // начальный размер списка фигур
            for (int i = 0; i < size; i++) {
                list.add(genSShape());
            }
        }
 
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);  // вызывать обязательно чтобы не было искажений
            int width = getWidth(); // размер панели
 
            for (int i = 0; i < list.size(); i++) {
                SShape sShape = list.get(i);
                int x = (int)(width* sShape.getX());
                int y = (int)(width* sShape.getY());
                int length = (int)(width* sShape.getLength()/4);  // 1/4 и половина
                if (sShape.isType()) {
                    g.setColor(sShape.getColor());
                    g.fillOval(x, y, length, length);
                    //x++;
                   // y++;
                }else{
                    g.setColor(sShape.getColor());
                    g.fillRect(x, y, length, length);
                    //x++;
                   // y++;
                }
            }
        }

        @Override
        public String toString() {
            return "CBox " + id;
        }
    }

    public FramePaint() {
        SJPanel sjPanel = new SJPanel(nSShape); // 8 объектов
        JPanel jPanel = new JPanel(new GridLayout(1,3));
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               
                //sjPanel.addSShape(true);// add circle
            }
        });
        jButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sjPanel.addSShape(false);// add rect
            }
        });
        jButton3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sjPanel.removeSShape();// remove last
            }
        });
 
        jPanel.add(jButton);
        jPanel.add(jButton2);
        jPanel.add(jButton3);
 
        add(sjPanel);
        add(jPanel,BorderLayout.SOUTH); // внизу три кнопки
 
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                FramePaint jFrame = new FramePaint();
                jFrame.setSize(500, 600);
                jFrame.setVisible(true);
 
            }
        });
    }
 
}

Решение задачи: «Написал программу добавления и удаления фигур»

textual
Листинг программы
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
 
 
public class Go
{
    public JFrame window = new JFrame();
    public JButton[] bt = new JButton[4];
    public String[] btNames = {"box", "oval", "delBox", "delOval"};
    public ArrayList<BaseEnemy> classBox = new ArrayList<BaseEnemy>();
    public ArrayList<BaseEnemy> classOval = new ArrayList<BaseEnemy>();
    
    public Go()
    {
        makeWindow();
        makeButtons();
    }
    
    
    private void makeWindow()
    {
        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(800, 600));
        panel.setOpaque(false);
        
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.getContentPane().setBackground(Color.black);
        window.setResizable(false);
        window.add(panel);
        window.pack();
        window.setLayout(null);
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }
    
    
    private void makeButtons()
    {
        for (int i = 0; i < bt.length; i++)
        {
            bt[i] = new JButton();
            bt[i].setBounds(20+i*100, 20, 90, 25);
            bt[i].setText(btNames[i]);
            bt[i].setName(i+"");
            bt[i].setForeground(Color.BLACK);
            bt[i].setOpaque(false);
            bt[i].setContentAreaFilled(true);
            bt[i].setBorderPainted(true);
            bt[i].setFocusPainted(false);
            bt[i].setLayout(null);
            bt[i].addActionListener(new ActionListener()
            {
                int num = -1;
                
                
                public void actionPerformed(ActionEvent e)
                {   
                    if (Integer.parseInt(((JButton) e.getSource()).getName()) == 0)
                    {
                        num++;
                        BaseEnemy Type = new BaseEnemy(Integer.parseInt(((JButton) e.getSource()).getName()));
                        classBox.add(Type);
                        
                        window.add(Type);
                        window.repaint();
                    }
                    else if (Integer.parseInt(((JButton) e.getSource()).getName()) == 1)
                    {
                        num++;
                        BaseEnemy Type = new BaseEnemy(Integer.parseInt(((JButton) e.getSource()).getName()));
                        classOval.add(Type);
                        
                        window.add(Type);
                        window.repaint();
                    }
                    else if (Integer.parseInt(((JButton) e.getSource()).getName()) == 2)
                    {
                        if (num < classBox.size() - 1)
                        {
                            num++;
                            classBox.get(num).fpsTimer.stop();
                            classBox.get(num).fpsTimer.removeActionListener(this);
                            window.remove(classBox.get(num));
                            window.repaint();
                        }
                    }
                    else if (Integer.parseInt(((JButton) e.getSource()).getName()) == 3)
                    {
                        if (num < classOval.size() - 1)
                        {
                            num++;
                            classOval.get(num).fpsTimer.stop();
                            classOval.get(num).fpsTimer.removeActionListener(this);
                            window.remove(classOval.get(num));
                            window.repaint();
                        }
                    }
                }
            });
                   
            window.add(bt[i]);
        }
    }
    
    
    public class BaseEnemy extends JLabel
    {   
        private static final long serialVersionUID = 1L;
        int x = new Random().nextInt(700 - 100) + 100;
        int y = new Random().nextInt(500 - 100) + 100;
        int w = new Random().nextInt(50 - 20) + 20;
        int h = new Random().nextInt(50 - 20) + 20;
        int[] characterXY = {x,y};
        Timer fpsTimer;
        int type;
        
        
        public BaseEnemy(int n)
        {       
            setBounds(x, y, w, h);
            type = n;
            
            fpsTimer = new Timer(15, new ActionListener()
            {
                int[] arrSpeed = {3,6,9,12};
                int[] speedControlXY = {1,1};
                int[] speedXY = {arrSpeed[new Random().nextInt(arrSpeed.length)],
                        arrSpeed[new Random().nextInt(arrSpeed.length)]};
            
                
                public void actionPerformed(ActionEvent e)
                {   
                    characterXY[0] += speedXY[0];
                    characterXY[1] += speedXY[1];
                    setLocation(characterXY[0], characterXY[1]);
                    
                    if (characterXY[0] + getWidth() > 700)
                    {
                        characterXY[0] = 700 - getWidth();
                        speedControlXY[0] *= -1;
                        speedXY[0] = arrSpeed[new Random().nextInt(arrSpeed.length)] * speedControlXY[0];
                    }
                    else if (characterXY[0] < 0)
                    {
                        characterXY[0] = 0;
                        speedControlXY[0] *= -1;
                        speedXY[0] = arrSpeed[new Random().nextInt(arrSpeed.length)] * speedControlXY[0];
                    }
                    else if (characterXY[1] < 0)
                    {
                        characterXY[1] = 0;
                        speedControlXY[1] *= -1;
                        speedXY[1] = arrSpeed[new Random().nextInt(arrSpeed.length)] * speedControlXY[1];
                    }
                    else if (characterXY[1] + getHeight() > 500)
                    {
                        characterXY[1] = 500 - getHeight();
                        speedControlXY[1] *= -1;
                        speedXY[1] = arrSpeed[new Random().nextInt(arrSpeed.length)] * speedControlXY[1];
                    }
                }
            });
            fpsTimer.start();
        }
        
        
        public void paintComponent(Graphics g)
        {   
            if (type == 0)
            {
                g.setColor(new Color(120,190,255));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
            else if (type == 1)
            {
                g.setColor(new Color(20,190,155));
                g.fillOval(0, 0, getWidth(), getHeight());
            }
            
            repaint();
        }
    }
    
    
    public static void main(String[] args)
    {
        new Go();
    }
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 3.625 из 5