25 May 2008 @ 11:21 PM 
 

How to write a JToolBar application with Java

 


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...
732 views

Here's a small demo I wrote that shows you how to use the Java JToolBar. The toolbar doesn't do a lot except for showing a message when the user clicks one of the toolbar items.

Screenshot:

Code:

JAVA:
  1. import java.awt.event.ActionEvent;
  2. import java.awt.event.ActionListener;
  3.  
  4. import javax.swing.ImageIcon;
  5. import javax.swing.JButton;
  6. import javax.swing.JFrame;
  7. import javax.swing.JLabel;
  8. import javax.swing.JToolBar;
  9.  
  10. public class JToolBarDemo extends JFrame implements ActionListener{
  11. String dir = System.getProperty("user.dir");
  12. int x = 500;
  13. JToolBar toolBar = new JToolBar();
  14. JButton item1 = new JButton(new ImageIcon(dir+ "\\images\\Save24.gif"));
  15. JButton item2 = new JButton(new ImageIcon(dir+ "\\images\\Delete24.gif"));
  16. JButton item3 = new JButton(new ImageIcon(dir+ "\\images\\About24.gif"));
  17. JLabel message = new JLabel("You clicked:");
  18. public JToolBarDemo(){
  19. setLayout(null);
  20.  
  21. item1.addActionListener(this);
  22. item2.addActionListener(this);
  23. item3.addActionListener(this);
  24.  
  25. toolBar.add(item1);
  26. toolBar.add(item2);
  27. toolBar.add(item3);
  28.  
  29. toolBar.setFloatable(false);
  30. toolBar.setBounds(0,0,x,40);
  31.  
  32. message.setBounds(0,40,200,20);
  33.  
  34. add(toolBar);
  35. add(message);
  36. setTitle("Toolbar example By: HappyFace - www.engineeringserver.com");
  37. setSize(x,200);
  38. setResizable(false);
  39. setLocationRelativeTo(null);
  40. setVisible(true);
  41. }
  42. public static void main(String[] args){
  43. new JToolBarDemo();
  44. }
  45. public void actionPerformed(ActionEvent e) {
  46. if(e.getSource() == item1){
  47. message.setText("You clicked: save as..");
  48. }
  49. if(e.getSource() == item2){
  50. message.setText("You clicked: delete");
  51. }
  52.  
  53. if(e.getSource() == item3){
  54. message.setText("You clicked: about us");
  55. }
  56. }
  57. }

The images that were used in this demo application can be freely downloaded here: http://java.sun.com/developer/techDocs/hi/repository/

Related posts

Your Ad Here
Tags Tags: , , , ,
Categories: Java
Posted By: HappyFace
Last Edit: 15 Jun 2008 @ 03 01 PM

EmailPermalink
 

Responses to this post » (None)

 

Post a Comment

You must be logged in to post a comment.

 Comment Meta:
RSS Feed for comments
\/ More Options ...
Change Theme...
  • Users » 888
  • Posts/Pages » 1,444
  • Comments » 506
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Online Users



    No Child Pages.

Forum



    No Child Pages.