943,712 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Marked Solved
  • Views: 1868
  • Java RSS
You are currently viewing page 1 of this multi-page discussion thread
Apr 3rd, 2008
0

Button Question/Issue

Expand Post »
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)
  1. package Fireworks;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import java.awt.event.KeyAdapter;
  7. import java.awt.event.KeyEvent;
  8. import java.awt.image.BufferedImage;
  9. import java.beans.PropertyChangeEvent;
  10. import java.beans.PropertyChangeListener;
  11. import javax.imageio.ImageIO;
  12. import java.util.*;
  13. import java.applet.*;
  14. import javax.swing.*;
  15. import javax.swing.event.*;
  16. import java.io.*;
  17. import java.net.*;
  18. import javax.sound.midi.*;
  19. import javax.sound.sampled.*;
  20. import java.applet.AudioClip;
  21. import javax.swing.JButton;
  22. import javax.imageio.*;
  23. import java.awt.Dimension;
  24. import java.beans.*;
  25.  
  26. public class FireworksPanel extends AbsFireworksPanel
  27. {
  28. Fireworks Game;
  29. FireworksSprite fireworks;
  30. FireworksSpinnerSprite spinner;
  31. FireworksRocketSprite rocket;
  32. private BufferedImage burst[];
  33. int GameScore;
  34. String explosion1 = "audio\\explosion1.wav";
  35. String spinner1 = "audio\\spinnerexplosion1.wav";
  36. String spinner2 = "audio\\fizzle.wav";
  37. String rocket1 = "audio\\rocketexplosion1.wav";
  38. Thread animation;
  39. Graphics2D dbg;
  40. private Image image;
  41. private int mx,my;
  42.  
  43.  
  44. public FireworksPanel()
  45. {
  46. //initComponents();
  47. GameScore = 0;
  48. setPreferredSize(new Dimension(Constants.WIDTH, Constants.HEIGHT));
  49. initFireworks();
  50. Thread animation = new Thread (this);
  51. animation.start ();
  52. //callEndGame(dbg);
  53. /*
  54.   JPanel fwDisplayPanel = new JPanel(new FlowLayout());
  55.   JLabel scoreBox = new JLabel("Current Score");
  56.   fwDisplayPanel.setBackground(Color.BLACK);
  57.   Dimension p1dimension = new Dimension();
  58.   p1dimension.setSize(900, 500);
  59.   fwDisplayPanel.setSize(p1dimension);
  60.   fwDisplayPanel.setBorder(BorderFactory.createEtchedBorder());
  61.   */
  62. }
  63.  
  64. public void paint(Graphics g)
  65. {
  66. g.setColor(Color.black);
  67. g.fillRect(0,0,mx+900,my+900);
  68. }
  69.  
  70.  
  71. public void setGame(Fireworks Game)
  72. {
  73. this.Game = Game;
  74. }
  75.  
  76.  
  77. public Fireworks getGame()
  78. {
  79. return Game;
  80. }
  81.  
  82.  
  83. public void initFireworks()
  84. {
  85. fireworks = new FireworksSprite();
  86. spinner = new FireworksSpinnerSprite();
  87. rocket = new FireworksRocketSprite();
  88.  
  89. System.out.println("Initializing fireworks.");
  90. fireworks = new FireworksSprite();
  91. fireworks.setActive(false);
  92. fireworks.setVisible(false);
  93.  
  94. System.out.println("Initializing spinner.");
  95. spinner = new FireworksSpinnerSprite();
  96. spinner.setActive(false);
  97. spinner.setVisible(false);
  98.  
  99. System.out.println("Initializing rocket.");
  100. rocket = new FireworksRocketSprite();
  101. rocket.setActive(false);
  102. rocket.setVisible(false);
  103. }
  104.  
  105.  
  106. public void renderSprites(Graphics2D g2d)
  107. {
  108. DisplayGameScore(GameScore, g2d);
  109. fireworks.paintSprite(g2d);
  110. spinner.paintSprite(g2d);
  111. rocket.paintSprite(g2d);
  112. if(fireworks.getLocy()<55 && fireworks.getLocy()> 0)
  113. {
  114. System.out.println("firework burst and sound.");
  115. soundeffects(rocket1); //explosion1);
  116. initBurst(g2d, 0);
  117. }
  118.  
  119. if(rocket.getLocy()<55 && rocket.getLocy()> 0)
  120. {
  121. System.out.println("rocket burst and sound.");
  122. soundeffects(rocket1);
  123. initBurst(g2d, 1);
  124. }
  125.  
  126. if(spinner.getLocy()<55 && spinner.getLocy()> 0)
  127. {
  128. System.out.println("spinner burst and sound.");
  129. soundeffects(spinner1);
  130. initBurst(g2d, 2);
  131. soundeffects(spinner2);
  132. }
  133. FireworksShow();
  134. }
  135.  
  136.  
  137.  
  138. public void FireworksShow()
  139. {
  140. addKeyListener(new KeyAdapter()
  141. {
  142. //public void keyReleased(KeyEvent event)
  143. public void keyPressed(KeyEvent event)
  144. {
  145. switch(event.getKeyCode())
  146. {
  147. case KeyEvent.VK_LEFT:
  148. {
  149. System.out.println("FireworksShow fireworks code hit.");
  150. if(!fireworks.isLaunched() && !fireworks.isVisible())
  151. {
  152. fireworks.setSpriteH(15);
  153. fireworks.setSpriteW(5);
  154. fireworks.setLocx(250);
  155. fireworks.setLocy(600);
  156. fireworks.setActive(true);
  157. fireworks.setVisible(true);
  158. fireworks.setLaunched(true);
  159. fireworks.setVel(3, -15);
  160. GameScore += 5;
  161. }
  162. }
  163. break;
  164.  
  165. case KeyEvent.VK_UP:
  166. {
  167. System.out.println("FireworksShow spinner code hit.");
  168. if(!spinner.isLaunched() && !spinner.isVisible())
  169. {
  170. System.out.println("Rendering spinner.");
  171. spinner.setSpriteH(15);
  172. spinner.setSpriteW(15);
  173. spinner.setLocx(250);
  174. spinner.setLocy(600);
  175. spinner.setActive(true);
  176. spinner.setVisible(true);
  177. spinner.setLaunched(true);
  178. spinner.setVel(-3, -15);
  179. GameScore += 10;
  180. }
  181. break;
  182. }
  183.  
  184. case KeyEvent.VK_RIGHT:
  185. {
  186. System.out.println("FireworksShow rocket code hit.");
  187. if(!rocket.isLaunched() && !rocket.isVisible())
  188. {
  189. rocket.setSpriteH(15);
  190. rocket.setSpriteW(5);
  191. rocket.setLocx(250);
  192. rocket.setLocy(600);
  193. rocket.setActive(true);
  194. rocket.setVisible(true);
  195. rocket.setLaunched(true);
  196. rocket.setVel(10, -15);
  197. GameScore += 15;
  198. }
  199. break;
  200. }
  201. }
  202. }
  203. });
  204. }
  205.  
  206. public void initBurst(Graphics2D g2d, int i)
  207. {
  208. burst = new BufferedImage[3];
  209. try
  210. {
  211. burst[0] = ImageIO.read(getClass().getResource("images\\fwexplosion1.gif"));
  212. burst[1] = ImageIO.read(getClass().getResource("images\\rocketexplosion1.gif"));
  213. burst[2] = ImageIO.read(getClass().getResource("images\\spinnerexplosion1.gif"));
  214. }
  215. catch (Exception ex){System.out.println("Invalid Image");}
  216. switch(i)
  217. {
  218. case 1:
  219. {
  220. try
  221. {
  222. g2d.drawImage((BufferedImage)burst[0], 150, 50, null);
  223. animation.sleep(0);
  224. }
  225. catch(InterruptedException x){}
  226. }
  227. break;
  228.  
  229. case 2:
  230. {
  231. try
  232. {
  233. g2d.drawImage((BufferedImage)burst[1], 150, 50, null);
  234. animation.sleep(0);
  235. }
  236. catch(InterruptedException x){}
  237. }
  238. break;
  239.  
  240. case 3:
  241. {
  242. try
  243. {
  244. g2d.drawImage((BufferedImage)burst[2], 150, 50, null);
  245. animation.sleep(0);
  246. }
  247. catch(InterruptedException x){}
  248. }
  249. break;
  250. }
  251.  
  252. try
  253. {
  254. g2d.drawImage((BufferedImage)burst[i], 150, 50, null);
  255. animation.sleep(0);
  256. }
  257. catch(InterruptedException x){}
  258. }
  259.  
  260.  
  261. public void updateGame()
  262. {
  263. fireworks.updateSprite();
  264. spinner.updateSprite();
  265. rocket.updateSprite();
  266. }
  267.  
  268.  
  269. public void callEndGame(Graphics2D dbg)
  270. {
  271. if(gameOver)
  272. {
  273. Font font = new Font("Times Roman", Font.BOLD, 50);
  274. dbg.setFont(font);
  275. dbg.setColor(Color.WHITE);
  276. String GameMsg = "Game Over";
  277. dbg.drawString(GameMsg, 150, 150);
  278. dbg.setFont(new Font("Times New Roman", Font.BOLD, 50));
  279.  
  280. dbg.setColor(Color.YELLOW);
  281. dbg.drawString("Fireworks Display", 100, 100);
  282. dbg.drawString("Final Score:", 200, 200);
  283. dbg.setFont(new Font("Times New Roman", Font.BOLD, 15));
  284. dbg.drawString("Fireworks Display Program.", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 40);
  285. dbg.drawString("Final Project, CS8680, Dr. Xu, KSU MSACS", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 60);
  286. dbg.drawString("Nathan Williams", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 80);
  287. dbg.drawString("Fall 2007.", Constants.WIDTH/2 + 20, Constants.HEIGHT/2 + 100);
  288. }
  289. }
  290.  
  291. public void SoundTrack()
  292. {
  293. //Initialize background music.
  294. /*bgsong = new SongSprite();
  295.   bgsong.setFilename(Constants.SONG);
  296.   //bgSound[0] = bgsong;
  297.   System.out.println("Now Playing Song");
  298.   //bgsong.loadClip();
  299.   bgsong.play();*/
  300. }
  301.  
  302.  
  303. public void soundeffects(String filename)
  304. {
  305. //Initialize audio sound effects.
  306. try
  307. {
  308. AudioClip FireworkSound = Applet.newAudioClip(getClass().getResource(filename));
  309. FireworkSound.play();
  310. //FireworkSound.stop();
  311. }
  312. catch(Exception e)
  313. {
  314. System.out.println("Problem with " + filename);
  315. }
  316. }
  317.  
  318.  
  319. private void DisplayGameScore(int theGameScore, Graphics2D dbg)
  320. {
  321. dbg.setFont(new Font("Times New Roman", Font.BOLD, 30));
  322. dbg.setColor(Color.YELLOW);
  323. dbg.drawString("Current Score is: " + theGameScore, 150,30);
  324. }
  325.  
  326. /** This method is called from within the constructor to
  327.   * initialize the form.
  328.   * WARNING: Do NOT modify this code. The content of this method is
  329.   * always regenerated by the Form Editor.
  330.   */
  331. // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
  332. private void initComponents() {
  333. jButton1 = new javax.swing.JButton();
  334. jButton2 = new javax.swing.JButton();
  335. jButton3 = new javax.swing.JButton();
  336.  
  337. jButton1.setLabel("firework");
  338.  
  339. jButton2.setText("spinner");
  340.  
  341. jButton3.setText("rocket");
  342.  
  343. org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
  344. this.setLayout(layout);
  345. layout.setHorizontalGroup(
  346. layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
  347. .add(layout.createSequentialGroup()
  348. .add(53, 53, 53)
  349. .add(jButton1)
  350. .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
  351. .add(jButton2)
  352. .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
  353. .add(jButton3)
  354. .addContainerGap(134, Short.MAX_VALUE))
  355. );
  356. layout.setVerticalGroup(
  357. layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
  358. .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
  359. .addContainerGap(266, Short.MAX_VALUE)
  360. .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
  361. .add(jButton1)
  362. .add(jButton2)
  363. .add(jButton3))
  364. .addContainerGap())
  365. );
  366. }// </editor-fold>
  367.  
  368. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
  369. {
  370. System.out.println("Button 1 Pressed.");
  371. }
  372.  
  373. // Variables declaration - do not modify
  374. private javax.swing.JButton jButton1;
  375. private javax.swing.JButton jButton2;
  376. private javax.swing.JButton jButton3;
  377. // End of variables declaration
  378.  
  379. }
  380.  
  381.  
  382. /*
  383. class ButtonBean
  384. {
  385.   PropertyChangeSupport pChange;
  386.   String valueOK;
  387.  
  388.   public ButtonBean()
  389.   {
  390.   pChange = new PropertyChangeSupport(this);
  391.   }
  392.  
  393.   public void setValueOK()
  394.   {
  395.   String oldValue = "ok";
  396.   String newValue = "It is OK";
  397.   pChange.firePropertyChange("text", oldValue, newValue);
  398.   }
  399.  
  400.   public void addPropertyChangeListener(PropertyChangeListener listener)
  401.   {
  402.   pChange.addPropertyChangeListener(listener);
  403.   }
  404. }*/
Similar Threads
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
CaffeineCoder is offline Offline
54 posts
since Feb 2008
Apr 3rd, 2008
0

Re: Button Question/Issue

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)
  1. public void actionPerformed (ActionEvent e)
  2. {
  3. if (e.getSource () == kButton)
  4. {
  5. // paste code from keyListener here
  6. }
  7. // code to handle other events
  8. }
Featured Poster
Reputation Points: 2614
Solved Threads: 687
Posting Expert
VernonDozier is offline Offline
5,372 posts
since Jan 2008
Apr 4th, 2008
0

Re: Button Question/Issue

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)
  1. public void actionPerformed (ActionEvent e)
  2. {
  3. if (e.getSource () == kButton)
  4. {
  5. // paste code from keyListener here
  6. }
  7. // code to handle other events
  8. }

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.
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
CaffeineCoder is offline Offline
54 posts
since Feb 2008
Apr 4th, 2008
0

Re: Button Question/Issue

If it's a class that you CAN add a button to, it'll be something like this:
JAVA Syntax (Toggle Plain Text)
  1. kButton = new JButton ("K Button");
  2. add (kButton);
  3. 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.
Featured Poster
Reputation Points: 2614
Solved Threads: 687
Posting Expert
VernonDozier is offline Offline
5,372 posts
since Jan 2008
Apr 4th, 2008
0

Re: Button Question/Issue

If it's a class that you CAN add a button to, it'll be something like this:
JAVA Syntax (Toggle Plain Text)
  1. kButton = new JButton ("K Button");
  2. add (kButton);
  3. 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.
OK, I have one giant button coming onto the screen, but it's behind the display screen. What's the best way to get the buttons to show up at the bottom of the screen? I'm thinking some sort of layout manager will be the best way, but not sure how to get it to work.
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
CaffeineCoder is offline Offline
54 posts
since Feb 2008
Apr 4th, 2008
0

Re: Button Question/Issue

This tutorial has examples of working with the available layout managers: http://java.sun.com/docs/books/tutor...out/index.html
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Ezzaral is offline Offline
6,758 posts
since May 2007
Apr 4th, 2008
0

Re: Button Question/Issue

Click to Expand / Collapse  Quote originally posted by Ezzaral ...
This tutorial has examples of working with the available layout managers: http://java.sun.com/docs/books/tutor...out/index.html
Thanks, I'll go through that. Was looking at a diff one, but my main concern is button size; don't want the buttons to be huge on the screen.
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
CaffeineCoder is offline Offline
54 posts
since Feb 2008
Apr 4th, 2008
0

Re: Button Question/Issue

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.
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Ezzaral is offline Offline
6,758 posts
since May 2007
Apr 4th, 2008
0

Re: Button Question/Issue

Click to Expand / Collapse  Quote originally posted by Ezzaral ...
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.
So basically 2 Layout managers are involved, one for the main screen, and another for the controls; that should work. already coding out the FlowLayout for the buttons. Cool, I'll try that. Thanks.
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
CaffeineCoder is offline Offline
54 posts
since Feb 2008
Apr 4th, 2008
0

Re: Button Question/Issue

Maybe something along these lines would work for you
java Syntax (Toggle Plain Text)
  1. import java.awt.BorderLayout;
  2. import java.awt.Color;
  3. import java.awt.Dimension;
  4. import java.awt.FlowLayout;
  5. import javax.swing.*;
  6.  
  7. public class FrameExample extends JFrame {
  8.  
  9. JPanel panNorth;
  10. JPanel panSouth;
  11. JPanel panCenter;
  12.  
  13. public FrameExample() {
  14. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  15.  
  16. setLayout(new BorderLayout());
  17.  
  18. // set up top panel
  19. panNorth = new JPanel();
  20. panNorth.setLayout(new FlowLayout());
  21. panNorth.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
  22. JLabel lblUpper = new JLabel("Upper Panel");
  23. panNorth.add(lblUpper);
  24. add(panNorth, BorderLayout.NORTH);
  25.  
  26. // set up center panel
  27. panCenter = new JPanel();
  28. panCenter.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
  29. panCenter.setLayout(new BorderLayout());
  30. JLabel lblMiddle = new JLabel("Middle thing");
  31. lblMiddle.setHorizontalAlignment(JLabel.CENTER);
  32. panCenter.add(lblMiddle, BorderLayout.CENTER);
  33. add(panCenter);
  34.  
  35. // set up bottom panel
  36. panSouth = new JPanel();
  37. panSouth.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
  38. panSouth.setLayout(new FlowLayout());
  39. JButton btnFirst = new JButton("Button 1");
  40. // if preferred size is not set then the button will size to fit the text on it
  41. btnFirst.setPreferredSize(new Dimension(100,18));
  42. panSouth.add(btnFirst);
  43. JButton btnSecond = new JButton("Button 2");
  44. btnSecond.setPreferredSize(new Dimension(100,18));
  45. panSouth.add(btnSecond);
  46. add(panSouth, BorderLayout.SOUTH);
  47.  
  48. setSize(300, 300);
  49. setVisible(true);
  50. }
  51.  
  52. public static void main(String args[]) {
  53. new FrameExample();
  54. }
  55. }
Moderator
Featured Poster
Reputation Points: 3239
Solved Threads: 838
Posting Genius
Ezzaral is offline Offline
6,758 posts
since May 2007

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: How do I add data to a Jtable
Next Thread in Java Forum Timeline: How the process of sending message of confirmation will be done ?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC