{"id":1230,"date":"2017-06-25T16:34:08","date_gmt":"2017-06-25T16:34:08","guid":{"rendered":"http:\/\/www.testingdocs.com\/questions\/?p=1230"},"modified":"2021-03-21T06:32:31","modified_gmt":"2021-03-21T06:32:31","slug":"how-to-code-a-simple-swing-game-using-java","status":"publish","type":"post","link":"https:\/\/www.testingdocs.com\/questions\/how-to-code-a-simple-swing-game-using-java\/","title":{"rendered":"How to code a Simple Swing Game using Java?"},"content":{"rendered":"<h3><strong>Problem Statement:<\/strong><\/h3>\n<p>Write a simple swing animation program using Java. Two buttons to start the animation and to close exit the window. You can use javax.swing.* package and java.awt.* package.<\/p>\n<h3><strong>Solution<\/strong><\/h3>\n<p>The problem statement is somewhat vague. It only conveys the idea to develop a swing application with animation using Swing \/ AWT packages in Java. Let us create a simple ball game with simple animation.<\/p>\n<p>We can compile and run Swing applications like any other java programs. Program that uses Swing\/AWT components need to import the following packages:<\/p>\n<p>&nbsp;<\/p>\n<h3><strong>Java Code<\/strong><\/h3>\n<pre>java.awt.*;\r\njavax.swing.*;\r\n\r\npublic class BallGame {\r\n    public static void main(String[] args) {\r\n        JFrame roomFrame = new Room();\r\n        roomFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); roomFrame.setVisible(true);\r\n    }\r\n}<\/pre>\n<h3><strong>Room<\/strong><\/h3>\n<pre><\/pre>\n<pre>class Room extends JFrame\r\n{\r\n    private static final long serialVersionUID = 1L;\r\n    private RoomPanel rPanel;\r\n    public static final int WIDTH = 750;\r\n    public static final int HEIGHT = 600;\r\n\r\n    public Room()\r\n    {\r\n        setSize(WIDTH, HEIGHT);\r\n        setTitle(\"GameRoom\");\r\n\r\n        Container contentPane = getContentPane();\r\n        rPanel = new RoomPanel();\r\n        contentPane.add(rPanel, BorderLayout.CENTER);\r\n        JPanel buttonPanel = new JPanel();\r\n        addButton(buttonPanel, \"Game Start\",\r\n                new ActionListener()\r\n                {\r\n                    public void actionPerformed(ActionEvent event)\r\n                    {\r\n                        addGameObject();\r\n                    }\r\n                });\r\n\r\n        addButton(buttonPanel, \"Game Close\",\r\n                new ActionListener()\r\n                {\r\n                    public void actionPerformed(ActionEvent event)\r\n                    {\r\n                        System.exit(0);\r\n                    }\r\n\r\n\r\n                });\r\n        contentPane.add(buttonPanel, BorderLayout.SOUTH);\r\n    }\r\n\r\n    public void addButton(Container c, String title,\r\n                          ActionListener listener)\r\n    {\r\n        JButton button = new JButton(title);\r\n        c.add(button);\r\n        button.addActionListener(listener);\r\n    }\r\n\r\n    public void addGameObject()\r\n    {\r\n        try\r\n        {\r\n            BallGameObject b = new BallGameObject(rPanel);\r\n            rPanel.add(b);\r\n            for (int i = 1; i &amp;lt;= 200; i++)\r\n            {\r\n                b.play();\r\n                Thread.sleep(50);\r\n            }\r\n        }\r\n        catch (InterruptedException ie)\r\n        {\r\n            ie.printStackTrace();\r\n        }\r\n    }\r\n}<\/pre>\n<pre><\/pre>\n<p>&nbsp;<\/p>\n<h3><strong>RoomPanel<\/strong><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1633\" src=\"http:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Room-extends-JFrame.png\" alt=\"Room extends JFrame\" width=\"1365\" height=\"659\" title=\"\"><\/p>\n<pre><\/pre>\n<pre>class RoomPanel extends JPanel\r\n{\r\n    private static final long serialVersionUID = 1L;\r\n    private ArrayList&amp;lt;BallGameObject&amp;gt; gameObjects = new ArrayList&amp;lt;BallGameObject&amp;gt;();\r\n\r\n    public void add(BallGameObject b)\r\n    {\r\n        gameObjects.add(b);\r\n    }\r\n\r\n    public void paintComponent(Graphics g)\r\n    {\r\n        super.paintComponent(g);\r\n        Graphics2D g2 = (Graphics2D)g;\r\n        for (int i = 0; i &amp;lt; gameObjects.size(); i++)\r\n        {\r\n            BallGameObject b = (BallGameObject)gameObjects.get(i);\r\n            b.draw(g2);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\nclass BallGameObject\r\n{\r\n    private Component component;\r\n    private static final int WIDTH = 60;\r\n    private static final int HEIGTH = 60;\r\n    private int x = 0;\r\n    private int y = 0;\r\n    private int dx = 10;\r\n    private int dy = 10;\r\n\r\n    public BallGameObject(Component c) { component = c; }\r\n\r\n    public void draw(Graphics2D g2)\r\n    {\r\n        g2.fill(new Ellipse2D.Double(x, y, WIDTH , HEIGTH ));\r\n        g2.setColor(Color.GREEN);\r\n    }\r\n\r\n    public void play()\r\n    {\r\n        x += dx;\r\n        y += dy;\r\n        if (x &amp;lt; 0)\r\n        {\r\n            x = 0;\r\n            dx = -dx;\r\n        }\r\n        if (x + WIDTH &amp;gt;= component.getWidth())\r\n        {\r\n            x = component.getWidth() - WIDTH ;\r\n            dx = -dx;\r\n        }\r\n        if (y &amp;lt; 0)\r\n        {\r\n            y = 0;\r\n            dy = -dy;\r\n        }\r\n        if (y + HEIGTH &amp;gt;= component.getHeight())\r\n        {\r\n            y = component.getHeight() - HEIGTH ;\r\n            dy = -dy;\r\n        }\r\n\r\n        component.paint(component.getGraphics());\r\n    }\r\n}\r\n\r\n\r\n\r\n<\/pre>\n<h3><strong>Output<br \/>\n<\/strong><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1631\" src=\"http:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Swing-Java-Simple-Game.png\" alt=\"Swing Java Simple Game\" width=\"1365\" height=\"673\" title=\"\"><\/p>\n<p><script type=\"text\/javascript\" src=\"\/\/services.brid.tv\/player\/build\/brid.min.js\"><\/script><\/p>\n<div id=\"Brid_19020492\" class=\"brid\" style=\"width: 600; height: 400;\"><\/div>\n<p><script type=\"text\/javascript\"> $bp(\"Brid_19020492\", {\"id\":\"8769\",\"width\":\"600\",\"height\":\"400\",\"video\":\"201881\"}); <\/script><\/p>\n<!--themify_builder_content-->\n<div id=\"themify_builder_content-1230\" data-postid=\"1230\" class=\"themify_builder_content themify_builder_content-1230 themify_builder tf_clear\">\n    <\/div>\n<!--\/themify_builder_content-->\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Write a simple swing animation program using Java. Two buttons to start the animation and to close exit the window. You can use javax.swing.* package and java.awt.* package. Solution The problem statement is somewhat vague. It only conveys the idea to develop a swing application with animation using Swing \/ AWT packages in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[40],"tags":[],"class_list":["post-1230","post","type-post","status-publish","format-standard","hentry","category-java","has-post-title","has-post-date","has-post-category","has-post-tag","has-post-comment","has-post-author",""],"_links":{"self":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1230","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/comments?post=1230"}],"version-history":[{"count":3,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1230\/revisions"}],"predecessor-version":[{"id":19733,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1230\/revisions\/19733"}],"wp:attachment":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/media?parent=1230"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/categories?post=1230"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/tags?post=1230"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}