Make graphics move on key events - java

I'm trying to make a circle capable of moving when the keys "i, j, k, l" are pressed (as arrow keys) and stop when released. Tried creating a Timer in order to wait a second before moving again so the animation is appreciable, but since I created the 'while(!quit)' loop, no graphics move or show. Could you please indicate my errors please?
Code:
import java.awt.*;
import java.awt.Color.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
public class Event_test{
public static void main(String args[])
{
boolean quit = false;
JFrame Window = new JFrame("Event_test");
MyCanvas WCanvas = new MyCanvas();
KeyCatcher k = new KeyCatcher();
WCanvas.addKeyListener(k);
Window.getContentPane().add(WCanvas);
Window.setSize(640, 360);
Window.setVisible(true);
Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Notification(1);
while(!quit)
{
WCanvas.update(WCanvas.getGraphics());
if(!Notification.flag)
{
continue;
}
else
{
Notification.flag = false;
System.out.println("tic");
/*
CONTROLS:
*/
if(KeyCatcher.KEYS[0])
{
MyCanvas.x--;
}
if(KeyCatcher.KEYS[1])
{
MyCanvas.y++;
}
if(KeyCatcher.KEYS[2])
{
MyCanvas.x++;
}
if(KeyCatcher.KEYS[3])
{
MyCanvas.y--;
}
if(KeyCatcher.KEYS[4])
{
quit = true;
}
new Notification(1);
}
}
}
}
class MyCanvas extends Canvas
{
static int x, y;
public void paint(Graphics g)
{
g = this.getGraphics();
MyClass.drawSomething(g, x, y);
}
}
class MyClass
{
public static void drawSomething(Graphics g, int x, int y)
{
g.setColor(Color.RED);
g.drawOval(x, y, 10, 10);
}
}
class KeyCatcher implements KeyListener
{
static boolean KEYS[] = new boolean[5];
public void keyPressed(KeyEvent e)
{
if(e.getKeyChar() == 'j'/*IZQ*/)
{
KEYS[0] = true;
}
if(e.getKeyChar() == 'i'/*ARR*/)
{
KEYS[1] = true;
}
if(e.getKeyChar() == 'l'/*DER*/)
{
KEYS[2] = true;
}
if(e.getKeyChar() == 'k'/*ABA*/)
{
KEYS[3] = true;
}
if(e.getKeyChar() == 'q'/*QUIT*/)
{
KEYS[4] = true;
}
}
public void keyReleased(KeyEvent e)
{
if(e.getKeyChar() == 'j'/*IZQ*/)
{
KEYS[0] = false;
}
if(e.getKeyChar() == 'i'/*ARR*/)
{
KEYS[1] = false;
}
if(e.getKeyChar() == 'l'/*DER*/)
{
KEYS[2] = false;
}
if(e.getKeyChar() == 'k'/*ABA*/)
{
KEYS[3] = false;
}
if(e.getKeyChar() == 'q'/*QUIT*/)
{
KEYS[4] = false;
}
}
public void keyTyped(KeyEvent e){
}
}
class Notification{
static boolean flag = false;
Timer timer;
Notification(int seconds)
{
timer = new Timer();
timer.schedule(new Task(), seconds*1000);
}
class Task extends TimerTask
{
public void run()
{
//What task does:
flag = true;
timer.cancel();
}
}
}

Your question is about Swing (not AWT) so:
Don't extend Canvas. Instead custom painting is done by extending a JPanel
Don't override paint(...). Custom painting is done by overrding paintComponent(...)
Don't use a TimerTask. Instead use a Swing Timer.
Don't use the getGraphics() method. See point 2.
Don't invoke update(...). You just invoke repaint() on the component and it will paint iself.
Don't use a while loop. That is the reason for using the Swing Timer.
Don't start variable names with an upper case character. Follow Java naming conventions.
Don't use a KeyListener. Swing was designed to be used with Key Bindings.
Check out the Swing tutorial on Custom Painting for basic painting examples to get you started.
Check out Motion Using the Keyboard. The Keyboard Animation example addresses many of these issues.

Related

Simple Pong Game Keyboard Input

(The game is not complete yet but nevertheless)
Using the keyboard input does not do anything, I believe this is due to KeyListener not being defined properly. Here is my code:
mainClass:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class mainClass extends JComponent{
private static ballAndGameplay ball;
private static calculateDrawPos blocks;
public static void main(String[] a) {
JFrame window = new JFrame("PONG");
window.setSize(1280,720);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainClass mc = new mainClass();
window.getContentPane().add(new mainClass());
window.setVisible(true);
ball = new ballAndGameplay(630,300,5,5);
blocks = new calculateDrawPos(false,false,false,false);
mc.addKeyListener(blocks);
while (true){
blocks.moveBlocks();
ball.moveBall();
mc.removeAll();
mc.paint(window.getGraphics());
try{
Thread.sleep(10);
}
catch (Exception e){
}
}
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect (-10, -10, 1300, 740);
g.setColor(Color.WHITE);
g.fillRect (10, blocks.PlayerOneY, 25, 125); //left player
g.fillRect (1230, blocks.PlayerTwoY, 25, 125); //right player
g.fillRect (638, -10, 4, 740); //middle line
g.fillRect (ball.ballX, ball.ballY, 20, 20); //ball
}
}
calculateDrawPos:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class calculateDrawPos extends KeyAdapter implements KeyListener {
int PlayerOneY=275;
int PlayerTwoY=275;
boolean wPressed;
boolean sPressed;
boolean upPressed;
boolean downPressed;
public calculateDrawPos (boolean a, boolean b, boolean c, boolean d) {
this.wPressed=a;
this.sPressed=b;
this.upPressed=c;
this.downPressed=d;
}
public void keyPressed(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.VK_W);
{
wPressed=true;
}
if (keyCode == KeyEvent.VK_S);
{
sPressed=true;
}
if (keyCode == KeyEvent.VK_UP);
{
upPressed=true;
}
if (keyCode == KeyEvent.VK_DOWN);
{
downPressed=true;
}
}
public void keyReleased(KeyEvent event) {
int keyCode = event.getKeyCode();
if (keyCode == KeyEvent.VK_W);
{
wPressed=false;
}
if (keyCode == KeyEvent.VK_S);
{
sPressed=false;
}
if (keyCode == KeyEvent.VK_UP);
{
upPressed=true;
}
if (keyCode == KeyEvent.VK_DOWN);
{
downPressed=true;
}
}
public void moveBlocks(){
if (wPressed==(true)){
PlayerOneY-=5;
}
if (sPressed==(true)){
PlayerOneY+=5;
}
if (upPressed==(true)){
PlayerTwoY-=5;
}
if (downPressed==(true)){
PlayerTwoY+=5;
}
}
}
ballAndGameplay:
import java.util.Random;
public class ballAndGameplay {
private static Random rand;
int ballX;
int ballY;
int ballXVelocity;
int ballYVelocity;
public ballAndGameplay (int a, int b, int c, int d) {
rand = new Random();
this.ballX=a;
this.ballY=b;
this.ballXVelocity=c;
this.ballYVelocity=d;
}
public void moveBall() {
boolean pointFinished = (ballX <= -20 || ballX >= 1280);
if (ballY <= 20 || ballY >= 700) {
ballYVelocity*=-1;
}
// if ((ballY >= PlayerOneY && ballY <= PlayerOneY+125 && ballX <= 35) || (ballY >= PlayerTwoY && ballY <= PlayerTwoY+125 && ballX >= 1245)){
// ballXVelocity*=-1.2;
// }
if (pointFinished==(true)){
try{
Thread.sleep(500);
}
catch (Exception e){
}
ballX=630;
ballY=300;
getBallX();
getBallY();
}
ballX+=ballXVelocity;
ballY+=ballYVelocity;
// System.out.println("ballX: "+ballX+" ballY: "+ballY+" ballXVelocity: "+ballXVelocity+" ballYVelocity: "+ballYVelocity);
}
public int getBallX(){
if (ballX != 630){
return ballXVelocity;
}
int side = rand.nextInt(2);
int number = rand.nextInt(5);
number+=4;
if (side==0){
ballXVelocity=-1*number;
}
else if (side==1){
ballXVelocity=1*number;
}
return ballXVelocity;
}
public int getBallY(){
if (ballY != 300){
return ballYVelocity;
}
int side = rand.nextInt(2);
int number = rand.nextInt(5);
number+=4;
if (side==0){
ballYVelocity=-1*number;
}
else if (side==1){
ballYVelocity=1*number;
}
return ballYVelocity;
}
}
You wrote
mainClass mc = new mainClass();
window.getContentPane().add(new mainClass());
That means that the mainClass that you added to your window isn't the same one that mc references. So all those operations you do to mc won't make any changes in your window.
You could try writing
mainClass mc = new mainClass();
window.getContentPane().add(mc);
instead.
Issues:
A KeyListener only works on a component that has current focus.
Your adding your KeyListener to a JComponent, a component that by default isn't even able to gain the focus (unlike a JButton, JTextField, and other components that typically allow keyboard interaction.)
One short term solution is to make your JComponent, the mc variable focusable by calling mc.setFocusable(true); and then giving it the system focus by calling mc.requestFocusInWindow();.
But having said this, you're still far better off using Key Bindings
Other issues:
Override and draw in the JComponent's paintComponent method not the paint method, if only to avoid the jerky graphics you'll get using paint.
Don't forget to call the super's paintComponent method in your override to erase the old ball image.
Never use a Graphics object obtained from a component by calling getGraphics() on it as the object thus obtained my become invalid or go null over time leading to invalid graphics or worse.
Never call the paint(...) or paintComponent(...) method directly as you're doing.
Instead use passive graphics as per the Swing graphics tutorials which I urge you to read.
Use a Swing Timer instead a while (true) loop since your while (true) loop risks tying up the Swing event thread, freezing your application.

How do I get fluid motion for my program?

The program works fine, but when I hold a key or change keys the motion is not smooth. It pauses for a split second before becoming smooth. I'm still a beginner at Java so please explain in detail.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game2015
{
JFrame frame;
DrawRect mainPanel;
GridBagLayout gridbag;
GridBagConstraints constraints;
Data data;
int width;
int height;
public static void main(String[] args)
{
new Game2015();
}
public Game2015()
{
frame = new JFrame();
width = 400;
height = 500;
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.setSize(width, height);
frame.setResizable(false);
data = new Data();
mainPanel = new DrawRect(data);
mainPanel.setFocusable(true);
mainPanel.setBackground(Color.WHITE);
KeyHandler keys = new KeyHandler();
mainPanel.addKeyListener(keys);
frame.add(mainPanel);
frame.validate();
frame.setLocationRelativeTo(null);
Thread thread = new Thread(new Runnable(){
public void run()
{
while(true)
{
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
});
thread.start();
}
public class KeyHandler implements KeyListener
{
public void keyReleased(KeyEvent event)
{
}
public void keyTyped(KeyEvent event)
{
}
public void keyPressed(KeyEvent event)
{
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP)
{
if(data.getY() >= data.getSpeed())
{
data.setY(data.getY() - data.getSpeed());
}
else
{
data.setY(0);
}
}
else if(event.getKeyCode() == KeyEvent.VK_S || event.getKeyCode() == KeyEvent.VK_DOWN)
{
if(data.getY() + 95 <= height - data.getSpeed())
{
data.setY(data.getY() + data.getSpeed());
}
else
{
data.setY(height - 95);
}
}
else if(event.getKeyCode() == KeyEvent.VK_A || event.getKeyCode() == KeyEvent.VK_LEFT)
{
if(data.getX() >= data.getSpeed())
{
data.setX(data.getX() - data.getSpeed());
}
else
{
data.setX(0);
}
}
else if(event.getKeyCode() == KeyEvent.VK_D || event.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(data.getX() + 75 <= width - data.getSpeed())
{
data.setX(data.getX() + data.getSpeed());
}
else
{
data.setX(width - 75);
}
}
else if(event.getKeyCode() == KeyEvent.VK_ESCAPE)
{
frame.dispose();
System.exit(0);
}
}
}
}
The code for drawing the rectangle is this:
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class DrawRect extends JPanel
{
BufferedImage img_player;
File file;
Data data;
public DrawRect(Data newData)
{
data = newData;
try
{
file = new File("Images\\Player.png");
img_player = ImageIO.read(file);
}
catch (Exception exception)
{
}
}
#Override
public void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.drawImage(img_player, data.getX(), data.getY(), null);
}
}
and the code for the Data class is this:
public class Data
{
int x, y, speed;
public Data()
{
x = 0;
y = 0;
speed = 10;
}
public void setSpeed(int new_speed)
{
speed = new_speed;
}
public int getSpeed()
{
return speed;
}
public void setX(int new_x)
{
x = new_x;
}
public int getX()
{
return x;
}
public void setY(int new_y)
{
y = new_y;
}
public int getY()
{
return y;
}
}
This is because of have java handles events: When you first press a key, it fires an event (pressing the key), and only after a small period of time does it continue to fire events (holding the key). You can test this by printing out every time an event is fired, and it will have a small delay between the first and the rest of the events.
The way to work around this is instead of every time you press a key changing the characters position, change the characters velocity.
For example, instead of
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
if(data.getY() >= data.getSpeed())
{
data.setY(data.getY() - data.getSpeed());
} else {
data.setY(0);
}
} ... etc ...
it would be
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
data.setVelocityY(-data.getSpeed());
} ... etc ...
as well as that, you'd also need to stop their velocity when they release the key. In your keyReleased() method, just do the same thing, but instead of setting velocity to speed, set it to 0.
if(event.getKeyCode() == KeyEvent.VK_W || event.getKeyCode() == KeyEvent.VK_UP){
data.setVelocityY(0);
} ... etc ...
and then in your game loop and a method update() that handles calculations (adding velocity to position)
So
public void run() {
while(true) {
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
would be
public void run() {
while(true) {
update();
mainPanel.repaint();
mainPanel.requestFocus(true);
}
}
where the update method would be
public static void update() {
data.setY(data.getY() + data.getVelocityY());
data.setX(data.getX() + data.getVelocityX());
}
You should look up basic tutorials on java games. For example, I always found this a good introductory tutorial.

Java 2D Game KeyListener Not Fulfilling It's Destiny

I've decided it's time to take my programming to the next step: Making A Game. So far I've been able to code everything alright, maybe having to Google some stuff I'm not too familiar with, but I feel like it should work. The graphics are being painted and all that's nice and dandy, but when it comes to the Key Listeners, that's where things went wrong. I made an inner class that implemented Key Listener, then added it in the Board constructor. I guess you'll just have to look at the code but it's pretty long and a bit messy. This is my first time doing this, so some stuff is probably unnecessary and I may just be forgetting something really obvious.
Main Class:
import javax.swing.*;
public class Game extends JFrame{
public static void main(String[] args){
new Game();
}
public Game(){
add(new Board());
setTitle("Hi mom");
setSize(555,330);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
}
}
Board Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Image background;
Player p;
int k;
boolean moving;
public Board() {
setFocusable(true);
Timer timer = new Timer(25, this);
timer.start();
ImageIcon img = new ImageIcon(getClass().getResource("images/map.png"));
background = img.getImage();
addKeyListener(new Kl());
p = new Player();
}
public void paint(Graphics g) {
g.drawImage(background, 0, 0, null);
g.drawImage(p.getPlayer(), p.setX(30), p.setY(187), null);
}
public void actionPerformed(ActionEvent e) {
if (k == 'W' && moving == true) {
p.move(0,-5);
}
if (k == 'S' && moving == true) {
p.move(0,5);
}
if (k == 'D' && moving == true) {
p.move(5,0);
}
if (k == 'A' && moving == true) {
p.move(-5,0);
}
repaint();
}
public class Kl implements KeyListener {
public void keyPressed(KeyEvent e) {
k = e.getKeyCode();
moving = true;
}
public void keyReleased(KeyEvent e) {
moving = false;
}
public void keyTyped(KeyEvent e) {
}
}
}
Player Class:
import javax.swing.*;
import java.awt.*;
public class Player{
int x, y;
Image player;
public Player(){
ImageIcon img = new ImageIcon(getClass().getResource("images/player.png"));
player = img.getImage();
}
public Image getPlayer(){
return player;
}
public void move(int x, int y){
this.x += x;
}
public int setX(int x){
this.x = x;
return x;
}
public int setY(int y){
this.y = y;
return y;
}
}
The problem is KeyListener will only trigger key events when the component it is registered to is focusable AND has keyboard focus. Simply calling setFocsuable isn't enough. This just means that the component is "capable" of receiving keyboard focus, not that it has it.
Instead, you should be using the Key Bindings API, which has the means to over come this limitation, amongst other things.

Java - KeyListener Events not firing

I have begun to write a simple platform game in java. As a test, I wrote this simple
program that moves a rectangle around the applet when you press the arrow keys. The key events have not been firing at all. Here's the code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends Applet implements Runnable, KeyListener
{
//setup data
Thread t;
Image buffimg;
Graphics draw;
Dimension dim;
//game variables
int charx = 400;//rectangles X and Y positions
int chary = 50;
boolean leftArrow = false;
public void init()
{
setSize(800, 500);
t = new Thread(this);
t.start();
addKeyListener( this );
}
public void run()
{
while(true)
{
repaint();
moveChar();//move the rectangle
try {
t.sleep(1000/30);
} catch (InterruptedException e) { ; }
}
}
public void keyPressed( KeyEvent e )
{
int k = e.getKeyCode();
if(k == 37)
{
leftArrow = true;
charx--;
}
}
public void keyReleased( KeyEvent e )
{
if(e.getKeyCode() == 37)
{
leftArrow = false;
}
}
public void keyTyped( KeyEvent e )
{
}
public void moveChar()
{
//move rectangle on left arrow key press
if(leftArrow == true)
{
charx--;
}
}
public void paint(Graphics g)
{
g.drawRect(charx, chary, 100, 100);
}
public void update (Graphics g)
{
//double buffering
// initialize buffer
if (buffimg == null)
{
buffimg = createImage (this.getSize().width, this.getSize().height);
draw = buffimg.getGraphics ();
}
// clear screen in background
draw.setColor (getBackground ());
draw.fillRect (0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
draw.setColor (getForeground());
paint (draw);
// draw image on the screen
g.drawImage (buffimg, 0, 0, this);
}
}
Why aren't they firing and how should I fix this?
this.requestFocusInWindow(); // end of init(), or better, in start()
I tried your code. It works as it should.
The problem is you need to press the mouse on the drawing area to focus it first before it can receive events.
To do it automatically, use this command: requestFocusInWindow()

KeyListener not responding in Java swing

I'm making a game, and I have a Main Menu that works perfectly. When I select one of the options, it brings up another Menu in a new window. However in this new window, the KeyListener is not responding. If I click back to the Main Menu window, the KeyListener is still working there. Here is the code:
MainMenu:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
public class DisplayMainMenu extends JFrame implements KeyListener{
static int width = 799, height = 463;
int arrowPos = 310;
boolean clear = true;
BufferedImage menu = null;
BufferedImage arrow = null;
LevelSkip test = new LevelSkip();
boolean done = false;
static DisplayMainMenu main;
public static void main(String[] args){
main = new DisplayMainMenu();
main.setResizable(false);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
main.init();
}
public void init() {
try{
menu = ImageIO.read(new File("Main Menu.png"));
arrow = ImageIO.read(new File("arrow.png"));
}catch(IOException ie) {
System.out.println(ie.getMessage());
}
this.setSize(width, height);
this.addKeyListener(this);
clear = true;
paint(getGraphics());
}
public void paint (Graphics g){
if(clear==true){
g.drawImage(menu,0,0,null);
clear = false;
}
g.drawImage(arrow,275,arrowPos,null);
}
public void keyPressed(KeyEvent e){
String key = e.getKeyText(e.getKeyCode());
if(key == "Up"){
clear = true;
if (arrowPos > 310)
arrowPos -= 30;
else
arrowPos = 370;
paint(getGraphics());
}
if(key == "Down"){
clear = true;
if (arrowPos < 370)
arrowPos += 30;
else
arrowPos = 310;
paint(getGraphics());
}
if(key == "Space"){
done = true;
switch(arrowPos){
case 310: System.out.println("RUN NEW GAME"); test.init();
break;
case 340: System.out.println("RUN HIGH SCORES");
break;
case 370: System.exit(0);
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
LevelSkip:
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
public class LevelSkip extends JFrame implements KeyListener {
static int width = 799, height = 463;
int arrowPos = 109;
boolean clear = true;
BufferedImage menu = null;
BufferedImage arrow = null;
public void init() {
LevelSkip main = new LevelSkip();
main.setSize(width, height);
main.requestFocusInWindow();
main.addKeyListener(main);
main.setResizable(false);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setVisible(true);
try{
menu = ImageIO.read(new File("level skip.png"));
arrow = ImageIO.read(new File("arrow2.png"));
}catch(IOException ie) {
System.out.println(ie.getMessage());
}
clear = true;
paint(main.getGraphics());
}
public void paint (Graphics g){
if(clear==true){
g.drawImage(menu,0,0,null);
clear = false;
}
g.drawImage(arrow,arrowPos,355,null);
}
public void keyPressed(KeyEvent e){
String key = e.getKeyText(e.getKeyCode());
if(key == "Left"){
clear = true;
if (arrowPos > 109)
arrowPos -= 260;
else
arrowPos = 629;
paint(getGraphics());
}
if(key == "Right"){
clear = true;
if (arrowPos < 629)
arrowPos += 260;
else
arrowPos = 109;
paint(getGraphics());
}
if(key == "Space"){
switch(arrowPos){
case 109: System.out.println("ADD 1 TO LEVEL AND RUN BATTLE");
break;
case 369: System.out.println("ADD 5 TO LEVEL AND RUN BATTLE");
break;
case 629: System.out.println("ADD 10 TO LEVEL AND RUN BATTLE");
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
I'm not exactly sure what the problem is, the Level Skip window displays fine, it just doesn't register any key presses.
If you've searched on this problem at all, you'll see that it almost always means that the component being listened to doesn't have focus. 90% of the time the solution is to use Key Bindings.
Your other problem is that you're comparing Strings ==. You don't want to do this. Use the equals or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if (fu.equals("bar")) {
// do something
}
or,
if (fu.equalsIgnoreCase("bar")) {
// do something
}
You're also
calling paint(...) directly, something you should almost never do.
Drawing in a top level window's paint(...) method which you also should avoid instead of drawing in a JPanel's (or other JComponent) paintComponent(...) method.
Not calling the paint or paintComponent's super method at the start of the method
Putting program logic in a paint or paintComponent method.
etc...
You will want to go through the Swing tutorials before going much further to learn from the pros.

Categories