Анимация с фигурой - Java

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

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

Написать приложение, которое выполняет анимацию изображения. Создать меню с командами Show picture, Choose, Animate, Stop, Quit. Команда Quit завершает работу приложения. При выборе команды Show picture в центре экрана рисуется объект, состоящий из нескольких графических примитивов. При выборе команды Choose открывается диалоговое окно, содержащее: -поле типа TextBox с меткой Speed для ввода скорости движения объекта; -группу Direction из двух переключателей (Up-Down, Left-Right) типа RadioButton для выбора направления движения; -кнопку типа Button. По команде Animate объект начинает перемещаться в выбранном направлении до края окна и обратно с заданной скоростью, по команде Stop — прекращает движение.
Присутствуют незначительные наброски проекта.
Листинг программы
  1. import java.awt.Dimension;
  2. import java.awt.GridBagLayout;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import javax.swing.JButton;
  6. import javax.swing.JComboBox;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. import javax.swing.JMenu;
  10. import javax.swing.JMenuBar;
  11. import javax.swing.JMenuItem;
  12. import javax.swing.JRadioButton;
  13. public class Main {
  14. public static void main(String[] args){
  15. JFrame frame = new JFrame("Moving square");
  16. frame.setSize(new Dimension(600,400));
  17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18. frame.setLocationRelativeTo(null);
  19. frame.setLayout(new GridBagLayout());
  20. JFrame frame1 = new JFrame("Choose");
  21. frame1.setSize(new Dimension(400,100));
  22. frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23. frame1.setLocationRelativeTo(null);
  24. frame1.setLayout(new GridBagLayout());
  25. JMenuBar menuBar = new JMenuBar();
  26. JMenuBar menuBar1 = new JMenuBar();
  27. JLabel label = new JLabel("Speed:");
  28. String str[] = {"1","2","3","4","5","10"};
  29. JComboBox combobox = new JComboBox(str);
  30. JRadioButton radiobutton1 = new JRadioButton("Up-Down");
  31. JRadioButton radiobutton2 = new JRadioButton("Left-Right");
  32. JButton button = new JButton("Ok");
  33. frame1.add(label);
  34. frame1.add(combobox);
  35. frame1.add(radiobutton1);
  36. frame1.add(radiobutton2);
  37. frame1.add(button);
  38. JMenu menu = new JMenu("Menu");
  39. JMenuItem showpicture = new JMenuItem("Show picture");
  40. JMenuItem choose = new JMenuItem("Choose");
  41. JMenuItem animate = new JMenuItem("Animate");
  42. JMenuItem stop = new JMenuItem("Stop");
  43. JMenuItem quit = new JMenuItem("Quit");
  44. menu.add(showpicture);
  45. menu.add(choose);
  46. menu.add(animate);
  47. menu.add(stop);
  48. menu.addSeparator();
  49. menu.add(quit);
  50. menuBar.add(menu);
  51.  
  52. quit.addActionListener(new ActionListener() {
  53. @Override
  54. public void actionPerformed(ActionEvent e) {
  55. System.exit(1);
  56. }
  57. });
  58.  
  59. choose.addActionListener(new ActionListener() {
  60. @Override
  61. public void actionPerformed(ActionEvent e) {
  62. frame1.setJMenuBar(menuBar1);
  63. frame1.setVisible(true);
  64. }
  65. });
  66. frame.setJMenuBar(menuBar);
  67. frame.setVisible(true);
  68. }
  69. }
Помогите с решением задачи...

Решение задачи: «Анимация с фигурой»

textual
Листинг программы
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5.  
  6. public class MainSpeed {
  7.  
  8.  
  9.     private static JComboBox combobox;
  10.     private static JRadioButton radiobutton1;
  11.     private static JRadioButton radiobutton2;
  12.     private static JButton button;
  13.  
  14.     private static class MyPanel extends JPanel {
  15.         private boolean active = false;
  16.         private boolean firstTime = true;
  17.  
  18.         private int x;
  19.         private int y;
  20.         private int dx;
  21.         private int dy;
  22.         private int speed;
  23.  
  24.         private final int TIMER_DELAY = 20;
  25.         private final int SHAPE_SIZE = 50;
  26.  
  27.         private Timer timer;
  28.  
  29.         public MyPanel() {
  30.             x = 0;
  31.             y = 0;
  32.             dx = 0;
  33.             dy = 0;
  34.             speed = 0;
  35.             timer = new Timer(TIMER_DELAY, new ActionListener() {
  36.                 @Override
  37.                 public void actionPerformed(ActionEvent e) {
  38.                     if (x < 0 || x > getWidth() - SHAPE_SIZE) {
  39.                         dx = -dx;
  40.                     }
  41.                     if (y < 0 || y > getHeight() - SHAPE_SIZE) {
  42.                         dy = -dy;
  43.                     }
  44.  
  45.                     x += dx;
  46.                     y += dy;
  47.  
  48.                     repaint();
  49.                 }
  50.             });
  51.  
  52.  
  53.         }
  54.  
  55.         @Override
  56.         public void paint(Graphics g) {
  57.             super.paint(g);
  58.  
  59.  
  60.             if (active) {
  61.                 g.setColor(Color.BLUE);
  62.                 g.drawOval(x, y, SHAPE_SIZE, SHAPE_SIZE);
  63.                 g.fillOval(x, y, SHAPE_SIZE, SHAPE_SIZE);
  64.             }
  65.  
  66.  
  67.         }
  68.  
  69.         private void getParameters() {
  70.             speed = Integer.parseInt((String) combobox.getSelectedItem());
  71.             if (firstTime) { //
  72.                 x = getWidth() / 2;
  73.                 y = getHeight() / 2;
  74.                 firstTime = false;
  75.             }
  76.  
  77.             if (radiobutton1.isSelected()) {
  78.                 if (dy > 0) {
  79.                     dy = -speed;
  80.                 } else {
  81.                     dy = speed;
  82.                 }
  83.             } else {
  84.                 if (dy > 0) {
  85.                     dy = speed;
  86.                 } else {
  87.                     dy = -speed;
  88.                 }
  89.             }
  90.             if (radiobutton2.isSelected()) {
  91.                 if (dx > 0) {
  92.                     dx = -speed;
  93.                 } else {
  94.                     dx = speed;
  95.                 }
  96.             } else {
  97.                 if (dx > 0) {
  98.                     dx = speed;
  99.                 } else {
  100.                     dx = -speed;
  101.                 }
  102.             }
  103.         }
  104.  
  105.     }
  106.  
  107.  
  108.     public static void main(String[] args) {
  109.         JFrame frame = new JFrame("Moving square");
  110.         frame.setSize(new Dimension(600, 400));
  111.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  112.         frame.setLocationRelativeTo(null);
  113. //        frame.setLayout(new GridBagLayout());
  114.  
  115.         JFrame frame1 = new JFrame("Choose");
  116.         frame1.setSize(new Dimension(400, 100));
  117.         frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  118.         frame1.setLocationRelativeTo(null);
  119.         frame1.setLayout(new GridBagLayout());
  120.  
  121.         JMenuBar menuBar = new JMenuBar();
  122.         JMenuBar menuBar1 = new JMenuBar();
  123.  
  124.         JLabel label = new JLabel("Speed:");
  125.         String str[] = {"1", "2", "3", "4", "5", "10"};
  126.         combobox = new JComboBox(str);
  127.         radiobutton1 = new JRadioButton("Up-Down");
  128.         radiobutton2 = new JRadioButton("Left-Right");
  129.         button = new JButton("Ok");
  130.  
  131.         frame1.add(label);
  132.         frame1.add(combobox);
  133.         frame1.add(radiobutton1);
  134.         frame1.add(radiobutton2);
  135.         frame1.add(button);
  136.  
  137.  
  138.         MyPanel panel = new MyPanel();
  139.         panel.setBackground(Color.white);
  140.         frame.add(panel, BorderLayout.CENTER);
  141.  
  142.  
  143.         JMenu menu = new JMenu("Menu");
  144.  
  145.         JMenuItem showpicture = new JMenuItem("Show picture");
  146.         JMenuItem choose = new JMenuItem("Choose");
  147.         JMenuItem animate = new JMenuItem("Animate");
  148.         JMenuItem stop = new JMenuItem("Stop");
  149.         JMenuItem quit = new JMenuItem("Quit");
  150.  
  151.         menu.add(showpicture);
  152.         menu.add(choose);
  153.         menu.add(animate);
  154.         menu.add(stop);
  155.         menu.addSeparator();
  156.         menu.add(quit);
  157.  
  158.         menuBar.add(menu);
  159.  
  160.  
  161.         button.addActionListener(new ActionListener() {
  162.  
  163.             @Override
  164.             public void actionPerformed(ActionEvent e) {
  165. //                frame1.setVisible(false);
  166.                 panel.getParameters();
  167.                 panel.repaint();
  168.             }
  169.         });
  170.  
  171.  
  172.         quit.addActionListener(new ActionListener() {
  173.             @Override
  174.             public void actionPerformed(ActionEvent e) {
  175.                 System.exit(1);
  176.  
  177.             }
  178.         });
  179.  
  180.  
  181.         choose.addActionListener(new ActionListener() {
  182.             @Override
  183.             public void actionPerformed(ActionEvent e) {
  184.                 frame1.setJMenuBar(menuBar1);
  185.                 frame1.setVisible(true);
  186.  
  187.  
  188.             }
  189.         });
  190.  
  191.         animate.addActionListener(new ActionListener() {
  192.             @Override
  193.             public void actionPerformed(ActionEvent e) {
  194.                 if (!panel.timer.isRunning()) {
  195.                     panel.timer.start();
  196.                 }
  197.                 frame.repaint();
  198.             }
  199.         });
  200.  
  201.         stop.addActionListener(new ActionListener() {
  202.             @Override
  203.             public void actionPerformed(ActionEvent e) {
  204.                 if (panel.timer.isRunning()) {
  205.                     panel.timer.stop();
  206.                 }
  207.                 frame.repaint();
  208.             }
  209.         });
  210.  
  211.  
  212.         showpicture.addActionListener(new ActionListener() {
  213.             @Override
  214.             public void actionPerformed(ActionEvent e) {
  215.                 if (panel.active) {
  216.                     panel.active = false;
  217.                 } else {
  218.  
  219.                     panel.active = true;
  220.                     if (panel.firstTime) {
  221.                         panel.getParameters();
  222.                     }
  223.                 }
  224.                 frame.repaint();
  225.             }
  226.         });
  227.  
  228.         frame.setJMenuBar(menuBar);
  229.         frame.setVisible(true);
  230.     }
  231.  
  232. }

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


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

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

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

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут