Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Need help with my code! Absolute coordinates

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help with my code! Absolute coordinates

    I need help with this code, I cannot seem to have either panels displayed along with their contents. It worked fine with a grid layout, however it did not have the positioning I required with the ease I would have liked. Thanks.
     
    package ratsac2;
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.*;
     
    public class RatSAC2 extends JFrame {
     
        // Create text fields for ItemList, Item Name, Quantity and Item description
      //  private JComboBox jtfItemList = new JComboBox();
        private JTextField jtfItemName = new JTextField();
        private JTextField jtfQuantity = new JTextField();
        private JTextField jtfDescription =  new JTextField();
     
        JComboBox ItemList; // Adds the combo box
        String choice;
     
     
        // Set the fonts to be used.
        Font font1 = new Font("DialogInput", Font.BOLD + Font.ITALIC, 15);
        Font font2 = new Font("Monospaced",Font.ITALIC,15);
        Color newCol = new Color(120,100,100);
     
        //Create the buttons.
        private JButton jbtCancel = new JButton("Cancel");
        private JButton jbtViewCart = new JButton ("View Cart");
        private JButton jbtAddToCart = new JButton("Add to Cart");   
     
        public RatSAC2 () {
     
            // Panel p1 to hold labels and text fields.
            JPanel p1 = new JPanel();
            p1.setLayout(null);
            p1.add(new JLabel("ItemList"));
     
            // Set up the combo box:
     
            String [] Item = {"Bath Mat","Mirror","Olive Scented Candle","Toilet Paper","Pet Rats","Vase","Potato Sack","Inflatable Beer Pong","LED   Fairy Net","Toothbrush"};  // Entries must be of type String! (These are the options)
            ItemList = new JComboBox(Item);
            ItemList.setSelectedIndex(0);
            ItemList.setBackground(Color.white); // Sets background and foreground colors
            ItemList.setForeground(Color.black);
     
     
     
        //    p1.add(jtfItemList); 
     
           // **** Add the combo box to panel p1, then add a listener to get the selected item.
     
            p1.add(ItemList);   
     
            ItemList.addItemListener(new ItemListener(){
                public void itemStateChanged(ItemEvent ie){
                 String str = (String)ItemList.getSelectedItem();
                 if ("Mirror".equals(str)){
                     jtfDescription.setText("uuu");
                 }
                 else if ("Vase".equals(str)){
                     jtfDescription.setText("kkk");
                 }
                 else {
                     jtfDescription.setText("ooo");  
                     }
                 }
     
                // choice = Integer.parseInt(str);
     
            });
     
     
           // Set absolute coordinates for fields and labels; X,Y,W,H
           jtfItemName.setBounds(20,20,50,50); 
           jtfQuantity.setBounds(40,40,50,50);
           jtfDescription.setBounds(50,50,50,50);
     
     
           // add the labels and fields to panel 1 
            p1.add(jtfItemName);
            p1.add(new JLabel("Item Name"));
            p1.add(jtfQuantity );   
            p1.add(new JLabel("Quantity"));
            p1.add(new JLabel("Description"));
            p1.add(jtfDescription);
     
     
            // *********** Set up the second frame  ************
     
            final JFrame f2 = new JFrame();  //See note below re local variable f2
            f2.getContentPane().setBackground(Color.white);
            f2.setSize(500,800);
            f2.setLocation(200,150); 
            f2.setVisible(false);
     
            // Check when NewWindow button is clicked.
            jbtCancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
     
                  // Local variable is accessed from within inner class. Needs to be declared final (as above). 
     
                   f2.setVisible(true);               
                }
            });
     
            // *************************************************
     
     
            // Panel p2 to hold the buttons.
            JPanel p2 = new JPanel();
            p2.setLayout(null);
            p2.add(jbtCancel);
            p2.add(jbtViewCart);
            p2.add(jbtAddToCart);
     
            // Add the panels to the frame. 
            add(p1, BorderLayout.NORTH);
            add(p2, BorderLayout.SOUTH);
     
        }
     
                public static void main(String[] args) {
            RatSAC2 f1 = new RatSAC2();
            f1.pack();
            f1.setSize(800,500);
            f1.setTitle("Shopping Cart");
            f1.setLocationRelativeTo(null); // Center the frame.
            f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f1.setVisible(true);
            f1.setResizable(false);
            }}


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,342
    My Mood
    Hungover
    Thanks
    143
    Thanked 625 Times in 536 Posts

    Default Re: Need help with my code! Absolute coordinates

    That's definitely a lot of code for somebody else to wade through. Why not post an SSCCE instead? I'm not sure what your actual question is.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: Need help with my code! Absolute coordinates

    MrLemons,
    If you have problem with layout, then try the other layouts. There are so many layouts available in Java - FlowLayout, BoxLayout, GridBagLayout, etc.
    I would suggest try GridBagLayout.

    Syed.

  4. #4
    Junior Member
    Join Date
    Sep 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code! Absolute coordinates

    Basically I'm trying to get a window to appropriately display labels and fields in the correct positions along with the correct width and height. However, with the code I have there, nothing is displayed. Thanks for the feedback Syed, I'll try that out.

    --- Update ---

     
    package ratsac2;
     
    // Imports for the code
    import java.awt.BorderLayout;
    import javax.swing.*;
     
     public class RatSAC2 extends JFrame {
     
        private JTextField jtfItemName = new JTextField();
        private JTextField jtfQuantity = new JTextField();
        private JTextField jtfDescription =  new JTextField();
     
        JComboBox ItemList; // Adds the combo box
        String choice;
     
        //Create the buttons.
        private JButton jbtCancel = new JButton("Cancel");
        private JButton jbtViewCart = new JButton ("View Cart");
        private JButton jbtAddToCart = new JButton("Add to Cart");   
     
        public RatSAC2 () {
     
           // Panel p1 to hold labels and text fields.
            JPanel p1 = new JPanel();
            p1.setLayout(null);
            p1.add(new JLabel("ItemList"));
     
              // Set absolute coordinates for fields and labels; X,Y,W,H
               jtfItemName.setBounds(20,20,50,50); 
               jtfQuantity.setBounds(40,40,50,50);
               jtfDescription.setBounds(50,50,50,50);
     
              // add the labels and fields to panel 1 
              p1.add(jtfItemName);
              p1.add(new JLabel("Item Name"));
              p1.add(jtfQuantity );   
              p1.add(new JLabel("Quantity"));
              p1.add(new JLabel("Description"));
              p1.add(jtfDescription);
              p1.add(ItemList); 
     
        // Panel p2 to hold the buttons.
            JPanel p2 = new JPanel();
            p2.setLayout(null);
            p2.add(jbtCancel);
            p2.add(jbtViewCart);
            p2.add(jbtAddToCart);
     
         // Add the panels to the frame. 
            add(p1, BorderLayout.NORTH);
            add(p2, BorderLayout.SOUTH);
     
        }
     
     public static void main(String[] args) {
     
              RatSAC2 f1 = new RatSAC2();
              f1.pack();
              f1.setSize(800,500);
              f1.setTitle("Shopping Cart");
              f1.setLocationRelativeTo(null); // Center the frame.
              f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f1.setVisible(true);
              f1.setResizable(false);
          }}

    I believe that's about as short as I can cut it down to. Should be easier to go over, thanks!

    hm... nvm. Tried to run this. Getting a few errors.

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,342
    My Mood
    Hungover
    Thanks
    143
    Thanked 625 Times in 536 Posts

    Default Re: Need help with my code! Absolute coordinates

    What errors are you getting? What line are the errors on?

    This code is pretty confusing. Where do you initialize ItemList (which really should be itemList, pay attention to standard naming conventions)? Why are you using a null layout?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Junior Member
    Join Date
    Sep 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code! Absolute coordinates

    Quote Originally Posted by KevinWorkman View Post
    What errors are you getting? What line are the errors on?

    This code is pretty confusing. Where do you initialize ItemList (which really should be itemList, pay attention to standard naming conventions)? Why are you using a null layout?
    Yeah, sorry, I'm somewhat new to Java, I've identified a few issues. First up, I had a second frame when using absolute coordinates which conflicts with the first frame (I believe), as-well as this I believe that the coordinates I've set are also in conflict with one another. Sorry for the vague explanations

    These are the errors I get:
    Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1090)
    at java.awt.Container.add(Container.java:410)
    at Ratsac2.Ratsac2.<init>(Ratsac2.java:33)
    at Ratsac2.Ratsac2.main(Ratsac2.java:49)
    Java Result: 1


    Also, the naming for the package name and others throughout the code didn't correspond to each other, thus, here is a modified version of what I had before without the second frame. The itemList combo box is initialized under where the labels are created.
    package Ratsac2;
     
    import javax.swing.*;
     
     public class Ratsac2 extends JFrame {
     
        // Create the fields
        private JTextField jtfitemName = new JTextField();
        private JTextField jtfQuantity = new JTextField();
        private JTextField jtfDescription =  new JTextField();
     
        //Create the buttons
        private JButton jbtCancel = new JButton("Cancel");
        private JButton jbtViewCart = new JButton ("View Cart");
        private JButton jbtAddToCart = new JButton("Add to Cart");  
     
        // Create the labels
        private JLabel jtfLblitemList = new JLabel("Item List"); 
        private JLabel jtfLblitemName = new JLabel("Item Name"); 
        private JLabel jtfLblQuantity = new JLabel("Quantity"); 
        private JLabel jtfLblDescription = new JLabel("Description"); 
     
     
        JComboBox itemList; // Adds the combo box
        String choice;
     
        public Ratsac2 () {
     
           // Panel 1 created - Variables added to Panel 1
            JPanel p1 = new JPanel();
            p1.setLayout(null);
            p1.add(jtfLblitemList);
            p1.add(itemList); 
            p1.add(jtfitemName);
            p1.add(jtfLblitemName);
            p1.add(jtfLblQuantity);
            p1.add(jtfQuantity );   
            p1.add(jtfLblQuantity);
            p1.add(jtfDescription);
     
              // Set absolute coordinates for fields and labels; X,Y,W,H
               jtfitemName.setBounds(20,20,50,50); 
               jtfQuantity.setBounds(40,40,50,50);
               jtfDescription.setBounds(50,50,50,50);
     
        }
     
     public static void main(String[] args) {
              Ratsac2 f1 = new Ratsac2();
              f1.pack();
              f1.setSize(800,500);
              f1.setTitle("Shopping Cart");
              f1.setLocationRelativeTo(null); // Center the frame.
              f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f1.setVisible(true);
              f1.setResizable(false);
          }}
    P.S. I haven't added everything to the frame yet, just trying to get the three with bounds to appear on the frame. I hope this is easier to understand for you.

    -- Update --
    Declared labels properly, to be added to the frame.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,051
    My Mood
    Mellow
    Thanks
    184
    Thanked 650 Times in 637 Posts

    Default Re: Need help with my code! Absolute coordinates

    The itemList combo box is initialized under where the labels are created.
    No, it's not.

    This is declared:

    JComboBox ItemList;

    This is initialized:

    ItemList = new JComboBox();

    This is declared and initialized:

    JComboBox ItemList = new JComboBox();

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,342
    My Mood
    Hungover
    Thanks
    143
    Thanked 625 Times in 536 Posts

    Default Re: Need help with my code! Absolute coordinates

    Why are you using a null layout in the first place? Just use a layout and let Swing do all the hard work for you.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    Junior Member
    Join Date
    Sep 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code! Absolute coordinates

    Using a null layout because I require some absolute position to accurate put all my elements where I want them. I have to do everything in code, so.. I'm not too familiar with Java layouts myself...
    But I did identify the issue.

    // Add the panels to the frame.
    add(p1, BorderLayout.NORTH);
    add(p2, BorderLayout.SOUTH);

    something I looked over, panels are added to the frame after I add the elements to the panels. Thanks for the help though.

    One more question though... How do I go about performing a forumla with an integer from a combo box, and then a dobule from a text field? I kind of know how to go about this, but I'm not sure how to do it within one iteration.

    Here's how I've attempted to do it...
              int i = Integer.parseInt((String)jcbQuantity.getSelectedItem()); 
              double o = Double.parseDouble(jtfUnitCost.getString()); 
              jtfRunningCost = (i * o);

    It returns with this error:

    Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1011)
    at java.lang.Double.parseDouble(Double.java:540)
    at ratsac2.RatSAC2.<init>(RatSAC2.java:273)
    at ratsac2.RatSAC2.main(RatSAC2.java:314)

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,342
    My Mood
    Hungover
    Thanks
    143
    Thanked 625 Times in 536 Posts

    Default Re: Need help with my code! Absolute coordinates

    It's almost never a good idea to use a null layout. Use a real layout. What happens if the screen is resized or if you want to add/remove a component?

    That error is telling me that the argument being passed into parseDouble is an empty String, which isn't a number and can't be parsed. You'll have to step through this with a debugger or at least add some print statements to figure out why the String is empty.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #11
    Junior Member
    Join Date
    Sep 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help with my code! Absolute coordinates

    Quote Originally Posted by KevinWorkman View Post
    It's almost never a good idea to use a null layout. Use a real layout. What happens if the screen is resized or if you want to add/remove a component?

    That error is telling me that the argument being passed into parseDouble is an empty String, which isn't a number and can't be parsed. You'll have to step through this with a debugger or at least add some print statements to figure out why the String is empty.
    The idea is that this program has a set resolution and that resizing is disabled. It's just in the criteria. Also, yeah. I'll figure that out today.

Similar Threads

  1. absolute and relative path
    By viper_pranish in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 20th, 2013, 10:34 AM
  2. absolute beginner needs direction
    By action711 in forum JDBC & Databases
    Replies: 2
    Last Post: March 8th, 2013, 07:55 AM
  3. Absolute beginner with errors in code
    By Robl in forum What's Wrong With My Code?
    Replies: 9
    Last Post: February 13th, 2013, 07:13 PM
  4. Literally, what's wrong with my code? Separating X and Y coordinates.
    By liamb109 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: October 9th, 2012, 07:53 AM
  5. [SOLVED] Absolute Beginner Here, should be an easy question for anyone really.
    By Harrald in forum What's Wrong With My Code?
    Replies: 27
    Last Post: July 31st, 2012, 09:40 PM