SlideShare a Scribd company logo
1 of 3
Download to read offline
Write a program that moves the ball in a pane. You should define a pane class for displaying the
ball and provide the methods for moving the ball left, right, up, and down. Check the boundary
to prevent the ball from moving out of sight completely. The language is Java.
Solution
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pane extends JFrame {
private JButton jbtLeft = new JButton("Left");
private JButton jbtRight = new JButton("Right");
private JButton jbtUp = new JButton("Up");
private JButton jbtDown = new JButton("Down");
private BallPanel ballPanel = new BallPanel();
public MovingABall () {
JPanel buttonPanel = new JPanel();
buttonPanel.add(jbtLeft);
buttonPanel.add(jbtRight);
buttonPanel.add(jbtUp);
buttonPanel.add(jbtDown);
ballPanel.setBackground(Color.RED);
this.add(ballPanel);
this.add(buttonPanel, BorderLayout.SOUTH);
jbtLeft.addActionListener(new ButtonListener());
jbtRight.addActionListener(new ButtonListener());
jbtUp.addActionListener(new ButtonListener());
jbtDown.addActionListener(new ButtonListener());
}
public static void main(String[] args) {
MovingABall mainWondow = new MovingABall();
mainWondow.setTitle("Moving a ball");
mainWondow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWondow.setVisible(true);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent buttonPressed) {
if (buttonPressed.getSource() == jbtLeft)
ballPanel.left();
else if (buttonPressed.getSource() == jbtRight)
ballPanel.right();
else if (buttonPressed.getSource() == jbtUp)
ballPanel.up();
else if (buttonPressed.getSource() == jbtDown)
ballPanel.down();
}
}
class BallPanel extends JPanel {
private int xCoord = -1;
private int yCoord = -1;
private Dimension preferredSize = new Dimension(300,200);
public void left() {
xCoord-=5;
repaint();
}
public void right() {
xCoord+=5;
repaint();
}
public void up() {
yCoord-=5;
repaint();
}
public void down() {
yCoord+=5;
repaint();
}
@Override
public Dimension getPreferredSize() {
return preferredSize;
}
protected void paintComponent(Graphics aBall) {
super.paintComponent(aBall);
if (xCoord<0 || yCoord<0) {
xCoord = getWidth()/2;
yCoord = getHeight()/2;
}
System.out.println("X" + getWidth());
aBall.drawOval(xCoord, yCoord, 10, 10);
}
}
}

More Related Content

More from sales98

Complete the following table for InvestmentsFair value method(s).pdf
Complete the following table for InvestmentsFair value method(s).pdfComplete the following table for InvestmentsFair value method(s).pdf
Complete the following table for InvestmentsFair value method(s).pdfsales98
 
Find the values of the trigonometric functions of from the informat.pdf
Find the values of the trigonometric functions of  from the informat.pdfFind the values of the trigonometric functions of  from the informat.pdf
Find the values of the trigonometric functions of from the informat.pdfsales98
 
Evolution is driven by environmental that put selection pressure on o.pdf
Evolution is driven by environmental that put selection pressure on o.pdfEvolution is driven by environmental that put selection pressure on o.pdf
Evolution is driven by environmental that put selection pressure on o.pdfsales98
 
e) As a practical matter, trade-offs of qualitative characteristics o.pdf
e) As a practical matter, trade-offs of qualitative characteristics o.pdfe) As a practical matter, trade-offs of qualitative characteristics o.pdf
e) As a practical matter, trade-offs of qualitative characteristics o.pdfsales98
 
Determine whether the relation defines y as a function of x. Give the.pdf
Determine whether the relation defines y as a function of x. Give the.pdfDetermine whether the relation defines y as a function of x. Give the.pdf
Determine whether the relation defines y as a function of x. Give the.pdfsales98
 
Connor and his wife are guests at the hotel, having reserved a room .pdf
Connor and his wife are guests at the hotel, having reserved a room .pdfConnor and his wife are guests at the hotel, having reserved a room .pdf
Connor and his wife are guests at the hotel, having reserved a room .pdfsales98
 
Define the role of the entrepreneur in the U.S. economy and describe.pdf
Define the role of the entrepreneur in the U.S. economy and describe.pdfDefine the role of the entrepreneur in the U.S. economy and describe.pdf
Define the role of the entrepreneur in the U.S. economy and describe.pdfsales98
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfsales98
 
8. You may have heard that drinking soda or acid is bad for your teet.pdf
8. You may have heard that drinking soda or acid is bad for your teet.pdf8. You may have heard that drinking soda or acid is bad for your teet.pdf
8. You may have heard that drinking soda or acid is bad for your teet.pdfsales98
 
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdf
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdfalter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdf
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdfsales98
 
2)Are enterprise information portals making executive information sy.pdf
2)Are enterprise information portals making executive information sy.pdf2)Are enterprise information portals making executive information sy.pdf
2)Are enterprise information portals making executive information sy.pdfsales98
 
5. How the tax system changes the distribution of income among capita.pdf
5. How the tax system changes the distribution of income among capita.pdf5. How the tax system changes the distribution of income among capita.pdf
5. How the tax system changes the distribution of income among capita.pdfsales98
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfsales98
 
Your name Date Explanation of Program -Modifying the first .pdf
Your name Date  Explanation of Program -Modifying the first .pdfYour name Date  Explanation of Program -Modifying the first .pdf
Your name Date Explanation of Program -Modifying the first .pdfsales98
 
Why is it that ozone is not desirable at the surface of earth, but i.pdf
Why is it that ozone is not desirable at the surface of earth, but i.pdfWhy is it that ozone is not desirable at the surface of earth, but i.pdf
Why is it that ozone is not desirable at the surface of earth, but i.pdfsales98
 
Which ape has been known to make territory patrols and wage war o.pdf
Which ape has been known to make territory patrols and wage war o.pdfWhich ape has been known to make territory patrols and wage war o.pdf
Which ape has been known to make territory patrols and wage war o.pdfsales98
 
What are the limitations of an expert systemSolutionLIMITATIO.pdf
What are the limitations of an expert systemSolutionLIMITATIO.pdfWhat are the limitations of an expert systemSolutionLIMITATIO.pdf
What are the limitations of an expert systemSolutionLIMITATIO.pdfsales98
 
Using the scenario provided in the Milestone One Guidelines and Rubr.pdf
Using the scenario provided in the Milestone One Guidelines and Rubr.pdfUsing the scenario provided in the Milestone One Guidelines and Rubr.pdf
Using the scenario provided in the Milestone One Guidelines and Rubr.pdfsales98
 
To avoid crises, companies should design their organizations to impl.pdf
To avoid crises, companies should design their organizations to impl.pdfTo avoid crises, companies should design their organizations to impl.pdf
To avoid crises, companies should design their organizations to impl.pdfsales98
 
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdf
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdfbronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdf
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdfsales98
 

More from sales98 (20)

Complete the following table for InvestmentsFair value method(s).pdf
Complete the following table for InvestmentsFair value method(s).pdfComplete the following table for InvestmentsFair value method(s).pdf
Complete the following table for InvestmentsFair value method(s).pdf
 
Find the values of the trigonometric functions of from the informat.pdf
Find the values of the trigonometric functions of  from the informat.pdfFind the values of the trigonometric functions of  from the informat.pdf
Find the values of the trigonometric functions of from the informat.pdf
 
Evolution is driven by environmental that put selection pressure on o.pdf
Evolution is driven by environmental that put selection pressure on o.pdfEvolution is driven by environmental that put selection pressure on o.pdf
Evolution is driven by environmental that put selection pressure on o.pdf
 
e) As a practical matter, trade-offs of qualitative characteristics o.pdf
e) As a practical matter, trade-offs of qualitative characteristics o.pdfe) As a practical matter, trade-offs of qualitative characteristics o.pdf
e) As a practical matter, trade-offs of qualitative characteristics o.pdf
 
Determine whether the relation defines y as a function of x. Give the.pdf
Determine whether the relation defines y as a function of x. Give the.pdfDetermine whether the relation defines y as a function of x. Give the.pdf
Determine whether the relation defines y as a function of x. Give the.pdf
 
Connor and his wife are guests at the hotel, having reserved a room .pdf
Connor and his wife are guests at the hotel, having reserved a room .pdfConnor and his wife are guests at the hotel, having reserved a room .pdf
Connor and his wife are guests at the hotel, having reserved a room .pdf
 
Define the role of the entrepreneur in the U.S. economy and describe.pdf
Define the role of the entrepreneur in the U.S. economy and describe.pdfDefine the role of the entrepreneur in the U.S. economy and describe.pdf
Define the role of the entrepreneur in the U.S. economy and describe.pdf
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdf
 
8. You may have heard that drinking soda or acid is bad for your teet.pdf
8. You may have heard that drinking soda or acid is bad for your teet.pdf8. You may have heard that drinking soda or acid is bad for your teet.pdf
8. You may have heard that drinking soda or acid is bad for your teet.pdf
 
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdf
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdfalter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdf
alter ego theory. TRUE FALSE Multiple Choice her nephew Dru to manag.pdf
 
2)Are enterprise information portals making executive information sy.pdf
2)Are enterprise information portals making executive information sy.pdf2)Are enterprise information portals making executive information sy.pdf
2)Are enterprise information portals making executive information sy.pdf
 
5. How the tax system changes the distribution of income among capita.pdf
5. How the tax system changes the distribution of income among capita.pdf5. How the tax system changes the distribution of income among capita.pdf
5. How the tax system changes the distribution of income among capita.pdf
 
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdfWrite Java FX code for this pseudocode of the void initilizaHistoryL.pdf
Write Java FX code for this pseudocode of the void initilizaHistoryL.pdf
 
Your name Date Explanation of Program -Modifying the first .pdf
Your name Date  Explanation of Program -Modifying the first .pdfYour name Date  Explanation of Program -Modifying the first .pdf
Your name Date Explanation of Program -Modifying the first .pdf
 
Why is it that ozone is not desirable at the surface of earth, but i.pdf
Why is it that ozone is not desirable at the surface of earth, but i.pdfWhy is it that ozone is not desirable at the surface of earth, but i.pdf
Why is it that ozone is not desirable at the surface of earth, but i.pdf
 
Which ape has been known to make territory patrols and wage war o.pdf
Which ape has been known to make territory patrols and wage war o.pdfWhich ape has been known to make territory patrols and wage war o.pdf
Which ape has been known to make territory patrols and wage war o.pdf
 
What are the limitations of an expert systemSolutionLIMITATIO.pdf
What are the limitations of an expert systemSolutionLIMITATIO.pdfWhat are the limitations of an expert systemSolutionLIMITATIO.pdf
What are the limitations of an expert systemSolutionLIMITATIO.pdf
 
Using the scenario provided in the Milestone One Guidelines and Rubr.pdf
Using the scenario provided in the Milestone One Guidelines and Rubr.pdfUsing the scenario provided in the Milestone One Guidelines and Rubr.pdf
Using the scenario provided in the Milestone One Guidelines and Rubr.pdf
 
To avoid crises, companies should design their organizations to impl.pdf
To avoid crises, companies should design their organizations to impl.pdfTo avoid crises, companies should design their organizations to impl.pdf
To avoid crises, companies should design their organizations to impl.pdf
 
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdf
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdfbronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdf
bronchi trachea vital capacity exhale carbon dioxide lungs alveoli in.pdf
 

Recently uploaded

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Recently uploaded (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 

Write a program that moves the ball in a pane. You should define a p.pdf

  • 1. Write a program that moves the ball in a pane. You should define a pane class for displaying the ball and provide the methods for moving the ball left, right, up, and down. Check the boundary to prevent the ball from moving out of sight completely. The language is Java. Solution import java.awt.BorderLayout; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Pane extends JFrame { private JButton jbtLeft = new JButton("Left"); private JButton jbtRight = new JButton("Right"); private JButton jbtUp = new JButton("Up"); private JButton jbtDown = new JButton("Down"); private BallPanel ballPanel = new BallPanel(); public MovingABall () { JPanel buttonPanel = new JPanel(); buttonPanel.add(jbtLeft); buttonPanel.add(jbtRight); buttonPanel.add(jbtUp); buttonPanel.add(jbtDown); ballPanel.setBackground(Color.RED); this.add(ballPanel); this.add(buttonPanel, BorderLayout.SOUTH); jbtLeft.addActionListener(new ButtonListener()); jbtRight.addActionListener(new ButtonListener()); jbtUp.addActionListener(new ButtonListener()); jbtDown.addActionListener(new ButtonListener()); } public static void main(String[] args) { MovingABall mainWondow = new MovingABall(); mainWondow.setTitle("Moving a ball"); mainWondow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWondow.setVisible(true);
  • 2. } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent buttonPressed) { if (buttonPressed.getSource() == jbtLeft) ballPanel.left(); else if (buttonPressed.getSource() == jbtRight) ballPanel.right(); else if (buttonPressed.getSource() == jbtUp) ballPanel.up(); else if (buttonPressed.getSource() == jbtDown) ballPanel.down(); } } class BallPanel extends JPanel { private int xCoord = -1; private int yCoord = -1; private Dimension preferredSize = new Dimension(300,200); public void left() { xCoord-=5; repaint(); } public void right() { xCoord+=5; repaint(); } public void up() { yCoord-=5; repaint(); } public void down() { yCoord+=5; repaint(); } @Override public Dimension getPreferredSize() { return preferredSize;
  • 3. } protected void paintComponent(Graphics aBall) { super.paintComponent(aBall); if (xCoord<0 || yCoord<0) { xCoord = getWidth()/2; yCoord = getHeight()/2; } System.out.println("X" + getWidth()); aBall.drawOval(xCoord, yCoord, 10, 10); } } }