Java object not updating from KeyEvent? - java

I am currently working on a simple program that will highlight a square depending on the corresponding key press (q for top left, e for top right, etc), and I cannot seem to get the rectangles to trigger from my key events. The key events are triggered, and the if statements are met for each one (put in a system.out in the color if statement and it displayed when key was pressed), however, the objects are not updating at all. Here is my code:
package acm;
import acm.graphics.*;
import acm.program.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class NewFinalGame extends GraphicsProgram {
private GObject redBrick, blueBrick, yellowBrick, greenBrick;
private GRectangle redBounds, blueBounds, yellowBounds, greenBounds;
Color dullRed = new Color(102, 0, 0);
Color dullBlue = new Color(0, 0, 51);
Color dullYellow = new Color(100, 100, 0);
Color dullGreen = new Color(0, 51, 0);
int level = 1;
public void init() {
addKeyListeners();
addMouseListeners();
setSize(500, 500);
setBackground(Color.black);
mainMenu();
}
public void run() {
waitForClick();
removeAll();
addSquares();
redBounds = redBrick.getBounds();
blueBounds = blueBrick.getBounds();
yellowBounds = yellowBrick.getBounds();
greenBounds = yellowBrick.getBounds();
}
public void mainMenu() {
GLabel welcome = new GLabel("Welcome to Simon.");
welcome.setColor(Color.white);
add(welcome, 100, 100);
GLabel clickToContinue = new GLabel("Click to continue...");
clickToContinue.setColor(Color.white);
add(clickToContinue, 150, 150);
}
public void addSquares() {
yellowBrick = new GRect(50, 50, 175, 175);
((GRect) yellowBrick).setFilled(true);
yellowBrick.setColor(dullYellow);
add(yellowBrick);
blueBrick = new GRect(275, 50, 175, 175);
((GRect) blueBrick).setFilled(true);
blueBrick.setColor(dullBlue);
add(blueBrick);
redBrick = new GRect(50, 275, 175, 175);
((GRect) redBrick).setFilled(true);
redBrick.setColor(dullRed);
add(redBrick);
greenBrick = new GRect(275, 275, 175, 175);
((GRect) greenBrick).setFilled(true);
greenBrick.setColor(dullGreen);
add(greenBrick);
}
public void highlight(GObject rect) {
if (rect.getColor() == dullYellow) {
System.out.println("Success!");
rect.setColor(Color.yellow);
pause(1000);
rect.setColor(dullYellow);
}
if (rect.getColor() == dullBlue) {
rect.setColor(Color.blue);
pause(1000);
rect.setColor(dullBlue);
}
if (rect.getColor() == dullRed) {
rect.setColor(Color.red);
pause(1000);
rect.setColor(dullRed);
}
if (rect.getColor() == dullGreen) {
rect.setColor(Color.green);
pause(1000);
rect.setColor(dullGreen);
}
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_Q:
highlight(yellowBrick);
break;
case KeyEvent.VK_W:
highlight(blueBrick);
break;
case KeyEvent.VK_A:
highlight(redBrick);
break;
case KeyEvent.VK_S:
highlight(greenBrick);
break;
}
}
}
Thank you for any help.

Related

java menu not working. i'm not being able to use the key down and up to go through the menu correctly

hi my java menu is not working probably is the keylistener i'm not being able to use the key up and down in case 2 to case 4, how can i fix this?
However, i'm not sure how to modify it to make it working correctly, but i know that probably s the keylistener. Im new in java and i'm trying to do this project pls help
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.Container;
import java.io.InputStream;
import javax.swing.JPanel;
import sun.audio.AudioStream;
public class Game extends JFrame implements KeyListener{
BufferedImage backBuffer;
int FPS = 100;
int JanelaX = 800;
int JanelaY = 600;
private static String[] TeclasPressionadas = new String[256];
// int FundoX = -250;
int se=-1;
int c =1;
int mf=1;
InputStream in;
AudioStream audio;
ImageIcon Fundo = new ImageIcon("src/Imagens/fundo.jpg");
Graphics g,bbg;
public void desenharGraficos(){
g = getGraphics();
bbg = backBuffer.getGraphics();
CriaMenu();
Acede_Opcoes();
//bbg.drawImage(Fundo.getImage(), FundoX, 0, this);
g.drawImage(backBuffer, 0, 0, this);
}
public void CriaMenu()
{
Font myFont = new Font("bauhaus 93",Font.BOLD,50);
bbg.setFont(myFont);
switch(c)
{
case 1:
bbg.setColor(new Color(57, 176, 214));
bbg.drawString("Jogar", 300, 210);
bbg.setColor(Color.orange);
bbg.drawString("Scores", 300,270);
bbg.drawString("Regras",300, 330);
bbg.drawString("Créditos", 300, 390);
bbg.drawString("Sair", 300, 450);
break;
case 2:
bbg.setColor(Color.orange);
bbg.drawString("Jogar", 300, 210);
bbg.setColor(new Color(57, 176, 214));
bbg.setColor(Color.orange);
bbg.drawString("Scores", 300,270);
bbg.drawString("Regras",300, 330);
bbg.drawString("Créditos", 300, 390);
bbg.drawString("Sair", 300, 450);
break;
case 3:
bbg.setColor(Color.orange);
bbg.drawString("Jogar", 300, 210);
bbg.setColor(Color.orange);
bbg.drawString("Scores", 300,270);
bbg.setColor(new Color(57, 176, 214));
bbg.drawString("Regras",300, 330);
bbg.drawString("Créditos", 300, 390);
bbg.drawString("Sair", 300, 450);
case 4:
bbg.setColor(Color.orange);
bbg.drawString("Jogar", 300, 210);
bbg.setColor(Color.orange);
bbg.drawString("Scores", 300,270);
bbg.drawString("Regras",300, 330);
bbg.setColor(new Color(57, 176, 214));
bbg.drawString("Créditos", 300, 390);
bbg.drawString("Sair", 300, 450);
case 5:
bbg.setColor(Color.orange);
bbg.drawString("Jogar", 300, 210);
bbg.setColor(Color.orange);
bbg.drawString("Scores", 300,270);
bbg.drawString("Regras",300, 330);
bbg.drawString("Créditos", 300, 390);
bbg.setColor(new Color(57, 176, 214));
bbg.drawString("Sair", 300, 450);
}
}
public void Acede_Opcoes()
{
switch(se)
{
case 1:
this.dispose();
Game jogo = new Game();
jogo.run();
break;
case 2:
this.dispose();
//Scores s = new Scores();
//s.run();
break;
case 3:
this.dispose();
//Regras regras = new Regras8);
//regras.run
break;
case 4:
this.dispose();
//Creditos creditos = new Creditos();
//Creditos.run();
break;
case 5:
System.exit(0);
break;
}
}
public void Inicializar(){
setTitle("Fruit Cutter");
setSize(JanelaX, JanelaY);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
setVisible(true);
setLocationRelativeTo(null);
backBuffer = new BufferedImage(JanelaX, JanelaY, BufferedImage.TYPE_INT_RGB);
addKeyListener(this);
Arrays.fill(TeclasPressionadas, "");
addKeyListener(this);
}
public void run(){
Inicializar();
while (true){
desenharGraficos();
try{
Thread.sleep(1000/FPS);
}catch (Exception e){
System.out.println("Thred Interrompida!");}}
}
public static void main(String[] args){
Game game = new Game();
game.run();
}
//Problem probably is here
#Override
public void keyTyped(KeyEvent e){
}
#Override
public void keyPressed(KeyEvent e){
if (e.getKeyCode()==KeyEvent.VK_DOWN)
{
c++;
if(c>5)
{
c=1;
}
if (e.getKeyCode()==KeyEvent.VK_UP)
{
c--;
if(c<1)
{
c=5;
}
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
se=c;
}
}
}
}
#Override
public void keyReleased(KeyEvent e){
if(!TeclasPressionadas[e.getKeyCode()].equals("")){
TeclasPressionadas[e.getKeyCode()] = "";}}
}
g = getGraphics(); is not how custom painting works see Painting in AWT and Swing for more information about how painting works in Swing and Performing Custom Painting for how you should work with it.
Because you've also extended from JFrame (which is generally considered a bad idea), you will end up with additional painting issues, as JFrame is a composite component (ie, it has other child components laid out on top of it)
From How to Use Root Panes
BufferedImage backBuffer; is unnecessary if you use Swing correctly, as Swing is double buffered by default.
ImageIcon Fundo = new ImageIcon("src/Imagens/fundo.jpg"); is going to cause you no end of issues when you export the project, as src won't exist. Never reference src within your code.
ImageIcon is also a poor choice, as it will fail silently, instead, prefer ImageIO.read instead.
Since the image is stored within the context of the source files, this will become an "embedded resource", meaning you can no longer reference it as a file (which is another issue with using ImageIcon the way you are), instead, you will need to use Class#getResource
However, because ImageIO.read does throw an exception, you'll have to load the image within the constructor (or some other method), for example...
private BufferedImage fundo;
public Game() throws IOException {
fundo = ImageIO.read(getClass().getResource("/Imagens/fundo.jpg"));
So, for a simple menu, you don't need a run loop, you're really not doing that much work, just let the system do it for you.
You should take the time to also have a look at:
Model–view–controller
Single Responsibility Principle
Observer Pattern
Delegation pattern
Dependency Injection; Dependency injection
All of these concepts will help you build a better solution, isolating functionality and decoupling your code.
I would start with a dedicated "menu component".
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
List<MenuItem> menuItems = new ArrayList<>();
menuItems.add(new MenuItem("Jogar", Color.BLACK, new Color(57, 176, 214)));
menuItems.add(new MenuItem("Scores", Color.BLACK, new Color(57, 176, 214)));
menuItems.add(new MenuItem("Regras", Color.BLACK, new Color(57, 176, 214)));
menuItems.add(new MenuItem("Créditos", Color.BLACK, new Color(57, 176, 214)));
menuItems.add(new MenuItem("Sair", Color.BLACK, new Color(57, 176, 214)));
JFrame frame = new JFrame();
frame.add(new MenuPane(menuItems));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MenuItem {
private String text;
private Color textColor;
private Color backgroundColor;
public MenuItem(String text, Color textColor, Color backgroundColor) {
this.text = text;
this.textColor = textColor;
this.backgroundColor = backgroundColor;
}
public String getText() {
return text;
}
public Color getTextColor() {
return textColor;
}
public Color getBackgroundColor() {
return backgroundColor;
}
}
public class MenuPane extends JPanel {
protected enum Direction {
UP, DOWN;
}
private List<MenuItem> menuItems;
private Color selectedTextColor = Color.WHITE;
private Color selectedBackgroundColor = Color.ORANGE;
private int selectedItemIndex = 0;
private int buttonWidth = 0;
private int totalButtonHeight = 0;
private BufferedImage fundo;
public MenuPane(List<MenuItem> menuItems) {
this.menuItems = menuItems;
for (MenuItem menuItem : menuItems) {
FontMetrics fm = getFontMetrics(getFont());
buttonWidth = Math.max(fm.stringWidth(menuItem.getText()) + 8, buttonWidth);
totalButtonHeight += (fm.getHeight() + 8);
}
totalButtonHeight += (menuItems.size() - 1) * 4;
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Pressed.up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "Pressed.down");
MenuInputAction.Observer observer = new MenuInputAction.Observer() {
#Override
public void menuDidNavigate(Direction direction) {
switch (direction) {
case UP:
selectedItemIndex--;
break;
case DOWN:
selectedItemIndex++;
break;
}
int count = getMenuItems().size() - 1;
if (selectedItemIndex < 0) {
selectedItemIndex = count;
} else if (selectedItemIndex > count) {
selectedItemIndex = 0;
}
repaint();
}
};
am.put("Pressed.up", new MenuInputAction(Direction.UP, observer));
am.put("Pressed.down", new MenuInputAction(Direction.DOWN, observer));
}
public Color getSelectedBackgroundColor() {
return selectedBackgroundColor;
}
public Color getSelectedTextColor() {
return selectedTextColor;
}
public void setSelectedBackgroundColor(Color selectedBackgroundColor) {
this.selectedBackgroundColor = selectedBackgroundColor;
repaint();
}
public void setSelectedTextColor(Color selectedTextColor) {
this.selectedTextColor = selectedTextColor;
repaint();
}
protected int getButtonWidth() {
return buttonWidth;
}
protected int getTotalButtonHeight() {
return totalButtonHeight;
}
public List<MenuItem> getMenuItems() {
return menuItems;
}
public int getSelectedItemIndex() {
return selectedItemIndex;
}
public MenuItem getSelectedMenuItem() {
int index = getSelectedItemIndex();
List<MenuItem> menuItems = getMenuItems();
if (index >= 0 && index < menuItems.size()) {
return menuItems.get(index);
}
return null;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(getButtonWidth() + 8, getTotalButtonHeight() + 8);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
FontMetrics fm = g2d.getFontMetrics();
int x = (getWidth() - getButtonWidth()) / 2;
int y = (getHeight() - getTotalButtonHeight()) / 2;
int buttonWidth = getButtonWidth();
int buttonHeight = fm.getHeight() + 8;
MenuItem selectedItem = getSelectedMenuItem();
for (MenuItem menuItem : menuItems) {
paintButton(g2d, menuItem, x, y, buttonWidth, buttonHeight, menuItem == selectedItem);
y += buttonHeight + 4;
}
g2d.dispose();
}
protected void paintButton(Graphics2D g2d, MenuItem menuItem, int x, int y, int width, int height, boolean isSelected) {
Color backgroundColor = menuItem.getBackgroundColor();
Color textColor = menuItem.getTextColor();
if (isSelected) {
backgroundColor = getSelectedBackgroundColor();
textColor = getSelectedTextColor();
}
g2d.setColor(backgroundColor);
g2d.fillRect(x, y, width, height);
FontMetrics fm = g2d.getFontMetrics();
int textX = x + ((width - fm.stringWidth(menuItem.getText())) / 2);
int textY = y + ((height - fm.getHeight()) / 2) + fm.getAscent();
g2d.setColor(textColor);
g2d.drawString(menuItem.getText(), textX, textY);
}
protected class MenuInputAction extends AbstractAction {
protected interface Observer {
public void menuDidNavigate(Direction direction);
}
private Direction direction;
private Observer observer;
public MenuInputAction(Direction direction, Observer observer) {
this.direction = direction;
this.observer = observer;
}
#Override
public void actionPerformed(ActionEvent e) {
observer.menuDidNavigate(direction);
}
}
}
}
So, what's missing? A trigger callback, how does the caller know when a menu item is selected?
Well, this is up to you now. I would...
Add an observer callback to notify the caller that some menu item has been selected/actioned
Add a key binding for the Enter key and a MouseListener to detect when the user clicks an item - however, this is going to present you with issues, as you need to dynamically calculate the button bounds (I might consider doing this up-front). You can do basic collision detection using Rectangle#contains

BasicScrollBarUI? How to use it

I am working on a code editor for Minecraft, and I am not very happy with the normal UI design in Java. I managed to change the buttons, but it doesn't really work for scroll bars. Could you please help me?
This is my ButtonUI class.
public class UIButton extends BasicButtonUI implements MouseListener {
private Color hoverColor;
private Color normalColor;
private Color pressedColor;
public UIButton(ColorSheme cs) {
super();
if (cs == ColorSheme.WHITE_BLUE_GRAY) {
hoverColor = new Color(212, 211, 255);
normalColor = new Color(184, 183, 206);
pressedColor = new Color(197, 196, 228);
}else if (cs == ColorSheme.GREEN_GRAY) {
hoverColor = new Color(22, 179, 103);
normalColor = new Color(9, 126, 101);
pressedColor = new Color(17, 158, 102);
}else if (cs == ColorSheme.RED_GRAY) {
hoverColor = new Color(204, 86, 88);
normalColor = new Color(171, 79, 91);
pressedColor = new Color(187, 82, 90);
}else if (cs == ColorSheme.BLUE_GRAY) {
hoverColor = new Color(126, 176, 191);
normalColor = new Color(104, 134, 179);
pressedColor = new Color(111, 148, 183);
}
}
#Override
public void installUI(JComponent c) {
super.installUI(c);
c.addMouseListener(this);
c.setBorder(null);
c.setFont(Main.getDefaultFont());
}
#Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removeMouseListener(this);
}
#Override
protected void installDefaults(AbstractButton b) {
super.installDefaults(b);
changeButtonColor((JButton) b, normalColor);
}
#Override
public void mouseClicked(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), hoverColor);
}
#Override
public void mousePressed(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), pressedColor);
}
#Override
public void mouseReleased(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), normalColor);
}
#Override
public void mouseEntered(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), hoverColor);
}
#Override
public void mouseExited(MouseEvent e) {
changeButtonColor((JButton) e.getComponent(), normalColor);
}
private void changeButtonColor(JButton b, Color c) {
b.setBackground(c);
}
}
And this is my UIScrollBarUI class.
public class UIScrollBar extends BasicScrollBarUI implements MouseListener {
private Color hoverColor;
private Color normalColor;
private Color pressedColor;
public UIScrollBar(ColorSheme cs) {
super();
if (cs == ColorSheme.WHITE_BLUE_GRAY) {
hoverColor = new Color(212, 211, 255);
normalColor = new Color(184, 183, 206);
pressedColor = new Color(197, 196, 228);
}else if (cs == ColorSheme.GREEN_GRAY) {
hoverColor = new Color(22, 179, 103);
normalColor = new Color(9, 126, 101);
pressedColor = new Color(17, 158, 102);
}else if (cs == ColorSheme.RED_GRAY) {
hoverColor = new Color(204, 86, 88);
normalColor = new Color(171, 79, 91);
pressedColor = new Color(187, 82, 90);
}else if (cs == ColorSheme.BLUE_GRAY) {
hoverColor = new Color(126, 176, 191);
normalColor = new Color(104, 134, 179);
pressedColor = new Color(111, 148, 183);
}
}
#Override
public void installUI(JComponent c) {
super.installUI(c);
c.addMouseListener(this);
c.setBorder(null);
}
#Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removeMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
System.out.print("Entered");
changeBarColor(e.getComponent(), hoverColor);
}
#Override
public void mouseExited(MouseEvent e) {
System.out.print("Exited");
}
private void changeBarColor(Component c, Color co) {
c.setBackground(co);
}
}
First of all, if you are not happy with the "normal" UI design, you should consider changing Look And Feel.
I personally hate MetalLookAndFeel, and i'm used to set a system dependent look and feel for my swing applications.
Check this link for further details.
If you just want to change track and/or thumb color, you can override BasicScrollBarUI paintThumb and paintTrack methods.
Scrollbar's buttons can be changed as well.
Try this example (screenshot below):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class Main
{
public static void main (String [] a) {
SwingUtilities.invokeLater (new Runnable () {
#Override public void run () {
try {
UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName ());
createAndShowGUI ();
}
catch (Exception e) {
JOptionPane.showMessageDialog (null, "An unexpected error occurred : " + e.getClass ().getSimpleName (), "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
private static void createAndShowGUI () {
JFrame frame = new JFrame ("Test ScrollBar");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setContentPane (new CustomScrollPane ());
frame.pack ();
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
}
class CustomScrollPane extends JScrollPane
{
public CustomScrollPane () {
super (VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_ALWAYS);
Image imageThumb = createImage (16, 16, Color.RED);
Image imageThumbPressed = createImage (16, 16, Color.MAGENTA);
Image imageTrack = createImage (16, 16, Color.YELLOW);
// Adding some test labels
JPanel view = new JPanel (new GridLayout (10, 5, 20, 50));
for (int i = 0; i < 50; i++) view.add (new JLabel ("Test Label " + String.valueOf (i)));
setViewportView (view);
setHorizontalScrollBar (new CustomScrollBar (JScrollBar.HORIZONTAL, imageThumb, imageThumbPressed, imageTrack));
setVerticalScrollBar (new CustomScrollBar (JScrollBar.VERTICAL, imageThumb, imageThumbPressed, imageTrack));
// Setting preferred size for convenience. Not a good practice !
setPreferredSize (new Dimension (200, 200));
}
private Image createImage (int width, int height, Color color) {
BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics ();
g.setColor (color);
g.fillRect (0, 0, width, height);
g.dispose ();
return image;
}
}
class CustomScrollBar extends JScrollBar
{
private boolean isThumbPressed;
public CustomScrollBar (final int orientation, final Image thumb, final Image thumbPressed, final Image track) {
super (orientation);
addMouseListener (new MouseAdapter () {
public void mousePressed (MouseEvent e) {
isThumbPressed = true;
}
public void mouseReleased (MouseEvent e) {
isThumbPressed = false;
}
});
setUI (new BasicScrollBarUI () {
#Override protected void paintThumb (Graphics g, JComponent c, Rectangle r) {
if (isThumbPressed) g.drawImage (thumbPressed, r.x, r.y, r.width, r.height, null);
else g.drawImage (thumb, r.x, r.y, r.width, r.height, null);
}
#Override protected void paintTrack (Graphics g, JComponent c, Rectangle r) {
g.drawImage(track, r.x, r.y, r.width, r.height, null);
}
});
}
}

ActionListener only responding once

I have created a basic Roulette wheel in Java, and I have a JButton with an ActionListener that spins the wheel. Once I have pressed the button once, it works as intended.
The problem is: Once I press the JButton a second time, it no longer works. I will post my entire code, for anyone who wants to see exactly what I mean.
Bonus Points: Bonus points to whoever can help me with the following things:
Buttons don't appear until after you have either clicked them, or put the window in the background and brought it back up.
For some reason, the spin ALWAYS lands on red. I have a method called randomSpin() which produces an int that is either 21 or 22, and that method DOES work, but for some reason when it's used in the spin method , it always spins 21 times.
WheelBuilder
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.lang.*;
public class WheelBuilder extends JApplet{
public int total = 1000, score, Tbet = 100, last;
public JLabel winning;
public JButton spin, Abet, Sbet;
RouletteWheel wheel = new RouletteWheel();
Graphics page;
public Color color;
public void init()
{
resize(540,600);
spin = new JButton("SPIN!");
spin.addActionListener(new spinListener());
Container cp = getContentPane();
cp.setVisible(true);
cp.setBackground((Color.GREEN).darker().darker());
Abet = new JButton("+BET+");
Abet.addActionListener(new aListener());
Sbet = new JButton("-BET-");
Sbet.addActionListener(new sListener());
cp.add(Sbet);
cp.add(spin);
cp.add(Abet);
cp.setLayout(new FlowLayout(270, 5, 525));
}
public void paint(Graphics page)
{
page.setColor((Color.GREEN).darker().darker());
page.fillRect(0, 0, 1000, 1000);
setBackground((Color.GREEN).darker().darker());
wheel.paintWheel(page, wheel.getStatus());
page.setColor(Color.BLACK);
page.drawString("TOTAL: "+total, 400, 50);
page.drawString("Current Bet: "+Tbet, 400, 25);
page.drawString("Last Spin:", 50, 25);
page.setColor(Color.WHITE);
page.fillOval(260, 75, 20, 20);
page.fillRect(50, 35, 60, 25);
page.setColor(color);
page.drawString(""+last, 70, 52);
}
public class spinListener implements ActionListener
{
Timer tm = new Timer(100, this);
int count = 0;
int countEnd = randomSpin();
public void actionPerformed(ActionEvent e)
{
tm.start();
changeWheel();
if (wheel.getStatus())
{
color = Color.RED;
last = (int)(Math.random()*7)*2+1;
}
else
{
color = Color.BLACK;
last = (int)(Math.random()*7)*2+2;
}
}
public void changeWheel()
{
int countEnd = randomSpin();
if (count <= countEnd)
{
wheel.setStatus(!(wheel.getStatus()));
repaint();
count++;
}
}
public int randomSpin()
{
return ((int)(Math.random()*2)+21);
}
}
public class aListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet <= total-50)
{
Tbet+=50;
}
last = 0;
repaint();
}
}
public class sListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Tbet > 50)
{
Tbet-=50;
}
last = 0;
repaint();
}
}
}
RouletteWheel
import javax.swing.JApplet;
import java.awt.*;
public class RouletteWheel extends JApplet {
public boolean status;
public void paintWheel(Graphics page, boolean status)
{
if (status){
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.BLACK);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.setColor(Color.RED);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
if (!status)
{
setBackground(Color.green);
page.setColor(Color.orange.darker().darker());
page.fillOval(20, 20, 500, 500);
page.setColor(Color.WHITE);
page.drawOval(40, 40, 460, 460);
page.setColor(Color.RED);
int[] xback = {0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70,240+70,160+70,90+70,30+70};
int[] yback = {240+70,160+70,90+70,30+70,0+70,0+70,30+70,90+70,160+70,240+70,310+70,370+70,400+70,400+70,370+70,310+70};
page.fillPolygon(xback, yback, 16);
int[] xvals = {0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70,240+70,160+70,200+70,90+70,30+70,200+70};
int[] yvals = {240+70,160+70,200+70,90+70,30+70,200+70,0+70,0+70,200+70,30+70,90+70,200+70,160+70,240+70,200+70,310+70,370+70,200+70,400+70,400+70,200+70,370+70,310+70,200+70};
page.setColor(Color.BLACK);
page.fillPolygon(xvals, yvals, 24);
page.setColor(Color.orange.darker().darker());
page.fillOval(140, 140, 260, 260);
page.setColor(Color.lightGray);
page.fillOval(220, 220, 100, 100);
page.setColor(Color.GRAY);
page.fillOval(240, 240, 60, 60);
page.setColor(Color.DARK_GRAY);
page.fillOval(260, 260, 20, 20);
page.setColor(Color.WHITE);
page.drawOval(100, 100, 340, 340);
page.drawOval(110, 110, 320, 320);
}
}
public boolean getStatus()
{
return status;
}
public void setStatus(boolean s)
{
status = s;
}
}

Create basic animation

How can I create basic animation in Java?
Currently i am trying to implement a basic animation program using swing in Java.
But i am not getting whether my logic for program in correct or not.
My program implements Runnable, ActionListener interfaces and also extends JApplet.
I want to know that, is it necessary to differentiate start method of JApplet and Runnable?
And if yes then why..?
My program is basic balloon program, when I click on start button balloons start moving upward and comes to floor again. This will be continue till i press stop button.
Here is my code.
public class Balls extends JApplet implements Runnable{
private static final long serialVersionUID = 1L;
JPanel btnPanel=new JPanel();
static boolean flag1=true;
static boolean flag2=true;
static boolean flag3=false;
static int h;
static int temp=10;
Thread t=new Thread(this);
JButton start;
JButton stop;
public void init()
{
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't create GUI because of exception");
System.exit(0);
}
}
private void makeGUI() {
start=new JButton("start");
stop=new JButton("stop");
btnPanel.add(start);
btnPanel.add(stop);
add(btnPanel,BorderLayout.NORTH);
}
public void run()
{
while(true)
{
if(flag1)
{
repaint();
flag1=false;
}
else
{
try
{
wait();
flag3=true;
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"Error ocuured !!\n Exiting..");
System.exit(0);
}
}
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int h=Integer.parseInt(getParameter("height"));
if (flag1)
{
g.setColor(Color.RED);
g.fillOval(10,h,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,h,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h,60,40);
g.setColor(Color.pink);
g.fillOval(370,h,65,45);
flag1=false;
}
else
{
g.setColor(Color.RED);
g.fillOval(10,h-temp,50,50);
g.setColor(Color.YELLOW);
g.fillOval(50,h-temp,20,20);
g.setColor(Color.CYAN);
g.fillOval(70,h-temp,80,30);
g.setColor(Color.BLUE);
g.fillOval(120,355,50,60);
g.setColor(Color.GRAY);
g.fillOval(160,h-temp,70,50);
g.setColor(Color.GREEN);
g.fillOval(200,h-temp,80,80);
g.setColor(Color.MAGENTA);
g.fillOval(260,h-temp,80,30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320,h-temp,60,40);
g.setColor(Color.pink);
g.fillOval(370,h-temp,65,45);
if(flag2 && temp<=400)
{
temp+=10;
if(temp==400)
{
flag2=false;
}
}
else if(!flag2)
{
temp-=10;
if(temp==10)
{
flag2=true;
}
}
else
{
}
}
}
public void start()
{
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.start();
if(flag3)
{
notify();
}
}
});
stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag1=false;
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
repaint();
t=null;
}
}
});
}
}
1) Use SwingTimer as recommended instead of your Runnable implementation.
2) Read about custom painting , and here
3) draw at the JPanel instead of on JFrame
I have changed your code, examine it. I think, that it does what you want.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Balls extends JApplet {
private static final long serialVersionUID = 1L;
JPanel btnPanel = new JPanel();
static boolean flag1 = true;
static boolean flag2 = true;
static boolean flag3 = false;
static int h;
static int temp = 10;
JButton start;
JButton stop;
private Timer timer;
public void init() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
makeGUI();
}
});
}
private void makeGUI() {
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
});
start = new JButton("start");
stop = new JButton("stop");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
timer.stop();
}
});
btnPanel.add(start);
btnPanel.add(stop);
add(new MyPanel(), BorderLayout.CENTER);
add(btnPanel, BorderLayout.NORTH);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
int h = Integer.parseInt(getParameter("height"));
if (flag1) {
g.setColor(Color.RED);
g.fillOval(10, h, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, h, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h, 65, 45);
flag1 = false;
} else {
g.setColor(Color.RED);
g.fillOval(10, h - temp, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(50, h - temp, 20, 20);
g.setColor(Color.CYAN);
g.fillOval(70, h - temp, 80, 30);
g.setColor(Color.BLUE);
g.fillOval(120, 355, 50, 60);
g.setColor(Color.GRAY);
g.fillOval(160, h - temp, 70, 50);
g.setColor(Color.GREEN);
g.fillOval(200, h - temp, 80, 80);
g.setColor(Color.MAGENTA);
g.fillOval(260, h - temp, 80, 30);
g.setColor(Color.DARK_GRAY);
g.fillOval(320, h - temp, 60, 40);
g.setColor(Color.pink);
g.fillOval(370, h - temp, 65, 45);
if (flag2 && temp <= 400) {
temp += 10;
if (temp == 400) {
flag2 = false;
}
} else if (!flag2) {
temp -= 10;
if (temp == 10) {
flag2 = true;
}
} else {
}
}
}
}
}

Why isn't this keyListener Working? How can i get it to work?

So I have my keyListener called TAdapter. For some reason i can't get this to work right. I have set the focus to the panel and it still doesnt work. I have searched and searched the web and found absolutely nothing on why this isn't working correctly. I'm new to java and completely stumped
import java.awt.*;
import javax.swing.JPanel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.TimerTask;
import java.util.Timer;
import java.awt.Toolkit;
public class Game extends JPanel implements Shared{
private static Brick bricks[];
private static Ball ball;
private static Paddle paddle;
Timer timer;
public Game(){
super();
this.addKeyListener(new TAdapter());
this.setFocusable(true);
this.requestFocusInWindow();
setSize(Shared.WIDTH, Shared.HEIGHT);
bricks = new Brick[100];
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), 1000, 10);
}
public void addNotify(){
super.addNotify();
gameInit();
}
public static void gameInit(){
ball = new Ball();
paddle = new Paddle();
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.GREEN, true);
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
switch(i){
case 0:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 255), true);
break;
case 1:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 20, 127), true);
break;
case 2:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 0, 0), true);
break;
case 3:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 127, 0), true);
break;
case 4:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(255, 255, 0), true);
break;
case 5:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 0), true);
break;
case 6:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 255, 127), true);
break;
case 7:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 127, 255), true);
break;
case 8:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(0, 0, 255), true);
break;
case 9:
gp = new GradientPaint(75, 75, Color.DARK_GRAY, 95, 95, new Color(127, 0, 255), true);
break;
}
bricks[k] = new Brick((j*BRICK_WIDTH) + (j*BRICK_SEP), (i*BRICK_HEIGHT) + BRICK_Y_OFFSET+(i*BRICK_SEP), gp);
k++;
}
}
}
public void paint(Graphics g){
super.paint(g);
GradientPaint gp = new GradientPaint(75, 75, Color.BLACK, 95, 95, Color.RED, true);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(gp);
g2.fillOval(ball.getX(), ball.getY(), BALL_RADIUS, BALL_RADIUS);
g2.fillRoundRect((Shared.WIDTH/2) - PADDLE_WIDTH/2, Shared.HEIGHT - PADDLE_Y_OFFSET*2, PADDLE_WIDTH, PADDLE_HEIGHT, 3, 3);
for(int i = 0; i< 100; i++){
if(!bricks[i].isDestroyed()){
g2.setPaint(bricks[i].getPaint());
g2.fillRoundRect(bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), 5, 5);
}
}
Toolkit.getDefaultToolkit().sync();
g2.dispose();
}
private class TAdapter extends KeyAdapter{
public void keyReleased(KeyEvent e){
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e){
paddle.keyPressed(e);
}
}
class ScheduleTask extends TimerTask{
public void run(){
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
public void stopGame(){
timer.cancel();
}
public void checkCollision() {
if (ball.getRect().getMaxY() > Shared.HEIGHT) {
stopGame();
}
for (int i = 0, j = 0; i < 100; i++) {
if (bricks[i].isDestroyed()) {
j++;
}
if (j == 100) {
stopGame();
}
}
if ((ball.getRect()).intersects(paddle.getRect())) {
int paddleLPos = (int)paddle.getRect().getMinX();
int ballLPos = (int)ball.getRect().getMinX();
int first = paddleLPos + 8;
int second = paddleLPos + 16;
int third = paddleLPos + 24;
int fourth = paddleLPos + 32;
if (ballLPos < first) {
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballLPos >= first && ballLPos < second) {
ball.setXDir(-1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos >= second && ballLPos < third) {
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballLPos >= third && ballLPos < fourth) {
ball.setXDir(1);
ball.setYDir(-1 * ball.getYDir());
}
if (ballLPos > fourth) {
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < 100; i++) {
if ((ball.getRect()).intersects(bricks[i].getRect())) {
int ballLeft = (int)ball.getRect().getMinX();
int ballHeight = (int)ball.getRect().getHeight();
int ballWidth = (int)ball.getRect().getWidth();
int ballTop = (int)ball.getRect().getMinY();
Point pointRight =
new Point(ballLeft + ballWidth + 1, ballTop);
Point pointLeft = new Point(ballLeft - 1, ballTop);
Point pointTop = new Point(ballLeft, ballTop - 1);
Point pointBottom =
new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDestroyed()) {
if (bricks[i].getRect().contains(pointRight)) {
ball.setXDir(-1);
}
else if (bricks[i].getRect().contains(pointLeft)) {
ball.setXDir(1);
}
if (bricks[i].getRect().contains(pointTop)) {
ball.setYDir(1);
}
else if (bricks[i].getRect().contains(pointBottom)) {
ball.setYDir(-1);
}
bricks[i].setDestroyed(true);
}
}
}
}
}`
then here is the main
import javax.swing.*;
public class BreakOut extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
static Game game =new Game();
public BreakOut()
{
add(game);
setTitle("Breakout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(Shared.WIDTH, Shared.HEIGHT);
setResizable(false);
setVisible(true);
setIgnoreRepaint(true);
}
public static void main(String arg[]){
new BreakOut();a
}
}
Your key listener just sends the events to paddle.
You might want to include the code (or at least look in the code) for paddle.keyPressed(e) and paddle.keyReleased(e); but really, you probably shouldn't have your paddle object handling the keys directly. It is nice to translate your key presses to in-game meaningful calls, like paddle.moveUp() or something.
Im not sure where the shared interface comes from/does, but try implementing KeyListener. "Public class Game extends JPanel implements Shared, KeyListner" if you keep using the shared but like i said idk what its purpose is or what it does right off the top of my head.

Categories

Resources