Mini Tennis Game using Threads Java - java

I am having a some difficulty with developing of my code. Since I am not too advanced with Java I need some help. I am trying to develop Mini Tennis game using Threads. The aim of this game is to catch the balls moving on the window with the paddle that can be controlled with the left and right buttons on the keyboard.
Those balls should move diagonally on the window and when they touch to any of the corner (out of bottom) they should change their ways like light reflection. Apart from this, when a ball touches to one of the obstacles they should change their ways as well.
Paddle on the bottom of the window can be controlled with left and right keys.The task of the player is to catch the balls. The number of balls that the user catches will be shown on the Score part with the total number of balls going to the bottom corner.
User may need to save the state of the game. When the user clicks to the “save game” button; ball locations and score should save to the file. And when the user clicks to the open button, the state of game should be reloaded.
My source code files are:
public class BallPanel extends JPanel implements Runnable {
int RED, GREEN, BLUE;
int Xdirection = 1, Ydirection = 1;
boolean pleaseWait = false;
BallPanel(int X, int Y){
locateBall(X, Y, 30, 30);
/* Random r = new Random();
RED = r.nextInt(255);
GREEN = r.nextInt(255);
BLUE = r.nextInt(255);
*/
}
public void paint(Graphics g){
int panelWidth = this.getWidth();
int panelHeight = this.getHeight();
// g.setColor( new Color(RED, GREEN, BLUE ));
g.setColor(Color.ORANGE);
g.fillOval(panelWidth/2, panelHeight/2,panelWidth/2, panelHeight/2);
}
public void locateBall(int x, int y, int width, int height){
setBounds(x, y, width, height);
repaint();
}
public void run() {
int width = this.getWidth();
int height = this.getHeight();
Random r = new Random();
while(true){
if(!pleaseWait){
int lastX = this.getX();
int lastY = this.getY();
if (lastX > 675) Xdirection = -1;
if (lastY > 485) Ydirection = -1;
if (lastX < -5) Xdirection = 1;
if (lastY < -5) Ydirection = 1;
/* if(lastX > 280 && lastY > 170){
Xdirection = -1;
Ydirection = -1;
}
*/
locateBall(lastX + Xdirection*r.nextInt(3),
lastY + Ydirection*r.nextInt(3),
width, height );
}
try{
Thread.sleep(5);
}catch(Exception e){};
}
}
}
public class BallWindow extends JFrame implements ActionListener{
JButton btnStop = new JButton("STOP");
JButton btnSave = new JButton("SAVE");
Vector<BallPanel> ballVector = new Vector<BallPanel>();
JPanel p1 = createPanel(280, 200, 200, 20, Color.gray);
JPanel p2 = createPanel(280, 300, 200, 20, Color.gray);
JPanel bottomp = createPanel(345, 540, 70, 15, Color.black);
JPanel lborder = createPanel(10, 10, 2, 560, Color.black);
JPanel rborder = createPanel(720, 10, 2, 560, Color.black);
JPanel tborder = createPanel(10, 10, 710, 2, Color.black);
public BallWindow() {
setLayout(null);
btnStop.setBounds(12, 15, 100, 30);
btnStop.addActionListener(this);
add(btnStop);
btnSave.setBounds(12, 50, 100, 30);
//btnSave.addActionListener(this);
add(btnSave);
Random r = new Random();
for(int i=0; i<7; i++){
BallPanel bp = new BallPanel(r.nextInt(740), r.nextInt(590));
Thread t = new Thread(bp);
ballVector.add(bp);
t.start();
add(bp);
}
add(p1);
add(p2);
add(bottomp);
add(lborder);
add(rborder);
add(tborder);
setSize(740, 590);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
repaint();
}
JPanel createPanel(int x, int y, int width, int height, Color pColor){
JPanel temp = new JPanel();
temp.setBackground(pColor);
temp.setBounds(x, y, width, height);
return temp;
}
public static void main(String[] args) {
new BallWindow();
}
public void actionPerformed(ActionEvent arg0) {
for (BallPanel ball : ballVector) {
ball.pleaseWait = !ball.pleaseWait;
}
if( btnStop.getText().equalsIgnoreCase("STOP"))
btnStop.setText("START");
else
btnStop.setText("STOP");
// if(arg0.getSource())
}
}
I'm stuck with obstacles part and the keylistener. Any type of help will be greatly appreciated.

Hava a look at http://zetcode.com/tutorials/javagamestutorial/
You should especially check out the Basics and the Animation section. It will help clean up the animation and thread stuff you are doing. It also shows a general pattern how one could implement a java game.

Related

MouseClick coordinates appear only for the first time, always the same for others

I am making a program which draws circles in the clicked place.
For the first click it draws circle which is not exactly in the same place I have clicked.
But furthermore, for other clicks it just draws circles one on the other. as i find out it is because the coordinates of click won't change.
my main:
public static void main(String[] args)
{
JFrame frame = new JFrame();
//set window size
frame.setSize(1000, 1000);
//set the title
frame.setTitle("Oval Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add panel to frame and make it visible
MouseComponent component = new MouseComponent();
frame.add(component);
frame.setVisible(true);
}
and the MouseComponent class:
public class MouseComponent extends JPanel implements MouseListener
{
boolean drawPoint = true;
boolean drawLine = false;
boolean drawOval = false;
public MouseComponent()
{
super();
pointX = 0;
pointY = 0;
lineX = 0;
lineY = 0;
addMouseListener(this);
}
int pointX, pointY, lineX, lineY;
int[] ArrayX,ArrayY;
#Override
public void paintComponent(Graphics g)
{
for(int i=0; i<10; i++)
{
super.paintComponent(g);
if(drawLine)
{
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startrandomColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endrandomColor = new Color(red, green, blue);
Graphics2D g2d = (Graphics2D) g;
// this.addMouseListener(this);
GradientPaint gradient = new GradientPaint(70, 70, startrandomColor,
150, 150, endrandomColor);
g2d.setPaint(gradient);
g2d.translate( lineX, lineY);
g2d.fillOval(70, 70, 100, 100);
System.out.print(lineX);
System.out.print(" ");
System.out.print(lineY);
System.out.print(" ");
System.out.print(pointX);
System.out.print(" ");
System.out.print(pointY);
System.out.print(" ");
// repaint();
}
else if(drawPoint)
{
// g.drawOval(pointX-5,pointY-5,10,10);
}
}
}
public void mouseClicked(MouseEvent mouse)
{
if(!drawPoint)
{
pointX = mouse.getX();
pointY = mouse.getY();
drawPoint = true;
}
else if(!drawLine)
{
lineX = mouse.getX();
lineY = mouse.getY();
drawLine = true;
}
repaint();
}
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mousePressed(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }
}
This here:
if(!drawPoint)
{
pointX = mouse.getX();
pointY = mouse.getY();
drawPoint = true;
}
simply doesn't make too much sense. You init drawPoint to true ... so you will never enter the if block and collect the click coordinates.
And beyond that: when you look into your other method --- the code to draw points is commented out.
Suggestion: step back; don't try to do 5 things at the same time. Write the code it takes to
fetch mouse coordinates after a click
draw circles around that coordinate
and get that to work. Forget about drawing lines, shapes, whatever for now.
And when you have a class that does nothing but that click+draw circles; then create a new class, where you add more features. Your "real" problem right now is that you started working on various features; and that your attempts to "integrate" them into a single class left you with something that is confusing, and not surprising ... not working!
Long story short: forgot about that strange logic that you have in your code right now to "toggle" between drawing points and lines. Draw points. And then, when that works ... add some radio buttons; or a drop down menu and use that to control if you want to draw lines or points. Don't make that "implicit" by toggling booleans in your event handler code!
boolean drawPoint = true;
boolean drawLine = false; cause it to print the first time. After that both are set to true so it will not change coordinates.

Transferring JFrame to JPanel

I created a simple "elevator" program (it's still in the beginning stages) that goes up 1 floor when I click UP and vice versa.
I messed up pretty badly when I drew all my components into JFrame, and as expected, it flickers every time I click the button (repaints). I know the solution to be draw in the JPanel and put the said panel in the JFrame, but I have a problem translating my JFrame components into JPanel. I've tried extending JPanel, creating a JFrame object and then overriding the paintComponent() method and doing my drawing there, but when I compile it does not draw it at all. It only creates the frame.
Can anyone help me or give me tips on how to proceed "transferring" my programming from JFrame based to JPanel based? Thank you in advance!
My code is below:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
import java.math.*;
public class MyCanvas extends JFrame {
private int up = 0;
private int down = 0;
private int movefloorup = 0;
private int buildingType;//type of building (1 = Residential, 2 = Commercial)
private int totnumoffloors; //for the total number of floors
private int numofelevators; //for the number of elevators to be generated
private int floorlimit = 0; //to determine up until where the elevator will be moving
private int currenttime; //determine the time of the day the elevator is operating (1 = Morning, 2 = Lunch, 3 = Afternooon)
//For elevator resetting to bottom
private int rectX = 190;
private int switchmarker = 0;
//Lines and stuff
private int horizborder = 0;
private int bordercount = 0;
private class UpAction implements ActionListener //move the elevator up
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup<780){
repaint();
up++;
movefloorup = movefloorup + 130;
//repaint();
}
else
{
switchmarker = 1;
movefloorup = 0;
repaint();
}
}
}
private class DownAction implements ActionListener //move the elevator down
{
public void actionPerformed(ActionEvent e)
{
if(movefloorup>0){
repaint();
down++;
movefloorup = movefloorup - 130;
//repaint();
}
else
{
switchmarker = 0;
movefloorup = 780;
repaint();
}
}
}
public MyCanvas(int buildingType, int totnumoffloors, int numofelevators, int currenttime){
this.buildingType = buildingType;
this.totnumoffloors = totnumoffloors;
this.numofelevators = numofelevators;
this.currenttime = currenttime;
String title;
if(this.buildingType == 1)
{
title = "Residential Building";
}
else
{
title = "Commercial Building";
}
setLayout(null);
horizborder = 500*((int)Math.ceil((double)totnumoffloors/7)); //calculating how wide the window should be
bordercount = ((int)Math.ceil((double)totnumoffloors/7)); //counts how many borders there will be
//NOTES
//A floor is 130 units in the Y-Direction
//Drawing the bulding layout
if(totnumoffloors>7)
{
setSize(horizborder, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
else{
setSize(500, 1000); //suitable for 7 floors
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle(title);
setLayout(new BorderLayout());
getContentPane().setBackground(Color.WHITE);
}
JButton upButton = new JButton("UP");
upButton.addActionListener(new UpAction());
add(upButton, BorderLayout.NORTH);
JButton downButton = new JButton("DOWN");
//downButton.setBounds(0, 0, 220, 30);
//downButton.setLocation(100, 100);
downButton.addActionListener(new DownAction());
add(downButton, BorderLayout.SOUTH);
}
public void paint(Graphics graphics){ //this is where you draw shit
super.paint(graphics);
//Floors
graphics.setColor(Color.RED);
int numoffloorsY = 830;
int numoffloorsX = 830;
int floorbeginning = 0;
int floorcounter = 1;
int floorflag = 0;
int rightedge = 500;
if(this.totnumoffloors>7) //drawing the floors
{
//Default number of floors -> 7
for(int i = 0;i<totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,rightedge,numoffloorsY); //FLOORS
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOORS
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
floorflag++;
if(floorflag==7)
{
floorbeginning = floorbeginning + 500;
rightedge = rightedge+500;
numoffloorsY = 830;
numoffloorsX = 830;
floorflag = 0;
}
}
//Every other floor past 7 will be added here.
/*for(int i = 0;i<totnumoffloors-7;i++)
{
//System.out.println("LOLOOLO");
graphics.setColor(Color.RED);
graphics.drawLine(floorbeginning,numoffloorsX,horizborder,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning, numoffloorsY+20);
//graphics.setColor(Color.DARK_GRAY);
//graphics.drawLine(500,0,500,1000);
floorcounter++;
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
}*/
//DIVIDING LINE -> to determine the first 7 floors from the ones higher up.
for(int i=0;i<bordercount;i++)
{
graphics.setColor(Color.DARK_GRAY);
graphics.drawLine(500*i,0,500*i,1000);
}
}
else{
for(int i = 0;i<this.totnumoffloors;i++)
{
graphics.setColor(Color.RED);
graphics.drawLine(0,numoffloorsX,500,numoffloorsY);
graphics.setColor(Color.DARK_GRAY);
graphics.setFont(new Font("TimesRoman", Font.PLAIN, 15));
graphics.drawString(" "+floorcounter, floorbeginning+10, numoffloorsY+20); //SAVE THIS FOR DRAWING FLOOR
numoffloorsY = numoffloorsY - 130;
numoffloorsX = numoffloorsX - 130;
floorcounter++;
}
}
//Drawing the elevators
if(up>0 && movefloorup<1000){
graphics.setColor(Color.GRAY);
if(switchmarker==1)
{
System.out.println("ELSA");
rectX = 690;
//rectX = rectX + 190;
}
else
{
rectX = 190;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(rectX, 850-movefloorup, 100, 100);
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
//drawLine(x1, y1, x2, y2); --From (x1,y1) to (x2,y2)
}
else if(down>0 && movefloorup>0)
{
graphics.setColor(Color.GRAY);
if(switchmarker==1) //This determines when the elevator should move to the next column of higher floors.
{
System.out.println("ELSA");
rectX = 500;
}
System.out.println(rectX);
graphics.fillRect(rectX, 850-movefloorup, 100, 100); //this needs to match the stats of the rectangle to fill it properly
//graphics.drawRect(190, 850 + movefloorup, 100, 100); //FIRST FLOOR
graphics.drawRect(rectX, 850-movefloorup, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(rectX+50, 850-movefloorup, rectX+50, 950-movefloorup); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
System.out.println(movefloorup);
System.out.println(switchmarker);
}
else
{
graphics.setColor(Color.GRAY);
graphics.fillRect(190, 850, 100, 100); //this needs to match the stats of the rectangle to fill it properly
graphics.drawRect(190, 850, 100, 100); //FIRST FLOOR
graphics.drawRect(190, 850, 100, 100); //SECOND FLOOR (135 units difference in Y-axis between floors)
//x-coordinate, y-coordinate, width, height
//Line for the door
graphics.setColor(Color.BLACK);
graphics.drawLine(240, 850, 240, 950); //match the y-coordinate for the rectangle, add 100 for the y-coordinate of the other end
//System.out.println("In else!");
}
}
}
The main class just gets input from the user, such as the number of floors, time of day, etc.
This is going to be a little messy.
Start by creating a custom component that extends from JPanel (I'll call it ElevatorPane).
Take the contents of the current paint method and place them within this components paintComponent method. This will involve moving the instance variables that the paintComponent method will need including, totnumoffloors, bordercount, up, down, movefloorup, switchmarker, rectX
This is where it gets a little messy...
You need to take the contents of your ActionListeners and translate these into methods within the ElevatorPane, this way you expose the functionality without exposing the details...
Create a constructor within ElevatorPane that takes the number of floors.
Override the getPrefferedSize method of ElevatorPane and return the size that the component needs to be to satisfy your needs...
Create an instance field of ElevatorPane in MyCanvas, instantiate it and add it to the frame.
Clean, build, run...

Components on the JPanel doesn't show

I created a JPanel and i modify it a bit. I change it's background to gradient color here is the class.
public class JGradientPanel extends JPanel {
private static final int N = 32;
private Color color1, color2;
public JGradientPanel(Color color1, Color color2) {
this.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
this.color1 = color1;
this.color2 = color2;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//Color color1 = getBackground();
//Color color2 = color1.darker();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
Now i added few components to the panel but it didn't display anything, here is the code
public JPanel getMenu() {
JGradientPanel menu = new JGradientPanel(Color.WHITE, Color.white.darker());
int menuHeight = (int) ((int) getHeight() * 0.07);
menu.setPreferredSize(new Dimension(screenWidth,menuHeight));
menu.setLayout(new GridLayout(1,10));
menu.setBackground(Color.LIGHT_GRAY);
//test
JGradientButton test = new JGradientButton("test",Color.GREEN, Color.BLUE);
menu.add(test);
JLabel space = new JLabel(); // first blank space on the menu
space.setBounds(0, 0, menu.getPreferredSize().width - 50, menu.getPreferredSize().height);
space.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.GREEN));
menu.add(space);
JLabel moreSpaces[] = new JLabel[6];
buttons = new JButton[buttonLabels.length];
for(int counter = 0; counter < moreSpaces.length + buttonLabels.length; counter ++ ) {
if(counter < 3) {
buttons[counter] = new JButton(buttonLabels[counter]); //menu buttons
} else {
moreSpaces[counter - 3] = new JLabel(); // the rest of the blank in the menu
}
}
// adding components to menu panel
for(int counter = 0; counter < moreSpaces.length + buttonLabels.length; counter ++){
if(counter < 3) {
buttons[counter].setFocusPainted(false);
menu.add(buttons[counter]);
} else {
menu.add(moreSpaces[counter - 3]);
}
}
return menu;
}
Did i miss something or i did it wrong? What's wrong with my code?
override getPreferredSize in public class JGradientPanel extends JPanel {
Painting in Swing by public void paintComponent(Graphics g) { by default never to returns PreferredSize to JPanel,
JPanel returns Dimension[0, 0];
EDIT
see very informative and interesting thread about GradientPaint

Add a JPanel to a Graphics Panel and making the JPanel Transparent except for objects

I am trying to make a Blackjack Game and way I want to design my program is with a graphics panel (Images, drawing of cards, etc.) and on top of that panel a JPanel with buttons. I want this JPanel to be transparent so that the Graphics Panel underneath is Visible but the JButtons do not turn transparent as well.
If someone can send me in the right direction?
Graphic Layer:
public class GraphicsBoard {
String[] fileName = { "cards.png", "BlackJackBoard.png" };
ClassLoader cl = GraphicsBoard.class.getClassLoader();
URL imgURL[] = new URL[2];
Toolkit tk = Toolkit.getDefaultToolkit();
Image imgCards, imgBG;
public GraphicsBoard() throws Exception {
for (int x = 0; x < imgURL.length; x++)
imgURL[x] = cl.getResource("pictures/" + fileName[x]);
imgCards = tk.createImage(imgURL[0]);
imgBG = tk.createImage(imgURL[1]);
}
public void paintComponent(Graphics g) {
g.drawImage(imgBG, 0, 0, 550, 450, 0, 0, 551, 412, this);
Graphics2D g2 = (Graphics2D) g;
for (int x = 0; x <= 550; x += 50) {
g2.drawLine(x, 0, x, 450);
g2.drawString("" + x, x + 5, 20);
}
for (int y = 5; y <= 450; y += 50) {
g2.drawLine(0, y, 550, y);
g2.drawString(" " + y, 0, y + 20);
}
}
}
Button Layer:
public class OverBoard extends JPanel implements ActionListener{
JButton btnDeal = new JButton("Deal");
public OverBoard(){
btnDeal.addActionListener(this);
add(btnDeal);
setOpaque(false);
}
}
I want the ButtonLayer to be on top of the GraphicLayer.
I want this JPanel to be transparent so that the Graphics Panel
underneath is Visible but the JButtons do not turn transparent as
well.
an OverlayLayout JPanel will do what you descibe.
there are a few ways, proper could be to
use GlassPane, have to consume() or redispatch KeyEvents
JLayer (Java7), based on JXLayer(Java6)

Zooming In On a Java Graphic

I am making a graph of a sound speed profile with java graphics. I have the static graph drawn (the one that pops up when you run the program), but I am trying to implement it such that if the user clicks on either the x or y axis, then it will zoom in so you can look at the sound speed profile more closely. I don't have the sound speed profile in the graph yet (I already know how to do that, I'm just saving the effort of drawing it until I have the zoom feature figured out). Does anyone have any ideas as to how to make this work? I have seen people trying to use the Affine Transform for similar tasks, but I am not sure that's the right thing to do or if I'm even doing this correctly. The particular code to look at is the paint(), zoomIn(), and mouseClicked() method. Ideas would be much apprecaited!
public class SoundSpeedProfile extends JPanel implements MouseListener, ActionListener {
private String title;
private String subTitle;
private JFrame frame;
private Graphics g;
.
.
.
/**Draws the sound speed profile and surrounding graphics
* #param Graphics g - graphics object
*/
public void paint(Graphics g){
this.g = g;
super.paint(g); //the super knows how to draw "standard" components like squares, rectangles, circles, etc
g.setColor(Color.DARK_GRAY);
//1) Set up the graph the sound speed profile lives in
//X-Axis for Speeds
g.drawLine(100, 150, 450, 150);//the graphics display has 0,0 in the upper left corner versus the lower left corner
int i = 120;
int k = 1460;
while (i<440){
g.drawString("|", i, 155);
g.drawString("" + k + "", i-2, 140);
k = k + 20;
i = i + 60;
}
//Y-Axis
g.drawLine(100, 500, 100, 150);
k= 7000;
int j = 500;
while (j>160){
g.drawString("" + k, 60, j);
g.drawString("--", 94, j);
k = k - 1000;
j = j - 50;
}
Font f1 = new Font("Serif", 4, 15);
g.setFont(f1);
g.drawString(this.title, 200,30);//Graph Title
g.drawString(this.subTitle, 225, 50);
Font f2 = new Font("Serif", 2, 15);
g.setFont(f2);
g.drawString("Sound Speed ", 200, 110);//x-axis label
g.drawString("(" + spdUnits + ")", 290, 110); //Units label--taken from input array
g.drawString("Depth", 10, 180); //y-axis label
g.drawString("(" + depUnits + ")", 07, 200); //Units label--taken from input array
//((Graphics2D)g).scale(20, 20);
}
/**Creates and shows the GUI drawing of the sound speed profile in a JFrame
*/
private void createAndShowGUI(){
frame = new JFrame("Sound Speed Profile");
canvas = new Canvas();
frame.add(canvas);
frame.addMouseListener(this);
frame.setBackground(Color.cyan);
frame.setSize(600,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);//add the sound speed profile graphic and set a Border Layout
//frame.pack();
frame.setVisible(true);
}
/**
* Runs test cases
* #param args
*/
public static void main (String [] args){
ssp.setTitle("Sound Speed Profile 1");
ssp.setSubtitle("June 1, 2012");
ssp.createAndShowGUI();
ssp.repaint(); //necessary?
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
int x = arg0.getX();
//System.out.println("x: " + x);
int xMin = x - 50;
int xMax = x + 50;
int y = arg0.getY();
//System.out.println("y: " + y);
int yMin = y-50;
int yMax = y + 50;
//If the user clicked on the x-axis
if ( 160<y && y<180 && 100<x && x<450){
System.out.println("About to zoom in on the x-axis");
zoomIn(x, y);
//System.out.println("zooming in on the x-axis");
}
//If the user clicked on the y-axis
if (90<x && x<110 && 150 <y && y<500){
//System.out.println("zooming in on the y-axis");
}
}
public void zoomIn(int x, int y){
AffineTransform old = ((Graphics2D) g).getTransform();
for (double zoom = 1; zoom >=0.1; zoom=-0.1){
AffineTransform tr2 =AffineTransform.getTranslateInstance(-x, -y);
AffineTransform tr= AffineTransform.getScaleInstance(zoom,zoom);
tr.concatenate(tr2); tr2=tr;
tr =AffineTransform.getTranslateInstance(x, y);
tr.concatenate(tr2); tr2=tr;
tr= new AffineTransform(old);
tr.concatenate(tr2); tr2=tr;
((Graphics2D)g).setTransform(tr2);
((Graphics2D)g).drawRect(x, y, 10, 10);
((Graphics2D)g).setTransform(old);
}
}

Categories

Resources