Hold button for spinning images - java

I'm trying to create a hold button on Java for my bandit machine, when pressed it will hold that image and the other 2 images will keep spinning. Anyone know the code to allow that to happen?
if (e.getSource()== btnaddcash){
txtbalance.setForeground(Color.red);
cash = cash + 100;
txtbalance.setText(cash + "");
if (e.getSource() == btnpic1){

The basic concept is, you want to spin an image (or take some action) while the button is "armed".
A way by which you can achieve this is to add a ChangeListener to the button and monitor the ButtonModel#isArmed state.
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SlotPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SlotPaneextends JPanel {
private SpinPane spinPane;
private JButton button;
public SlotPane() {
spinPane = new SpinPane();
button = new JButton("Press");
// I've attached directly to the model, I don't
// think this is required, simply attaching a change
// listener to the button achieve the same result.
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
spinPane.setSpinning(button.getModel().isArmed());
}
});
setLayout(new BorderLayout());
add(spinPane);
add(button, BorderLayout.SOUTH);
}
}
public class SpinPane extends JPanel {
private BufferedImage mole;
private Timer timer;
private float angel = 0;
public SpinPane() {
try {
mole = ImageIO.read(new File("mole.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angel += 15;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return mole == null ? super.getPreferredSize() : new Dimension(mole.getWidth(), mole.getHeight());
}
public void setSpinning(boolean spinning) {
if (spinning) {
if (!timer.isRunning()) {
timer.restart();
}
} else {
timer.stop();
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mole != null) {
int x = (getWidth() - mole.getWidth()) / 2;
int y = (getHeight() - mole.getHeight()) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angel), getWidth() / 2, getHeight() / 2));
g2d.drawImage(mole, x, y, this);
g2d.dispose();
}
}
}
}

Related

The image not showing up in JFrame after adding the movement

I am trying to make a PacMan alternative with a tiger chasing bagels (don't ask why). I'm on the first stage still, trying to make the tiger move around the JFrame. However, now that I implemented the KeyEvent, the image is no longer showing up. I have been stuck on this for an hour, and I don't understand where I went wrong.
Edit: I have got the image to show up, but the image does not update or change location when pressing on the arrow keys, probably something to do with the connection between the KeyEvent and the PacMan class.
Main:
public Main() {
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
UI frame = null;
try {
frame = new UI();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
});
}
UI:
public PacMan PacMan;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT){
PacMan.moveRight();
}
if (key == KeyEvent.VK_LEFT){
PacMan.moveLeft();
}
if (key == KeyEvent.VK_UP){
PacMan.moveUp();
}
if (key == KeyEvent.VK_DOWN){
PacMan.moveDown();
}
}
public UI() throws IOException {
this.PacMan = new PacMan();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setTitle("PacMan");
frame.setResizable(false);
frame.setSize(1200, 700);
frame.setMinimumSize(new Dimension(1200, 700));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBackground(Color.BLACK);
panel.add(PacMan.getImage());
frame.add(panel);
frame.setVisible(true);
}
PacMan:
public int xCoords = 570;
public int yCoords = 320;
JLabel pacManImage = new JLabel();
Icon tigerLeft;
Icon tigerRight;
public PacMan() throws IOException {
ImageIcon tigerLeft = new ImageIcon(new ImageIcon("textures/tigerLeft.png").getImage().getScaledInstance(60, 40, Image.SCALE_DEFAULT));
ImageIcon tigerRight = new ImageIcon(new ImageIcon("textures/tigerRight.png").getImage().getScaledInstance(60, 40, Image.SCALE_DEFAULT));
pacManImage.setIcon(tigerRight);
pacManImage.setVisible(true);
}
public void initialDraw() {
pacManImage.setBounds(xCoords, yCoords, 60, 40);
pacManImage.setIcon(tigerRight);
pacManImage.repaint();
}
public void moveRight() {
System.out.println("here: " + tigerRight);
//xCoords = xCoords + 2;
pacManImage.setIcon(tigerRight);
pacManImage.setLocation(pacManImage.getLocationOnScreen().x + 2, pacManImage.getLocationOnScreen().y);
pacManImage.repaint();
}
public void moveLeft() {
//xCoords = xCoords + 2;
pacManImage.setIcon(tigerLeft);
pacManImage.setLocation(pacManImage.getLocationOnScreen().x - 2, pacManImage.getLocationOnScreen().y);
pacManImage.repaint();
}
public void moveUp() {
//yCoords = yCoords + 2;
pacManImage.setLocation(pacManImage.getLocationOnScreen().x, pacManImage.getLocationOnScreen().y - 2);
pacManImage.repaint();
}
public void moveDown() {
//yCoords = yCoords + 2;
pacManImage.setLocation(pacManImage.getLocationOnScreen().x, pacManImage.getLocationOnScreen().y + 2);
pacManImage.repaint();
}
public JLabel getImage(){
return pacManImage;
}
Your UI class is not complete so I can't tell exactly what you are doing. I can only guess.
Ignoring the actual KeyListener code, my guess is you have code like:
public class UI extends JPanel
{
public UI() throws IOException
{
this.PacMan = new PacMan();
addKeyListener(this);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.add(PacMan.getImage());
frame.add(panel);
frame.setVisible(true);
}
}
So once again you have two JPanel components:
the UI class "is a" JPanel and you add the KeyListener to it.
then you create a second JPanel and add the "PacMan" to that panel and add that panel to the frame.
So the problem is the first panel has the KeyListener but it is never added to the frame.
Your class should look like:
public class UI extends JPanel
{
public UI() throws IOException
{
this.PacMan = new PacMan();
addKeyListener(this);
setBackground(Color.BLACK);
add(PacMan.getImage());
}
}
That's it. The creation of the frame does not belong in this class.
I found out that my keyReleased function was never being called, and I fixed that issue by issuing the simplest fix, moving the KeyListener within the UI method.
UI class code:
public class UI extends JPanel {
public PacMan PacMan;
public UI() throws IOException {
this.PacMan = new PacMan();
addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN){
PacMan.moveDown();
}
if (e.getKeyCode() == KeyEvent.VK_UP){
PacMan.moveUp();
}
if (e.getKeyCode() == KeyEvent.VK_LEFT){
PacMan.moveLeft();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
PacMan.moveRight();
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
});
setFocusable(true);
setBackground(Color.BLACK);
add(PacMan.getImage());
}

How to implement a KeyListener to an object in a JFrame?

I'm attempting to make Frogger in java for a school project but I'm having a lot of difficulties setting up KeyListener for the actual frog character.
I've tried setting up key bindings, requesting focus for the JPanel and JFrame, moving around where the character is initiated but nothing has seemed to work. This is the remnants of my attempts.
This is the program that runs my game.
import javax.swing.*;
public class Frogger
{
JFrame frame = new JFrame("Frogger");
CPT c = new CPT();
public Frogger()
{
frame.setBounds(0,0,700,500);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(c);
}
public static void main(String[] args){
new Frogger();
}
}
The main game
public CPT() {
setLayout(new BorderLayout());
label = new JLabel("Frogger");
frame1 = new JFrame("Main");
label.setFont(new Font("Serif", Font.BOLD,50));
label.setBounds(275,10,250,250);
button1 = new JButton("PLAY");
button1.setBounds(300,350,100,50);
button1.setOpaque(false);
button1.setVisible(true);
this.setOpaque(false);
this.setLayout(null);
this.add(label);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(700,500);
frame1.setResizable(false);
frame1.setFocusable(false);
button1.setVisible(false);
frame1.add(new TrainCanvas());
frame1.add(p1);
p1.requestFocus();
}
});
this.add(button1); }
This is the TrainCanvas class that Draws the cars in the games as well as the frog
class TrainCanvas extends JComponent
{
private int lastX = 0;
private int lastX_1 = 0;
private int lastX_2 = 0;
public TrainCanvas() {
Thread animationThread = new Thread(new Runnable() {
public void run() {
while (true) {
repaint();
try {Thread.sleep(10);} catch (Exception ex) {}
}
}
});
animationThread.start();
}
public void paintComponent(Graphics g) {
Graphics2D gg = (Graphics2D) g;
//Draws Train 1
int w = getWidth();
int h = getHeight();
int trainW_1 = 100;
int trainH_1 = 5;
int trainSpeed_1 = 3;
int x = lastX + trainSpeed_1;
if (x > w + trainW_1) {
x = -trainW_1;
}
gg.setColor(Color.BLACK);
gg.fillRect(x, h/2 + trainH_1, trainW_1, trainH_1);
lastX = x;
Graphics2D g3 = (Graphics2D) g;
frog = new Rectangle(f_x,f_y,25,25);
g3.fill(frog);
g3.setColor(Color.GREEN);
}
}
Finally, the Key Listener
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()== KeyEvent.VK_UP)
{
CPT.f_y -= 100;
repaint();
}
else if(e.getKeyCode()== KeyEvent.VK_RIGHT)
{
CPT.f_x += 100;
repaint();
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
CPT.f_x -= 100;
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
CPT.f_y += 100;
repaint();
}
else {}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
The program runs perfectly fine without giving me any errors, which is making this troublesome. Whenever it gets to the main game window, none of the keys seem to work.

Cannot find symbol error. java

I am running the following code and i am getting a cannot find symbol error at resultPane.setResult(0); am i putting the new handlerclass in wrong spot? ive tried putting
it in different spots but nothing
public class MovingLabel {
public static void main(String[] args) {
new MovingLabel();
}
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
ResultPane resultPane = new ResultPane();
JFrame frame = new JFrame("Testing");
frame.setGlassPane(resultPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new NewPane(resultPane));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setBounds(500,300,200,200);
}
});
}
public class ResultPane extends JPanel {
private JLabel result;
private Timer timer;
private int xDelta = (Math.random() > 0.5) ? 1 : -1;
private int yDelta = (Math.random() > 0.5) ? 1 : -1;
public ResultPane() {
setOpaque(false);
setLayout(null);
result = new JLabel();
Font font = result.getFont();
font = font.deriveFont(Font.BOLD, 26f);
result.setFont(font);
add(result);
HandlerClass handler = new HandlerClass();
result.addMouseListener(handler);
result.addMouseMotionListener(handler);
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point point = result.getLocation();
point.x += xDelta;
point.y += yDelta;
if (point.x < 0) {
point.x = 0;
xDelta *= -1;
} else if (point.x + result.getWidth() > getWidth()) {
point.x = getWidth() - result.getWidth();
xDelta *= -1;
}
if (point.y < 0) {
point.y = 0;
yDelta *= -1;
} else if (point.y + result.getHeight() > getHeight()) {
point.y = getHeight() - result.getHeight();
yDelta *= -1;
}
result.setLocation(point);
repaint();
}
});
timer.start();
}
public void setResult(Number number) {
result.setText(NumberFormat.getNumberInstance().format(number));
result.setSize(result.getPreferredSize());
setVisible(true);
}
}
public class NewPane extends JPanel {
private final ResultPane resultPane;
public NewPane(ResultPane resultPane) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
this.resultPane = resultPane;
JPanel buttons = new JPanel();
buttons.add(new JButton(new LabelAction()));
add(buttons, gbc);
}
public class LabelAction extends AbstractAction {
LabelAction() {
putValue(NAME, "Label");
}
#Override
public void actionPerformed(ActionEvent e) {
resultPane.setResult(123);
}
}
}
private class HandlerClass implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent event) {
resultPane.setResult(0);
}
public void mouseReleased(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseMoved(MouseEvent event) {
}
public void mouseDragged(MouseEvent event){
}
}
}
resultPane is only defined in the scope of run(). If you want HandlerClass to have access to it you need to give it a definition.
Make resultPane instance variable. You can't access local variable outside the method.
class MovingLabel {
private ResultPane resultPane; // Declare it as instance variable
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
...
resultPane = new ResultPane(); // Initialize the instance variable
...
}
}
}
It's a nice program.
Personally, I put every class in a new file. For me it easier to understand scope. The problem is indeed that the reference in HandlerClass is outside of it's declaration in the other classes.

JInternalFrame image bag

I have a program, with JFrame and JInternalFrames inside. So, when I try to set background with this code:
BufferedImage myImage;
myImage = ImageIO.read(new File("C:/5/JavaLibrary2/background.jpg"));
ImagePanel Image = new ImagePanel(myImage);
frame.setContentPane(Image);
My JInternalFrames just gone. So, see a short video with debug
frame.setContentPane(Image); just delete my JInternal windows.
I have no issue.
I've used both a JLabel and custom painting routines.
I've created and setup the internal frames BEFORE adding them to the desktop,
I've added the internal frame to the desktop and THEN changed their content panes as well as throwing the update to the end of the EDT to ensure that the main frame is visible.
The problem must be in some part of your code you're not showing us.
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JDesktopPane desktop = new JDesktopPane();
final JInternalFrame frame1 = new JInternalFrame("Image on Label");
// frame1.setContentPane(new LabelImagePane());
// frame1.pack();
// frame1.setLocation(0, 0);
frame1.setVisible(true);
desktop.add(frame1);
final JInternalFrame frame2 = new JInternalFrame("Painted Image");
// frame2.setContentPane(new ImagePane());
// frame2.pack();
// frame2.setLocation(frame1.getWidth(), 0);
frame2.setVisible(true);
desktop.add(frame2);
JFrame frame = new JFrame("I Haz Images");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(desktop);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame1.setContentPane(new LabelImagePane());
frame1.pack();
frame1.setLocation(0, 0);
frame2.setContentPane(new ImagePane());
frame2.pack();
frame2.setLocation(frame1.getWidth(), 0);
}
});
}
});
}
public class LabelImagePane extends JPanel {
public LabelImagePane() {
setLayout(new BorderLayout());
JLabel label = new JLabel();
add(label);
try {
label.setIcon(new ImageIcon(ImageIO.read(new File("..."))));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImagePane extends JPanel {
private BufferedImage image;
public ImagePane() {
try {
image = ImageIO.read(new File("..."));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}

Changing Swing GUI Default Look and Feel in real time

Before showing the GUI, if i have a code block like this:
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("GTK+".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {}
Here for example, i am using theme GTK+ in ubunut. Other options like Nimbus etc can be used. Now once i launch the app, it loads and show this theme. But is there anyway i can change the theme in real time. Because if i change it i have to close the GUI and load it again with new theme?
Is possible change Look and Feel on Runtime by invoke SwingUtilities#updateComponentTreeUI, for example
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class ButtonTest {
private JFrame frame;
private JButton opaqueButton1;
private JButton opaqueButton2;
private SoftJButton softButton1;
private SoftJButton softButton2;
private Timer alphaChanger;
public void createAndShowGUI() {
opaqueButton1 = new JButton("Opaque Button");
opaqueButton2 = new JButton("Opaque Button");
softButton1 = new SoftJButton("Transparent Button");
softButton2 = new SoftJButton("Transparent Button");
opaqueButton1.setBackground(Color.GREEN);
softButton1.setBackground(Color.GREEN);
frame = new JFrame();
frame.getContentPane().setLayout(new java.awt.GridLayout(2, 2, 10, 10));
frame.add(opaqueButton1);
frame.add(softButton1);
frame.add(opaqueButton2);
frame.add(softButton2);
frame.setSize(700, 300);
frame.setLocation(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
alphaChanger = new Timer(30, new ActionListener() {
private float incrementer = -.03f;
#Override
public void actionPerformed(ActionEvent e) {
float newAlpha = softButton1.getAlpha() + incrementer;
if (newAlpha < 0) {
newAlpha = 0;
incrementer = -incrementer;
} else if (newAlpha > 1f) {
newAlpha = 1f;
incrementer = -incrementer;
}
softButton1.setAlpha(newAlpha);
softButton2.setAlpha(newAlpha);
}
});
alphaChanger.start();
Timer uiChanger = new Timer(3500, new ActionListener() {
private final LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
private int index = 1;
#Override
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(laf[index].getClassName());
SwingUtilities.updateComponentTreeUI(frame);
opaqueButton1.setText(laf[index].getClassName());
softButton1.setText(laf[index].getClassName());
} catch (Exception exc) {
exc.printStackTrace();
}
index = (index + 1) % laf.length;
}
});
uiChanger.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonTest().createAndShowGUI();
}
});
}
private static class SoftJButton extends JButton {
private static final JButton lafDeterminer = new JButton();
private static final long serialVersionUID = 1L;
private boolean rectangularLAF;
private float alpha = 1f;
SoftJButton() {
this(null, null);
}
SoftJButton(String text) {
this(text, null);
}
SoftJButton(String text, Icon icon) {
super(text, icon);
setOpaque(false);
setFocusPainted(false);
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float alpha) {
this.alpha = alpha;
repaint();
}
#Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
}
#Override
public void updateUI() {
super.updateUI();
lafDeterminer.updateUI();
rectangularLAF = lafDeterminer.isOpaque();
}
}
}

Categories

Resources