473,656 Members | 2,824 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JButton question

20 New Member
I put in a next and previous button but it crashes when I run it. I also need it to loop around to the first or last if at the ends. Can some one help me with this?

Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.event.*;
  5. import javax.swing.JFrame.*;
  6. import java.io.*;
  7.  
  8. class Testing
  9. {
  10.   java.util.List<DVD> dvds = new java.util.ArrayList<DVD>();
  11.  
  12.   JTextField tfTitle = new JTextField(15);
  13.   JTextField tfGenre = new JTextField();
  14.   JTextField tfProductNumber = new JTextField();
  15.   JTextField tfPrice = new JTextField();
  16.   JTextField tfQuantity = new JTextField();
  17.   JTextField tfvalue = new JTextField();
  18.   JTextField tfrestock = new JTextField();
  19.   DefaultListModel dlm = new DefaultListModel();
  20.   JList list = new JList(dlm);
  21.   public void buildGUI()
  22.   {
  23.     JButton btnAdd = new JButton("Add");
  24.     JButton btnPrevious = new JButton ("Previous");
  25.     JButton btnNext = new JButton ("Next");
  26.     JPanel p1 = new JPanel(new BorderLayout());
  27.     JPanel p = new JPanel(new GridLayout(8,4));
  28.     p.add(new JLabel("DVD Title: "));
  29.     p.add(tfTitle);
  30.     p.add(new JLabel("Genre: "));
  31.     p.add(tfGenre);
  32.     p.add(new JLabel("Product Number: "));
  33.     p.add(tfProductNumber);
  34.     p.add(new JLabel("Price per Unit: "));
  35.     p.add(tfPrice);
  36.     p.add(new JLabel("Quantity on Hand: "));
  37.     p.add(tfQuantity);
  38.     p.add(new JLabel("Value: "));
  39.     p.add(tfvalue);
  40.     p.add(new JLabel("Restock-fee: "));
  41.     p.add(tfrestock);
  42.     p1.add(p,BorderLayout.NORTH);
  43.     JPanel p2 = new JPanel();
  44.     p2.add(btnAdd);
  45.     p2.add(btnPrevious);
  46.     p2.add(btnNext);
  47.     p1.add(p2,BorderLayout.CENTER);
  48.     JFrame f = new JFrame();
  49.     f.setIconImage(new ImageIcon("sunlogo64x30.gif").getImage());
  50.     f.getContentPane().add(p1,BorderLayout.NORTH);
  51.     JScrollPane sp = new JScrollPane(list);
  52.     f.getContentPane().add(sp,BorderLayout.CENTER);
  53.     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  54.     f.pack();
  55.     f.setLocationRelativeTo(null);
  56.     f.setVisible(true);
  57.     f.setIconImage(new ImageIcon("Images/sunlogo64x30.gif").getImage());
  58.     btnAdd.addActionListener(new ActionListener(){
  59.       public void actionPerformed(ActionEvent ae){
  60.         dvds.add(new DVD(tfTitle.getText(),tfGenre.getText(),
  61.                                 tfProductNumber.getText(),
  62.                                 Double.parseDouble(tfPrice.getText()),
  63.                                 Double.parseDouble(tfvalue.getText()),
  64.                                 Double.parseDouble(tfrestock.getText()),
  65.                                Integer.parseInt(tfQuantity.getText())));
  66.         setList();
  67.         clearTextFields();
  68.               }
  69.     });
  70.     btnPrevious.addActionListener(new ActionListener(){
  71.           public void actionPerformed(ActionEvent ae){
  72.             DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
  73.                         int index = (list.getSelectedIndex()-1) % dvds.size();
  74.                         if(index < 0) index = dvds.size()-1;
  75.                         list.setSelectedIndex(index);
  76.             setList();
  77.  
  78.       }
  79.     });
  80.  
  81.     btnNext.addActionListener(new ActionListener(){
  82.           public void actionPerformed(ActionEvent ae){
  83.             DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
  84.                         int index = (list.getSelectedIndex()+1) % dvds.size(); 
  85.                         list.setSelectedIndex(index);
  86.             setList();
  87.  
  88.       }
  89.     });
  90.     list.addListSelectionListener(new ListSelectionListener(){
  91.       public void valueChanged(ListSelectionEvent lse){
  92.         if(lse.getValueIsAdjusting() == false)
  93.         {
  94.           DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
  95.           tfTitle.setText(dvd.title);
  96.           tfGenre.setText(dvd.genre);
  97.           tfProductNumber.setText(dvd.productNumber);
  98.           tfPrice.setText(""+dvd.price);
  99.           tfQuantity.setText(""+dvd.quantity);
  100.           tfvalue.setText(""+dvd.value);
  101.           tfrestock.setText(""+dvd.restock);
  102.         }
  103.       }
  104.     });
  105.   }
  106.   public void setList()
  107.   {
  108.     dlm.clear();
  109.     for(int x = 0, y = dvds.size(); x < y; x++)
  110.     {
  111.       dlm.addElement((DVD)dvds.get(x));
  112.     }
  113.   }
  114.   public void clearTextFields()
  115.   {
  116.     tfTitle.setText("");
  117.     tfGenre.setText("");
  118.     tfProductNumber.setText("");
  119.     tfPrice.setText("");
  120.     tfQuantity.setText("");
  121.     tfvalue.setText("");
  122.     tfrestock.setText("");
  123.     tfTitle.requestFocusInWindow();
  124.   }
  125.   public static void main(String[] args)
  126.   {
  127.     EventQueue.invokeLater(new Runnable(){
  128.       public void run(){
  129.         new Testing().buildGUI();
  130.       }
  131.     });
  132.   }
  133. }
  134. class DVD
  135. {
  136.   String title;
  137.   String genre;
  138.   String productNumber;
  139.   double price;
  140.   double value;
  141.   double restock;
  142.   int quantity;
  143.   public DVD(String t, String g, String pn, double p, double v, double r, int q)
  144.   {
  145.     title = t; genre = g; productNumber = pn; price = p; value = v; restock = r; quantity = q;
  146.     value = p * q;
  147.     restock = v * 1.05;
  148.   }
  149.   public String toString(){return title;}
  150. }
Nov 14 '06 #1
4 1678
horace1
1,510 Recognized Expert Top Contributor
why do you call the setList() method in your btnPrevious and btnNext actionPerformed () methods - it clears the List and rewrites it (which you don't need to do for these buttons) and in the process sets list.getSelecte dIndex() to -1 which causes your indexOutOfBound s Exceptions
Nov 14 '06 #2
porky008
20 New Member
Thank you thank you. My next question is how would I add a button that goes to the last or first item? I have not been able to figure that part out.
Nov 14 '06 #3
horace1
1,510 Recognized Expert Top Contributor
Thank you thank you. My next question is how would I add a button that goes to the last or first item? I have not been able to figure that part out.
You could add two more buttons First and Last with appropriate ActionListeners , e.g. for First
Expand|Select|Wrap|Line Numbers
  1.     btnFirst.addActionListener(new ActionListener(){
  2.               public void actionPerformed(ActionEvent ae){
  3.                 DVD dvd = (DVD)dvds.get(0);
  4.                 list.setSelectedIndex(0);
  5.       }
  6.     });
  7.  
Nov 14 '06 #4
porky008
20 New Member
thank you now i just have to re-read the book to see if i can find the value of the last item.
Nov 14 '06 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2218
by: Jeff T. | last post by:
Hi, I have a JMenuBar object that contains a JToolBar object which contains some JButton objects. After I let my applet sit for > 20 minutes, the graphics on those buttons would disappear. There seems to be nothing I can do to reload these graphics. I declare a JToolBar toolBar and call
3
2304
by: Konrad Den Ende | last post by:
Is it possible to do at all? The software will be used on computers with western operative systems (so i guess, JVM will be english) but i'm asured that japanese will be enabled through IME so that all fonts-and-company are installed. -- Kindly Konrad ---------------------------------------------------
0
4367
by: Oswald Otte | last post by:
Hello How can I change the look of a disabled JButton? I have made a boardgame with a brown background and brown buttons. I have also put an imageicon on the buttons that has a colored image on it. When I disable the buttons, the colored image is turned into grey which screws up the look of my game. Can I change the grey color on a disabled button? Or do I have to keep it enabled, and attach another imageicon with different color to...
9
1986
by: SimonHeffer | last post by:
I've been asked to give my .NET app the same look and feel to another app written using Java/Swing. My main issue is to do with button/icons. The JButton used by the other app has an icon with a transparent background - this may a consequence of using GIF as the source format. Now I just want to knock-up some simple icons for my app using VS2005 image editor and add them to the buttons. Cannot see how to add transparent pixels. <gripe>...
6
2136
by: vijaykumarsharma | last post by:
Hi all I am having a problem with JButton. JButton b=new JButton("save"); how can i get the name of the JButton b. Please give the anser for me
2
2273
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that already exist) in my application using the Design Editor. I go about this by right-clicking on the JButton in the design editor, navigating to Events -> Action -> actionPerformed. The auto-generated code appears for a brief moment before it...
1
3187
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that already exist) in my application using the Design Editor. I go about this by right-clicking on the JButton in the design editor, navigating to Events -> Action -> actionPerformed. The auto-generated code appears for a brief moment before it...
12
3645
by: yeshello54 | last post by:
So I want to set the background color of a Jbutton. I know that the normal way to do such a thing is down the following way: JButton button = new JButton("xxxx"); button.setBackground(Color.RED); but in my program i add my Jbutton the following way.. horizontalBox2=Box.createHorizontalBox(); horizontalBox2.add(new JButton("Black"));
1
2364
by: mlibot | last post by:
My JButton will be disabled when running my program... my JButton will be enabled if the value or parameter are equal to 3... for example: 1 value is path of the file i selected. 2 vaue is path of the directory i selected. 3 value is path of i want to be creating a output. if this three value will complete my JButton will be going to enabled... and i have no problem with that. But!!!.. if i just type a words or letters let say "abcd" of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.