How to loop something in my paint function? [duplicate] - java

This question already has answers here:
Image change on hover Java
(2 answers)
Closed 5 years ago.
So I am trying to set up this thing that changes an image when hovered over. I have already set up the mouseListener to know if the mouse is over my image. I have a variable that has the image location stored in it and it changes when the image is hovered over. When my paint command is run it paints the default image and when I hover over it, it doesn't change because it is not painted again. How can I make it so that it repaints it again when the image location is changed. BTW the mouseListener is in a different class than the image.
My image:
private String settingsConfig = snake.settingsConfig;
settingsImage = new ImageIcon(getClass().getResource(settingsConfig));
settingsImage.paintIcon(this, g, 700, 23);
My main class (painting method is in the other class)
public class snake implements MouseListener{
public static int mouseX;
public static int mouseY;
public static String settingsConfig = "/assets/settings.png";
public static void main(String[] args) {
// JFrame
JFrame obj = new JFrame("Snake");
gameplay Gameplay = new gameplay();
obj.setBounds(10, 10, 905, 700);
obj.setBackground(Color.DARK_GRAY);
obj.setResizable(false);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(Gameplay);
obj.setVisible(true);
obj.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if(mouseX > 699 && mouseX < 761 && mouseY > 22 + 25 && mouseY < 54 + 25) {
settingsConfig = "/assets/settingshover.png";
}
else {
settingsConfig = "/assets/settings.png";
}
}
});
}
Very small piece of paint(Graphics g) (In a different class):
public void paint (Graphics g) {
if(moves == 0) {
snakexlength[2] = 50;
snakexlength[1] = 75;
snakexlength[0] = 100;
snakeylength[2] = 100;
snakeylength[1] = 100;
snakeylength[0] = 100;
}
if(moves >= 1) {
playing = true;
}
// Draw title image border
g.setColor(Color.WHITE);
g.drawRect(24, 10, 851, 55);
// Draw the title image and settings
titleImage = new ImageIcon(getClass().getResource("/assets/snaketitle.jpg"));
titleImage.paintIcon(this, g, 25, 11);
settingsImage = new ImageIcon(getClass().getResource(settingsConfig));
settingsImage.paintIcon(this, g, 700, 23);
// Draw the border for gameplay
g.setColor(Color.WHITE);
g.drawRect(24, 74, 851, 577);
// Draw background for the gameplay
g.setColor(Color.BLACK);
g.fillRect(25, 75, 850, 575);
// Draw score
g.setColor(Color.WHITE);
g.setFont(new Font("arial", Font.PLAIN, 14));
g.drawString("Score: " + score, 780, 30);
// Draw high score
g.drawString("High Score: " + highScore, 780, 50);
}

How can I make it so that it repaints it again when the image location is changed
Invoke reapint(); in the place where you need the paintings to be updated. For example in the listener when you mouse-over the image.
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if(mouseX > 699 && mouseX < 761 && mouseY > 22 + 25 && mouseY < 54 + 25){
settingsConfig = "/assets/settingshover.png";
}
else{
settingsConfig = "/assets/settings.png";
}
repaint();
}

Related

How to move this eye applet or to make it blink?

Please help me how to make this eye move or to make it blink using repaint, thread and implements runnable. I don't know where to place the right codes to make it work. Please help me guys! Thank you!
Here is the code:
import java.awt.*;
import java.applet.*;
public class Pucca extends Applet {
public Pucca(){
setSize(700, 700); }
//paint method
public void paint(Graphics g){
Color white = new Color(255,255,255);
g.setColor(white);
g.fillOval(600, 100, 125, 125); //left white fill eye
g.setColor(Color.BLA­CK);
g.drawOval(600, 100, 125, 125); // left big black line eye
g.setColor(white);
g.fillOval(700, 100, 125, 125); //right white fill eye
g.setColor(Color.BLA­CK);
g.drawOval(700, 100, 125, 125); //right big black line eye
Color blue = new Color(0, 160, 198);
g.setColor(blue);
g.fillOval(635, 130, 51, 51); // left blue fill eye
g.setColor(Color.BLA­CK);
g.drawOval(635, 130, 50, 50); // left black small line eye
g.setColor(blue);
g.fillOval(735, 130, 51, 51); // right blue fill eye
g.setColor(Color.BLA­CK);
g.drawOval(735, 130, 50, 50); // right black small line eye
g.setColor(Color.BLA­CK);
g.fillOval(650, 145, 20, 20); // left black iris
g.setColor(Color.BLA­CK);
g.fillOval(750, 145, 20, 20); // right black iris
}
}
When it comes to animation, everything becomes variable. You also have a lot of repeated code (seriously, if you can paint one eye, you can paint lots).
The first thing you need to is make all the values of the eye as variable as possible.
The follow makes the eye size and position variable and the iris and pupil a scaled value of the eye size, which makes the whole process simpler to animate.
Next, you need an updated loop, which can update the state of the values you want to change. To keep it simple, I've set it up so that the pupil has a variable offset, which is changed over time.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
public class Pucca extends Applet {
public Pucca() {
setSize(700, 700);
Thread t = new Thread(new Runnable() {
private int xDelta = -1;
private int yDelta = 0;
private int blinkCount = 0;
#Override
public void run() {
while (true) {
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
xOffset += xDelta;
double irisSize = eyeSize.width * irisScale;
double range = ((eyeSize.width - irisSize) / 2);
if (xOffset <= -range) {
xOffset = -(int) range;
xDelta *= -1;
} else if (xOffset >= range) {
xOffset = (int) range;
xDelta *= -1;
}
blinkCount++;
if (blink && blinkCount > 10) {
blink = false;
blinkCount = 0;
} else if (blinkCount > 25) {
blink = true;
blinkCount = 0;
}
repaint();
}
}
});
t.setDaemon(true);
t.start();
}
private boolean blink = false;
private int xOffset, yOffset = 0;
private Dimension eyeSize = new Dimension(125, 125);
private Point left = new Point(20, 20);
private Point right = new Point(left.x + 100, left.y);
private double irisScale = 0.4;
private double pupilScale = 0.16;
//paint method
#Override
public void paint(Graphics g) {
super.paint(g);
paintEye(g, new Rectangle(left, eyeSize));
paintEye(g, new Rectangle(right, eyeSize));
}
protected void paintEye(Graphics g, Rectangle bounds) {
Color white = new Color(255, 255, 255);
if (blink) {
g.setColor(Color.YELLOW);
} else {
g.setColor(white);
}
g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(bounds.x, bounds.y, bounds.width, bounds.height); // left big black line eye
if (!blink) {
Color blue = new Color(0, 160, 198);
paintEyePartAt(g, bounds, irisScale, blue);
paintEyePartAt(g, bounds, pupilScale, Color.BLACK);
}
}
private void paintEyePartAt(Graphics g, Rectangle bounds, double delta, Color color) {
int width = (int) (bounds.width * delta);
int height = (int) (bounds.height * delta);
g.setColor(color);
g.fillOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width, height); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width,
height); // left blue fill eye
}
}
This complicates things, as painting can occur for any number of reasons, many of which you don't have control over or will be notified about, so you should be very careful about where and when you change values.
You should also have a look at Java Plugin support deprecated and Moving to a Plugin-Free Web and Why CS teachers should stop teaching Java applets.
Applets are simply a dead technology and given the inherent complexities involved in using them, you should instead focus you should probably attention towards window based programs.
Personally, I'd start with having a look at Painting in AWT and Swing and Performing Custom Painting

Mini Tennis Game using Threads 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.

Java Key Events and Timer control

Im almost finished with this car project im working on but cant seem to get the key events to work. I think it has to do with my action listener with my timer but im not sure. When I press the up arrow key the timer delay is supposed to decrease and vice versa for the down arrow key. I have the commands written but they are not registering input. If anyone could give me some pointers I'd appreciate it
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RaceCar extends JFrame{
public RaceCar(){
add(new CarPic());
}
public static void main(String[] args){
JFrame frame = new RaceCar();
frame.setTitle("Brady Kedge: Race Car");
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class CarPic extends JPanel implements KeyListener
{
private int x = 0;
private int y = 150;
private int z = 300;
Timer mytimer = new Timer(50, new ActionListener());
public CarPic()
{
mytimer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 20);
polygon.addPoint(x + 20, y - 30);
polygon.addPoint(x + 30, y - 30);
polygon.addPoint(x + 40, y - 20);
if(x < z - 40)
{
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 10, 10, 10);
g.fillOval(x + 30, y - 10, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 20, 50, 10);
g.setColor(Color.BLUE);
g.fillPolygon(polygon);
}
else
x = 0;
}
public void actionPerformed(ActionEvent e){
x+=10;
repaint();
}
#Override
public void keyTyped(KeyEvent k) {
//Fill
}
#Override
public void keyPressed(KeyEvent k) {
int delay = mytimer.getDelay();
if(k.getKeyCode() == KeyEvent.VK_UP)
mytimer.setDelay(delay > 10 ? delay - 10 : 0);
else if(k.getKeyCode() == KeyEvent.VK_DOWN)
mytimer.setDelay(delay < 5000 ? delay + 10 : 5000);
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
First of all, you never register a KeyListener with your component (implementing KeyListener isn't enough).
Second of all, KeyListener will only raise KeyEvents if the component it is registered to has focus and is focusable.
A better solution would be to use the key bindings API, which provides you with the means to configure the focus level at which a component will trigger key events.
Also, personally, instead of modifying the Timer delay, I would have use a speed modifier (of type double) which would be percentage of the speed you want. In this way 1 would normal speed, 0.5 half speed and 2 double speed, for example.

Java create graphics object for drawing complex graphics from working method

I am somewhat new to java OO. Using the classic procedural aspects of Java are fairly straightforward, includingevent processing and even Swing. But I am having some trouble with objects.I have written a small program in Eclipsethat uses event processing for detecting mouse movement and clicks in an applet viewer. I even draw a face in the viewer on a mouse click. The face draw code is done in a method included in the program, which returns the drawn face as Graphics object 'g' passed as a parameter when calling the the 'drawFace()' method. The 'drawFace()' method returns a Graphics type and program works fine! I then try to make a separate class in Eclipse to create a new 'drawFace' object when there is a mouse click, just like the previous code, and instantiate it via 'new'. The face
is not drawn. I am sure I am not either defining the Face constructor class correctly or invoking it correctly. I am attaching first the working code using a method ('DrawFaceMethod'), and the non-working code using the main code and the second constructor class to draw to face ('DrawFaceObject'). Both codes are fairly short and similar. Any help appreciated.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletDrawFaceMethod extends Applet implements MouseListener ,
MouseMotionListener{
int mouseX = 0, mouseY = 30; // display area where coordinates of mouse displayed
int width = 0, height = 0; // size of applet viewing area
String msg = "";
boolean mouseclick = false; //need to test for mouse click on TRUE
Font font = new Font("Serif", Font.BOLD, 36);
public void init() {
width = getSize().width; //get applet viewing size
height = getSize().height;
System.out.println("Applet dimensions: " + width + " , " + height);
//addMouseListeners
addMouseListener(this);
addMouseMotionListener(this);
} // end init()
// paint method executed on every event
public void paint(Graphics g) {
//need to associate font with paint method
g.setFont(font);
//test mouseclick and set boolean
if (mouseclick == true){
//calls method 'drawFace', passes mouseclick x,y coordinates
// and Graphics object 'g'
//the 'drawFace' method returns a Graphic object of a face drawn
drawFace(mouseX, mouseY, g);
msg = "Face drawn at mouse click " + mouseX + ", " + mouseY;
//re-initialize variables
mouseclick = false;
mouseX = 0;
mouseY = 30;
} // end of 'if mouseclick == true' face drawing code
g.drawString(msg, mouseX, mouseY);
} // end of paint method
// Following methods are mouse 'Listener' methods to detect mouse events
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
msg = "Moving mouse at " + me.getX() + ", " + me.getY();
//showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
repaint();
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
mouseclick = true; //set boolean 'mouseclick' to TRUE
//save coordinates
mouseX = me.getX();
mouseY = me.getY();
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
//mouseX = 0;
//mouseY = 30;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
//mouseX = 0;
//mouseY = 30;
msg = "Mouse exited applet viewer.";
repaint();
}
//Other method mouse event methods required even if not used
// Handle button pressed.
public void mousePressed(MouseEvent me) {}
// Handle button released.
public void mouseReleased(MouseEvent me) {}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {}
///////////////////////////////////////////////////////////
//
// 'drawFace method' receive a Graphics object parameter g'
// it must return a Graphics object which the method draws
//
///////////////////////////////////////////////////////////
public Graphics drawFace(int xStart,int yStart, Graphics g) {
g.drawOval (mouseX, mouseY, 120, 150); // Head.
g.drawOval ((mouseX + 45), (mouseY + 60), 30, 30); // nose
g.fillArc((mouseX + 20), (mouseY + 85), 80, 40, 180, 180); //mouth.
g.drawOval ((mouseX + 17),(mouseY + 35), 30, 20); //Left eye.
g.drawOval ((mouseX + 70),(mouseY + 35), 30, 20); //Right eye.
g.fillOval ((mouseX + 28), (mouseY + 41), 10, 10); //Left pupil.
g.fillOval ((mouseX + 81), (mouseY + 41), 10, 10); //Right pupil.
g.drawOval ((mouseX - 15), (mouseY + 52), 15, 30); //Left ear.
g.drawOval ((mouseX + 120), (mouseY + 52), 15, 30); //Right ear.
g.drawArc ((mouseX + 15), (mouseY + 25),35,15,0,180);//Left brow.
g.drawArc ((mouseX + 67), (mouseY + 25), 35, 15, 0, 180);//Right.
return g; //returns pointer to drawn graphics face
} //end of drawFace method
} // End of class
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
//
// 'drawFaceObject' Applet code , followed by 'drawFace' constructor class
//
//
//////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DrawFaceObject extends Applet implements MouseListener ,
MouseMotionListener{
int mouseX = 0, mouseY = 30; // display mouse coordinates
int width = 0, height = 0; // size of applet viewing area
String msg = "";
boolean mouseclick = false; //need to test for mouse click on TRUE
Font font = new Font("Serif", Font.BOLD, 36);
public void init() {
width = getSize().width; //get applet viewing size
height = getSize().height;
System.out.println("Applet dimensions: " + width + " , " + height);
//addMouseListeners
addMouseListener(this);
addMouseMotionListener(this);
} // end init()
// paint method executed on every event
public void paint(Graphics g) {
//need to associate font with paint method
g.setFont(font);
//test mouseclick and set boolean
if (mouseclick == true){
//creates object'drawFace', passes mouseclick x,y coordinates
// and Graphics object 'g'
Class_DrawFace face = new Class_DrawFace(g);
msg = "Face drawn at mouse click " + mouseX + ", " + mouseY;
//re-initialize variables
mouseclick = false;
mouseX = 0;
mouseY = 30;
} // end of 'if mouseclick == true' face drawing code
g.drawString(msg, mouseX, mouseY);
} // end of paint method
// Following are mouse 'Listener' methods to detect mouse events
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
msg = "Moving mouse at " + me.getX() + ", " + me.getY();
//showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
repaint();
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
mouseclick = true; //set boolean 'mouseclick' to TRUE
//save coordinates
mouseX = me.getX();
mouseY = me.getY();
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
//mouseX = 0;
//mouseY = 30;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
//mouseX = 0;
//mouseY = 30;
msg = "Mouse exited applet viewer.";
repaint();
}
//Other method mouse event methods required even if not used
// Handle button pressed.
public void mousePressed(MouseEvent me) {}
// Handle button released.
public void mouseReleased(MouseEvent me) {}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {}
} // End of class
/////////////////////////////////////////////////////////////
//
// 'drawFace' Constructor
////////////////////////////////////////////////////////////
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Class_DrawFace extends Applet{
//instance variables
public Graphics g;
public int x, y;
Class_DrawFace(Graphics g) {
int x = 0;
int y = 0;
}
Class_DrawFace(int mouseX, int mouseY, Graphics g) {
int x = mouseX;
int y = mouseY;
}
public Graphics drawFace(int x, int y, Graphics g) {
g.drawOval (x, y, 120, 150); // Head.
g.drawOval ((x + 45), (y + 60), 30, 30); // nose
g.fillArc ((x + 20), (y + 85),80,40,180, 180);//mouth.
g.drawOval ((x + 17),(y + 35), 30, 20);//Left eye.
g.drawOval ((x + 70),(y + 35), 30, 20);//Right eye.
g.fillOval ((x + 28), (y + 41),10,10);//Left pupil.
g.fillOval ((x + 81), (y + 41),10,10);//Right pupil.
g.drawOval ((x - 15), (y + 52), 15, 30);//Left ear.
g.drawOval ((x + 120), (y + 52), 15, 30);//Right ear.
g.drawArc ((x + 15), (y + 25),35,15,0,180);//Left eyebrow.
g.drawArc ((x + 67), (y + 25),35,15,0,180);//Right eyebrow.
return g; //return drawnFace Graphics object
} //end of drawFace class constructor
}//end of class

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