| | |
Button Question/Issue
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Feb 2008
Posts: 39
Reputation:
Solved Threads: 0
I currently have a program using keyboard input from the user, but am trying to replace keyboard input with onscreen buttons. Does anyone have any information on the best way to do this? I've pasted the code file involved with this (there are other files in the program). I'm not very familiar with java so what I'm finding so far is a bust (some of my attempts are commented out in code). Thanks in advance to anyone able to shed light on this!
Java Syntax (Toggle Plain Text)
package Fireworks; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.imageio.ImageIO; import java.util.*; import java.applet.*; import javax.swing.*; import javax.swing.event.*; import java.io.*; import java.net.*; import javax.sound.midi.*; import javax.sound.sampled.*; import java.applet.AudioClip; import javax.swing.JButton; import javax.imageio.*; import java.awt.Dimension; import java.beans.*; public class FireworksPanel extends AbsFireworksPanel { Fireworks Game; FireworksSprite fireworks; FireworksSpinnerSprite spinner; FireworksRocketSprite rocket; private BufferedImage burst[]; int GameScore; String explosion1 = "audio\\explosion1.wav"; String spinner1 = "audio\\spinnerexplosion1.wav"; String spinner2 = "audio\\fizzle.wav"; String rocket1 = "audio\\rocketexplosion1.wav"; Thread animation; Graphics2D dbg; private Image image; private int mx,my; public FireworksPanel() { //initComponents(); GameScore = 0; setPreferredSize(new Dimension(Constants.WIDTH, Constants.HEIGHT)); initFireworks(); Thread animation = new Thread (this); animation.start (); //callEndGame(dbg); /* JPanel fwDisplayPanel = new JPanel(new FlowLayout()); JLabel scoreBox = new JLabel("Current Score"); fwDisplayPanel.setBackground(Color.BLACK); Dimension p1dimension = new Dimension(); p1dimension.setSize(900, 500); fwDisplayPanel.setSize(p1dimension); fwDisplayPanel.setBorder(BorderFactory.createEtchedBorder()); */ } public void paint(Graphics g) { g.setColor(Color.black); g.fillRect(0,0,mx+900,my+900); } public void setGame(Fireworks Game) { this.Game = Game; } public Fireworks getGame() { return Game; } public void initFireworks() { fireworks = new FireworksSprite(); spinner = new FireworksSpinnerSprite(); rocket = new FireworksRocketSprite(); System.out.println("Initializing fireworks."); fireworks = new FireworksSprite(); fireworks.setActive(false); fireworks.setVisible(false); System.out.println("Initializing spinner."); spinner = new FireworksSpinnerSprite(); spinner.setActive(false); spinner.setVisible(false); System.out.println("Initializing rocket."); rocket = new FireworksRocketSprite(); rocket.setActive(false); rocket.setVisible(false); } public void renderSprites(Graphics2D g2d) { DisplayGameScore(GameScore, g2d); fireworks.paintSprite(g2d); spinner.paintSprite(g2d); rocket.paintSprite(g2d); if(fireworks.getLocy()<55 && fireworks.getLocy()> 0) { System.out.println("firework burst and sound."); soundeffects(rocket1); //explosion1); initBurst(g2d, 0); } if(rocket.getLocy()<55 && rocket.getLocy()> 0) { System.out.println("rocket burst and sound."); soundeffects(rocket1); initBurst(g2d, 1); } if(spinner.getLocy()<55 && spinner.getLocy()> 0) { System.out.println("spinner burst and sound."); soundeffects(spinner1); initBurst(g2d, 2); soundeffects(spinner2); } FireworksShow(); } public void FireworksShow() { addKeyListener(new KeyAdapter() { //public void keyReleased(KeyEvent event) public void keyPressed(KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.VK_LEFT: { System.out.println("FireworksShow fireworks code hit."); if(!fireworks.isLaunched() && !fireworks.isVisible()) { fireworks.setSpriteH(15); fireworks.setSpriteW(5); fireworks.setLocx(250); fireworks.setLocy(600); fireworks.setActive(true); fireworks.setVisible(true); fireworks.setLaunched(true); fireworks.setVel(3, -15); GameScore += 5; } } break; case KeyEvent.VK_UP: { System.out.println("FireworksShow spinner code hit."); if(!spinner.isLaunched() && !spinner.isVisible()) { System.out.println("Rendering spinner."); spinner.setSpriteH(15); spinner.setSpriteW(15); spinner.setLocx(250); spinner.setLocy(600); spinner.setActive(true); spinner.setVisible(true); spinner.setLaunched(true); spinner.setVel(-3, -15); GameScore += 10; } break; } case KeyEvent.VK_RIGHT: { System.out.println("FireworksShow rocket code hit."); if(!rocket.isLaunched() && !rocket.isVisible()) { rocket.setSpriteH(15); rocket.setSpriteW(5); rocket.setLocx(250); rocket.setLocy(600); rocket.setActive(true); rocket.setVisible(true); rocket.setLaunched(true); rocket.setVel(10, -15); GameScore += 15; } break; } } } }); } public void initBurst(Graphics2D g2d, int i) { burst = new BufferedImage[3]; try { burst[0] = ImageIO.read(getClass().getResource("images\\fwexplosion1.gif")); burst[1] = ImageIO.read(getClass().getResource("images\\rocketexplosion1.gif")); burst[2] = ImageIO.read(getClass().getResource("images\\spinnerexplosion1.gif")); } catch (Exception ex){System.out.println("Invalid Image");} switch(i) { case 1: { try { g2d.drawImage((BufferedImage)burst[0], 150, 50, null); animation.sleep(0); } catch(InterruptedException x){} } break; case 2: { try { g2d.drawImage((BufferedImage)burst[1], 150, 50, null); animation.sleep(0); } catch(InterruptedException x){} } break; case 3: { try { g2d.drawImage((BufferedImage)burst[2], 150, 50, null); animation.sleep(0); } catch(InterruptedException x){} } break; } try { g2d.drawImage((BufferedImage)burst[i], 150, 50, null); animation.sleep(0); } catch(InterruptedException x){} } public void updateGame() { fireworks.updateSprite(); spinner.updateSprite(); rocket.updateSprite(); } public void callEndGame(Graphics2D dbg) { if(gameOver) { Font font = new Font("Times Roman", Font.BOLD, 50); dbg.setFont(font); dbg.setColor(Color.WHITE); String GameMsg = "Game Over"; dbg.drawString(GameMsg, 150, 150); dbg.setFont(new Font("Times New Roman", Font.BOLD, 50)); dbg.setColor(Color.YELLOW); dbg.drawString("Fireworks Display", 100, 100); dbg.drawString("Final Score:", 200, 200); dbg.setFont(new Font("Times New Roman", Font.BOLD, 15)); dbg.drawString("Fireworks Display Program.", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 40); dbg.drawString("Final Project, CS8680, Dr. Xu, KSU MSACS", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 60); dbg.drawString("Nathan Williams", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 80); dbg.drawString("Fall 2007.", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 100); } } public void SoundTrack() { //Initialize background music. /*bgsong = new SongSprite(); bgsong.setFilename(Constants.SONG); //bgSound[0] = bgsong; System.out.println("Now Playing Song"); //bgsong.loadClip(); bgsong.play();*/ } public void soundeffects(String filename) { //Initialize audio sound effects. try { AudioClip FireworkSound = Applet.newAudioClip(getClass().getResource(filename)); FireworkSound.play(); //FireworkSound.stop(); } catch(Exception e) { System.out.println("Problem with " + filename); } } private void DisplayGameScore(int theGameScore, Graphics2D dbg) { dbg.setFont(new Font("Times New Roman", Font.BOLD, 30)); dbg.setColor(Color.YELLOW); dbg.drawString("Current Score is: " + theGameScore, 150,30); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code "> private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton1.setLabel("firework"); jButton2.setText("spinner"); jButton3.setText("rocket"); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(53, 53, 53) .add(jButton1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jButton3) .addContainerGap(134, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(266, Short.MAX_VALUE) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButton1) .add(jButton2) .add(jButton3)) .addContainerGap()) ); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { System.out.println("Button 1 Pressed."); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; // End of variables declaration } /* class ButtonBean { PropertyChangeSupport pChange; String valueOK; public ButtonBean() { pChange = new PropertyChangeSupport(this); } public void setValueOK() { String oldValue = "ok"; String newValue = "It is OK"; pChange.firePropertyChange("text", oldValue, newValue); } public void addPropertyChangeListener(PropertyChangeListener listener) { pChange.addPropertyChangeListener(listener); } }*/
•
•
Join Date: Jan 2008
Posts: 3,828
Reputation:
Solved Threads: 501
Decide where you want to put the buttons on the GUI, place them there, and add ActionListeners to them. Each new button represents a key that was pressed before. Decide which buttons go with which keys. Say a button called kButton was assigned to do the same thing as what used to happen when the user pressed K on the keyboard. Somewhere in your old code you have a KeyListener and a keyPressed function to go along with it. Within that keyPressed function, some code exists to handle what happens when K is pressed. Copy that code and put it into your new actionPerformed function. Somewhere within actionPerformed you'll want to have a block of code to be executed if kButton was pressed. Paste the code that you just copied from keyPressed into there.
JAVA Syntax (Toggle Plain Text)
public void actionPerformed (ActionEvent e) { if (e.getSource () == kButton) { // paste code from keyListener here } // code to handle other events }
•
•
Join Date: Feb 2008
Posts: 39
Reputation:
Solved Threads: 0
•
•
•
•
Decide where you want to put the buttons on the GUI, place them there, and add ActionListeners to them. Each new button represents a key that was pressed before. Decide which buttons go with which keys. Say a button called kButton was assigned to do the same thing as what used to happen when the user pressed K on the keyboard. Somewhere in your old code you have a KeyListener and a keyPressed function to go along with it. Within that keyPressed function, some code exists to handle what happens when K is pressed. Copy that code and put it into your new actionPerformed function. Somewhere within actionPerformed you'll want to have a block of code to be executed if kButton was pressed. Paste the code that you just copied from keyPressed into there.
JAVA Syntax (Toggle Plain Text)
public void actionPerformed (ActionEvent e) { if (e.getSource () == kButton) { // paste code from keyListener here } // code to handle other events }
Thanks, but here's the kicker: HOW do I add the button?? I'm sorry to say I can't get a button to show up on screen at all.
•
•
Join Date: Jan 2008
Posts: 3,828
Reputation:
Solved Threads: 501
If it's a class that you CAN add a button to, it'll be something like this:
This particular example comes from code where I created my own class called "Proj1Component", which extended JComponent and implemented ActionListener. I added a JButton called "kButton" to "Proj1Component". An instance of "Proj1Component" was added to a JFrame. This code is from the Proj1Component constructor. kButton is defined in Proj1Component outside of any functions.
JAVA Syntax (Toggle Plain Text)
kButton = new JButton ("K Button"); add (kButton); kButton.addActionListener (this);
This particular example comes from code where I created my own class called "Proj1Component", which extended JComponent and implemented ActionListener. I added a JButton called "kButton" to "Proj1Component". An instance of "Proj1Component" was added to a JFrame. This code is from the Proj1Component constructor. kButton is defined in Proj1Component outside of any functions.
•
•
Join Date: Feb 2008
Posts: 39
Reputation:
Solved Threads: 0
•
•
•
•
If it's a class that you CAN add a button to, it'll be something like this:
JAVA Syntax (Toggle Plain Text)
kButton = new JButton ("K Button"); add (kButton); kButton.addActionListener (this);
This particular example comes from code where I created my own class called "Proj1Component", which extended JComponent and implemented ActionListener. I added a JButton called "kButton" to "Proj1Component". An instance of "Proj1Component" was added to a JFrame. This code is from the Proj1Component constructor. kButton is defined in Proj1Component outside of any functions.
This tutorial has examples of working with the available layout managers: http://java.sun.com/docs/books/tutor...out/index.html
•
•
Join Date: Feb 2008
Posts: 39
Reputation:
Solved Threads: 0
•
•
•
•
This tutorial has examples of working with the available layout managers: http://java.sun.com/docs/books/tutor...out/index.html
You can probably use a BorderLayout for the main frame with your main panel in CENTER and a button panel in SOUTH. The button panel could use FlowLayout or GridLayout perhaps. Neither of those is too complex.
GridBagLayout would be more flexible, but it can take a little work to get comfortable with it.
GridBagLayout would be more flexible, but it can take a little work to get comfortable with it.
•
•
Join Date: Feb 2008
Posts: 39
Reputation:
Solved Threads: 0
•
•
•
•
You can probably use a BorderLayout for the main frame with your main panel in CENTER and a button panel in SOUTH. The button panel could use FlowLayout or GridLayout perhaps. Neither of those is too complex.
GridBagLayout would be more flexible, but it can take a little work to get comfortable with it.
Maybe something along these lines would work for you
java Syntax (Toggle Plain Text)
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.*; public class FrameExample extends JFrame { JPanel panNorth; JPanel panSouth; JPanel panCenter; public FrameExample() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); // set up top panel panNorth = new JPanel(); panNorth.setLayout(new FlowLayout()); panNorth.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); JLabel lblUpper = new JLabel("Upper Panel"); panNorth.add(lblUpper); add(panNorth, BorderLayout.NORTH); // set up center panel panCenter = new JPanel(); panCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); panCenter.setLayout(new BorderLayout()); JLabel lblMiddle = new JLabel("Middle thing"); lblMiddle.setHorizontalAlignment(JLabel.CENTER); panCenter.add(lblMiddle, BorderLayout.CENTER); add(panCenter); // set up bottom panel panSouth = new JPanel(); panSouth.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); panSouth.setLayout(new FlowLayout()); JButton btnFirst = new JButton("Button 1"); // if preferred size is not set then the button will size to fit the text on it btnFirst.setPreferredSize(new Dimension(100,18)); panSouth.add(btnFirst); JButton btnSecond = new JButton("Button 2"); btnSecond.setPreferredSize(new Dimension(100,18)); panSouth.add(btnSecond); add(panSouth, BorderLayout.SOUTH); setSize(300, 300); setVisible(true); } public static void main(String args[]) { new FrameExample(); } }
![]() |
Similar Threads
- Slow localhost (Networking Hardware Configuration)
- New Thread button hard to find? (DaniWeb Community Feedback)
- radio button ASP question?? (ASP)
- radio button ASP question?? (ASP)
- shutdown or powerdown issue for medion PC (Windows NT / 2000 / XP)
Other Threads in the Java Forum
- Previous Thread: How do I add data to a Jtable
- Next Thread: How the process of sending message of confirmation will be done ?
| Thread Tools | Search this Thread |
-xlint android api applet application array arrays automation bi binary blackberry block bluetooth chat class classes client code compile compiler component database developmenthelp draw eclipse error event exception fractal freeze game gameprogramming givemetehcodez graphics gui html ide image input integer j2me j2seprojects java javac javaprojects jetbrains jni jpanel jtable julia learningresources lego linux list login loop loops mac map method methods mobile netbeans newbie notdisplaying number online oracle page print problem program programming project qt recursion scanner screen server set singleton size sms sort sql string swing system template textfields threads time title tree tutorial-sample update variablebinding windows working xor






