Reputation: 93
I have a whopping amount of code that I don't know how to implement key listener into. Basically, I wanted the key listener to detect a key press like "w" and change some fields (width and length), in which the program will interact with it. I have a boatload of import statements so I didn't include them. My original idea was to have setSizeWidth and setSizeLength call the keylistener method, which these two are called by the ok() method in the frame.setSize. This should make the keypress "w" shrink the window size. I really really really apologize for very long code but I am stumped. Ignore the other methods because I haven't finished this game and its levels yet!
@SuppressWarnings("serial")
public class Game extends JFrame implements KeyListener{
public static Game game;
public static JFrame frame = new JFrame("Bouncy Ball");
public static int x = 0;
public static int y = 0;
public static int xa = 1;
public static int ya = 1;
public static int x1 = 700;
public static int y1 = 500;
public static int x1a = 1;
public static int y1a = 1;
public static int f = 1;
public static boolean gg = true;
public static boolean t = false;
public static int width = 1000;
public static int length = 1000;
private void moveBall() {
if(f==1){
if (x + xa < 0)
xa = 1;
if (x + xa > getWidth() - 30)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > getHeight() - 30)
ya = -1;
x = x + xa;
y = y + ya;
}
else if(f==2){
if (x + xa < 0)
xa = 1;
if (x + xa > getWidth() - 30)
xa = -1;
if (x + xa > 670&&y+ya<770)
xa = -1;
if (x + xa < 680&&y+ya>770)
xa=1;
if (y + ya < 0)
ya = 1;
if (y + ya > getHeight() - 30)
ya = -1;
x = x + xa;
y = y + ya;
}
if(f==3){
if (x + xa < 0)
xa = 1;
if (x + xa > getWidth() - 30)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > getHeight() - 30)
ya = -1;
if(gg==true){
if (x1 + x1a < 0)
x1a = 1;
if (x1 + x1a > getWidth() - 30)
x1a = -1;
if (y1+ y1a < 0)
y1a = 1;
if (y1 + y1a > getHeight() - 30)
y1a = -1;
x1+=x1a;
y1+=y1a;
}
x = x + xa;
y = y + ya;
}
}
public static int setSizeWidth(){
????
return width;
}
public static int setSizeLength(){
?????
return length;
}
public void drawLevelOne(Graphics2D g2d) {
g2d.fillOval((int)x, (int)y, 30, 30);
if(t)g2d.setColor(Color.GREEN);
else g2d.setColor(Color.RED);
g2d.fillRect(300,500,30,30);
}
public void drawLevelTwo(Graphics2D g2d) {
g2d.fillOval((int)x, (int)y, 30, 30);
if(t)g2d.setColor(Color.GREEN);
else g2d.setColor(Color.BLUE);
g2d.fillRect(750,300,30,30);
g2d.fillRect(700,0,15,800);
}
public void drawLevelThree(Graphics2D g2d) {
g2d.fillOval((int)x, (int)y, 30, 30);
if(t)g2d.setColor(Color.GREEN);
else g2d.setColor(Color.RED);
g2d.fillRect(x1,y1,30,30);
g2d.fillRect(600,750,30,30);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(f==1) drawLevelOne(g2d);
else if(f ==2) drawLevelTwo(g2d);
else if(f==3) drawLevelThree(g2d);
}
public void checkCollision() throws InterruptedException {
boolean a = false;
if(270 < x && x < 330 && 470 < y && y < 530&&f==1) a = true;
else if(720 < x && x < 780 && 270 < y && y < 330&&f==2) a = true;
else if(f==3&&x>x1-30&&x<x1+30&&y>y1-30&&y<y1+30) gg = false;
else if(gg==false&& 570 < x && x < 630 && 720 < y && y < 780) a = true;
if(a) {
t=true;
game.repaint();
Thread.sleep(1300);
frame.setVisible(false);
System.out.println("You win! Play again?");
Scanner ggg = new Scanner (System.in);
String l = ggg.nextLine();
if(l.equals("yes")){
x=0;
y=0;
x1 = 300;
y1 = 500;
gg=true;
t = false;
ok();
frame.dispose();
System.exit(0);
}
else {
frame.dispose();
System.exit(0);
}
System.exit(0);
}
}
public void endGame() throws InterruptedException {
frame.setVisible(false);
System.out.println("You went out of bounds! Retry?");
Scanner ggg = new Scanner (System.in);
String l = ggg.nextLine();
if(l.equals("yes")){
x=0;
y=0;
x1 = 300;
y1 = 500;
gg=true;
t=false;
ok();
frame.dispose();
System.exit(0);
}
else {
frame.dispose();
System.exit(0);
}
}
public void checkOutOfBounds() throws InterruptedException {
if(f == 1 && (frame.getWidth() < 315 || frame.getHeight() < 540)) endGame();
else if(f == 2 && (frame.getWidth() < 765 || frame.getHeight() < 340)) endGame();
else if(f==3 && (frame.getWidth() < 615 || frame.getHeight() < 790)) endGame();
}
public void ok() throws InterruptedException {
game = new Game();
frame.add(game);
frame.setSize(1000, 1000);
addFocusable(true);
frame.addKeyListner(this);
Scanner scan = new Scanner (System.in);
System.out.println("Level one, two, or three?(must be an int)");
f = scan.nextInt();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
frame.setSize(setSizeWidth(),setSizeLength());
game.repaint();
Thread.sleep(5);
checkCollision();
checkOutOfBounds();
}
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 119:
length -= 5;
break;
case 115:
width += 5;
break;
case 97:
length -= 5;
break;
case 100:
length += 5;
break;
}
}
@Override
public void keyReleased(KeyEvent e){
}
@Override
public void keyTyped(KeyEvent e){
}
}
Upvotes: 0
Views: 90
Reputation: 347244
Consider using the Key Bindings API over KeyListener
, see How to Use Key Bindings for more details.
The basic idea is when a key event occurs, you want to call another method. In this way, you can call the method when ever you need it
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel("...");
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "shrink");
am.put("shrink", new DecreaseAction());
add(label);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
public void invalidate() {
super.invalidate();
Dimension size = getSize();
label.setText(size.getWidth() + "x" + getHeight());
}
protected void resizeBy(int widthDelta, int heightDelta) {
Window win = SwingUtilities.getWindowAncestor(this);
Dimension size = win.getSize();
size.width += widthDelta;
size.height += heightDelta;
win.setSize(size);
}
public class DecreaseAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
resizeBy(-1, 0);
}
}
}
}
Upvotes: 1