aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes GUI Pieces and Parts Not Sticking! Help! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "GUI Pieces and Parts Not Sticking! Help!" Watch "GUI Pieces and Parts Not Sticking! Help!" New topic
Author

GUI Pieces and Parts Not Sticking! Help!

Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
As you will soon catch on, I'm very, very unknowledgeable about Java...well, any programming really. I'm just learning. I've been trying to sort out exactly what I need to create a GUI interface for a program I've already written. And, yes, the GUI interface is an assignment.

My problem is this: what do I need and in what order or structure do I code it? (Here's a little background: I've been studying the simplest chapter on GUI components in my text book, as well as referencing the Java API and my three Java for Dummies books (yep, 3). I think I understand that I need a JFrame, JTextFields (for user input), a JCheckBox could be used, JOptionPanes (for input dialog and message dialog), and a JComboBox for selecting from a list of choices.

Question: Did I leave any important component out?

Question: Should I use JTextfields (but make them uneditable) to show the result of calculations based on user input or is there a better component?

Question: Do I need to nest a component (like JTextField) inside another component class? If yes, which component? (I'll do my best to figure out how to nest it if someone will just give me little hint.)

I'm sorry I'm having to ask this, but I have a disorder that makes it very hard to focus when I'm under stress (and I've had some doozies hit me the last two weeks). This is all so new, and so much. I just need a little help in unraveling it.


Disclaimer: The author of this post makes no claims, implied or otherwise, as to her ability to understand anything but the simplest of answers. Further, the author of this post has no programming background whatsoever and has taken one Java Programming class which was 9 weeks long. She does want to learn, so please teach patiently.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Well, it depends on what you mean by "not sticking." Can you be more specific? My guess is that you are not using a Layout Manager correctly. See Swing Tutorial - Laying Out Components Within a Container.

(For other topics, the Swing Tutorial contents page is here.)

In general, I strongly suggest that you start small. Before writing a mountain of code trying to cram all of these components together in one shot, just get 2 or 3 components to display correctly. Once you get that to work, then gradually add components, and see how it looks before moving on. This will save a lot of time, making it much easier to debug and correct problems early so you can move forward on the right footing.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
The subject line was just me trying to laugh off my frustration--GUI (gooey) stuffy is usually sticky. That's all.

I do everything small, already. I'm just learning so nothing is a bigger headache than 10 error messages and not having a clue what the real problem is. So, I write in pieces, compile, execute, and debug before I add anything new.

However, I don't know exactly how to fit these GUI components together. The examples I have to go by are tiny programs, not so much pieces put together. I have an example for labels; I have an example for text fields; I have an example for check boxes, one for combo boxes, etc. But they are separate little programs. I do not have one cohesive example of all of these components represented in an application.

Do you have a better understanding of my problem?
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
I took a look at the Layout Tutorial and it has only made things more confusing. I really want to keep this as simple as possible, but I want to use the proper components. I have a text-based version of the program I am trying to create a GUI for. Oh, and, by the way, this is a class project but it is one I already did and turned in. Yes, I can hear you now, "If she's already turned it in then why...?" It wasn't correct, and I knew it. I had to turn it in though. Unfortunately, my instructor did not give me any good feedback on how I could have done better. My classes are online. My instructor is in another state, altogether. And there seems to be a language barrier... thing... I don't know.

Java Ranch is the one and only resource I've found that is remotely friendly and truly helpful. I don't know squat about programming but I know quite a bit about computing in general for a personal user. Most tech sites are snobbish and shrug off beginners, so I usually avoid them like the plague.

But I've had great experiences here. As a result, I've told my instructor, Academic Advisor, and other classmates about this site.

Now, what is it specificly that you need more specifics on? I thought my original post and questions were very specific, but apparently I was wrong.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

What do you have so far? And which part are you stuck on?

If you haven't created a GUI yet, I think a good start would be to display a field for user input, and then write code to "get" that input and print it out to the console. If you can get that to work, you will have a good basis to move forward.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Okay. I can write a JOptionPane.showInputDialog. I've also been working on how to code JTextFields. JOptionPane is going to be the simplest, isn't it?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

A JOptionPane is fairly easy because it's a "pop up," so you don't need to fit it into the GUI frame. Is that what you want? Or do you want an input field to stay put on your screen?

Can you describe how the user experience should be? What do they see first? (Is it a frame with a bunch of stuff already laid out? Or is it some pop-up dialogs asking for input?) What do they do with that? What happens when they provide input?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Since this is a Swing topic, I'm moving this to our Swing forum. Please continue there.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Since this is my first GUI, and I write what I call Kindergarten Java, the user experience will be very simplistic.

The program is an Inventory program. The product is, more specifically, movies, TV/Cable series, Anime/Manga... you know, pretty much anything that is sold on DVDs. Therefore, the input needed from the user (think store clerk or owner of store that specializes in movies, etc.--but not a video rental place) would be:

Movie Title

Academy Award (basically, 0 if movie is not a winner; 1 if movie is an Academy Award winner)

Genre or type of movie (I have 14, using zero for "Miscellaneous" category so I could take advantage of the element indices in the movie array)

Unit Price

Units in Stock

Based on unit price, a calculation would determine a restock fee (Yes, I know this would normally apply to a video rental place, but I don't have to track all of the info one would have to track in a video rental store.)

Restock rate is 5%, so I have assigned 0.05 as the value for restockRate variable.

Retail Price would be the total of unit price + restock fee.

Title Inventory would be the sum of the retail price * units in stock.

Product Information on the movie just entered would be displayed as follows:

Title, Oscar Winner, Genre, Unit Price, Restock Fee, Retail Price, Title Inventory value.

The code is a sentinel controlled loop that terminates when "quit" is entered into the title field. Once the sentinel value is entered, the value of entire inventory is displayed.

I have written the code for JOptionPanes to take advantage of the showInputDialog with success. However, I could not get my product information to display. I kept getting errors and couldn't figure out why. So, I thought perhaps I was asking too much of a simple component.

I even figured out how to convert the String entries to double, int, or whatever I needed the value to be. The application compiled when I didn't have the JOptionPane.showMessageDialog code. That's why I figured it was my naivete was leading me to attempt to use the JOptionPane.showMessageDialog inappropriately. Which lead me to think I was trying to do too much in too simple an environment.
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Originally posted by Robin Lane:
[QB]
The code is a sentinel controlled loop that terminates when "quit" is entered into the title field. Once the sentinel value is entered, the value of entire inventory is displayed.

This will work well with a "linear" program, but once you start creating more advanced GUI/event-driven programs, you'll need to ditch the sentinal controlled loop, or whatever it's called.

I have written the code for JOptionPanes to take advantage of the showInputDialog with success. However, I could not get my product information to display.

What displays instead? Anything? Or do you crash? How do you try to display it and where? In a JOptionPane?
I kept getting errors and couldn't figure out why. So, I thought perhaps I was asking too much of a simple component.
Nah, not asking too much, though you may want to give us more information: code in code tags and actual error messages.

Good luck.
Jacob Steingart
Ranch Hand

Joined: Mar 28, 2008
Posts: 63
Originally posted by Robin Lane:
The subject line was just me trying to laugh off my frustration--GUI (gooey) stuffy is usually sticky. That's all.

I do everything small, already. I'm just learning so nothing is a bigger headache than 10 error messages and not having a clue what the real problem is. So, I write in pieces, compile, execute, and debug before I add anything new.

However, I don't know exactly how to fit these GUI components together. The examples I have to go by are tiny programs, not so much pieces put together. I have an example for labels; I have an example for text fields; I have an example for check boxes, one for combo boxes, etc. But they are separate little programs. I do not have one cohesive example of all of these components represented in an application.

Do you have a better understanding of my problem?


I do believe that you are in need of sorting out your ActionListeners. There is probably a tutorial somewhere about creating these that has specific code, but I'm here for the main idea. Basically, when you let your code do something, you need something to get input from the user (eg a button), something to see if anything is happening (the ActionListener object), and then commands to do something when the ActionListener "hears" the button do something. In a program with a single ActionListener, you create a class that implements ActionListener, create your JFrame from it, add a widget BUT that is all done in a seperate method from main(), at least not with my programs. All that main does is create an instance of the class that just implemented ActionListener and tell the JVM to go run the method that has the creation of the JFrame and JButton in it. In that method, you only want to create intances of JFrame and JButton, not set any of their variables or add the button to the JFrame instance, because you first need to get your implement of ActionListener to actually become a Listener for your button. If your JButton is called myBtn, the line would look like this:

This tells the JVM to add an ActionListener that is of the type of whatever class/object you are in, in this case the class that implements ActionListener. Then you need it to do something so you use the actionPerformed method. So how do you get it to listen to different widgets? You make different classes to listen to different instances! You might create a BtnListener that listens to a button, and a CheckListener that listens to a checkbox. Both implement ActionListener or else they won't be able to "listen." In the other class that has your main code with your JFrames and JButtons and whatever else you have in there, you also have code that will instantiate the other class. This is done with our helpful little addActionListener() method. Instead of saying

This tells the JVM to add a listener of the BtnListener class to the list of myBtn's listeners.

If you've read this far, you must be really patient. I hope I was helpful.


I never know what to put in my signature...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Robin Lane:
...I have written the code for JOptionPanes to take advantage of the showInputDialog with success. However, I could not get my product information to display. I kept getting errors and couldn't figure out why...

Maybe this is the place to start. Can you post the code and the error messages?
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
(feeling enormous relief and gratitude) Thank you. Here's my Kindergarten code:



I recompiled my code just to make sure it was compiled. I also tested it by running it. So, it does execute.

However, I did delete my JOptionPane.showMessageDialogs because the kept the program from compiling and I had to get it turned in to my instructor. I thought it was better to have an executable program that fell short than a program that wouldn't compile because it was a mess.

This is how I was attempting to display product information:



At first it displayed as expected, but then it wouldn't. I was trying to isolate when it stopped displaying. My process was to make sure the program would compile and execute before I added anything new. Then, compile, debug, re-compile, and execute. I bet I compiled and re-compiled 50 times... on that tiny little bit of code. (sighs)

I think I may have an idea on why the Message Dialog stopped displaying. It may have been after I added my conversion code to convert the price and units in stock from Strings to a double and an int, respectively. The Message Dialog is concatenating, right. Only Strings can be concatenated, correct? So, is my String value lost after I convert it to a number? Making my JOptionPane.showMessageDialog trying to concatenate a String (title), a double (original price), and an int (product number)?
[ June 03, 2008: Message edited by: Nathan Pruett ]
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Oh, yeah. One more thing. The if...elses were my pathetic attempt to assign the String value for variable genre using category (an int). Sad, isn't it?
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Update so you will know I'm still trying to figure this out and not sitting around waiting for the answer to be handed to me.



I added them one at a time, recompiled, and executed before adding the next, etc. Currently, all display properly, though not as I'd like. I'd much rather have one pop-up to display all of the product information together. In order to do that, would I have to go to a more complicated layout (shudders in fear!)?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

Robin, please use the edit () button if you need to update your posts. Two posts within two minutes is really not necessary.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Originally posted by Robin Lane:
Java Ranch is the one and only resource I've found that is remotely friendly and truly helpful.
Was I away at the time?

Jacob (and Robin): Be careful about books (or even online tutorials) which recommend addActionListener(this). I appear to have written about that very recently here. On close examination that is a 2-year old thread which somebody found yesterday. But, Robin, that is not your particular problem at the moment since you don't actually have any ActionListeners!

What you have at present is a set of JOptionPane dialogues which appear and vanish, leaving you with a set of local variables. You ought to have not problems with String concatenation and numbers; if you try to concatenate "Robin owes Campbell $" + 1000000000 it will print out correctly, so that's not the source of your problem. I can't see any reason why the dialogues don't display correctly; you must have got the correct arguments or it wouldn't have compiled. You will by now have worked out that passing null as the 1st argument makes it appear in the centre of the screen, and you will have noticed its annoying habit of hiding behind other windows.

I suggest you work out what you are planning to show on your dialogue, then rather than JOptionPane.showMessageDialog( you precede it with System.out.println( . . . At least that way you will know you are getting your String right.
Try using a StringBuilder or the format method of the String class to make up your long messages.

You can reduce your
else if (category == 2)s to a switch block. Or an array of genre names, but make sure your input number is in range.

Your main method is getting unmanageably large. You will need to break it into smaller methods. You also need to get away from static methods into instance methods.

Are you really ready to dive into showing a proper GUI? Consider yourself about to be dropped in at the deep end. If you aren't ready, stop reading now.
  • Go to this link: The Swing Package.
  • Right at the bottom of the page you will find a section headed "Swing's Threading Policy."
  • Copy the 1st example, before "or".
  • Import the classes javax.swing.SwingUtilities and javax.swing.JFrame. You don't have to import Runnable.
  • If you don't know what String[] args means, delete the references to args in the MyApp constructor and constructor invocation.
  • Give MyApp a better name.
  • Put an instance field of type JFrame into the class.
  • Do 3 things in the constructor 1: Initialise your JFrame new JFrame("Robin's App"), 2: set its Size setSize(200, 100), 3: set its closing operation setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
  • In the run method invoke the setVisible() method on the JFrame, passing true as its argument.
  • Check carefully in the JFrame API whether I have spelt any method wrongly. I am afraid it isn't a pretty GUI. Sorry.

    And good luck with it. Make sure to come back if you have any problems.
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    Originally posted by Rob Prime:
    Robin, please use the edit () button if you need to update your posts. Two posts within two minutes is really not necessary.


    Rob, my apologies. Thank you for the helpful suggestion, and I'll try to do better in future. I'm still very green at this forum thing, as this is the first site I've found to of any assistance to people like me. Hence, I don't have much experience at posting, etc.


    quote:
    --------------------------------------------------------------------------------
    Originally posted by Robin Lane:
    Java Ranch is the one and only resource I've found that is remotely friendly and truly helpful.
    --------------------------------------------------------------------------------

    Was I away at the time?


    Actually, Campbell (you superb person), I credited you in the description of a program I submitted to my instructor a few weeks ago, because you gave me three days of your time in order to help me correct and refine a loop I needed! Fred Rosenberger was most recently credited in in the description of a program I submitted, because he helped me take a switch and replace it with an array.
    [ June 03, 2008: Message edited by: Robin Lane ]
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    Stop embarrassing me. If Rob sees that he'll never give me any peace.

    Have you got any farther with your GUI? Or have I confused you totally?
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    Rob's just jealous! Well, as soon as Rob does something superb, I'll call him a superb person, too!

    Okay... my GUI. (takes deep breath) I got my GUI to the point it executes and executes properly (though not superbly) However, for it to operate superbly and be poised to go the next level (that would be GUI First Grade) I have to be able to code a JFrame, JTextFields, JLabels (maybe), JCheckBox, JComboBox, and a much better display format than what I have currently.

    I need to be able to display product information on one pop-up (or whatever) that would show movie title, product #, genre, original price, restocking fee calculated, retail price (original price + restocking fee), units in stock, and the title's inventory value (retail price * units in stock). JOptionPane.showMessageDialog just won't work and look decent. My next assignment requires the program be modified to add a pair of buttons (Forward and Back) to allow the user to scroll through the product inventory by title. So, I'll have to sort by product # or alphabetically by title.

    But first things first.

    I need to take what I have and make it more sophisticated than JOptionPane.showInputDialog and showMessageDialog. I'm thinking that my initial screen would list the options Add, View by Product, View Inventory Total... unless it would be easier to just add the Forward and Back buttons to the Add screen. In which case, I wouldn't need the View by Product screen, would I?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    Originally posted by Robin Lane:
    [QB]Well, as soon as Rob does something superb . . .[/B]
    Rob is a superb chap.

    You have presumably been told to go little by little?

    Suggest you add a text area to your JFrame (just use the add() method of JFrame), then get all your JOptionPanes up again, then when you have got all the text together into a single String, put it onto the text area with its setText() method.

    You will notice that whenever you get to a Component in the API it gives you a link to the Java Tutorial. Make sure you follow and read those links.

    You will also have to learn about Layouts. JFrame uses Border as a default, which means you can add Jpanels in 5 places and put something like Box or Grid on those panels. If you add a single Component to a BorderLayout and don't give any parameters it goes to the centre.
    You can put the whole lot onto a single JFrame using GridBag or Group, but they are more complicated to use.

    As I said, little by little.

    For entering data onto your app useand it is probably easy to lay out with a GridLayout with 2 columns.
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    Rob is a superb chap.
    I'll take your word for it, Campbell, but nobody gets to be called 'superb' by me until they are 'superb' to me. (starts laughing)

    I was working on my re-design (on paper, believe it or not!) for my GUI, and I thought that BoxLayout with JTabbedPane might work well for me. GridLayout seemed a bit more complicated. BoxLayout gives the horizontal or vertical options with additional rigid or glue options. However, I know you have a much greater understanding of the GUI components and how they work. Given that you have the knowledge I do not, do you think the BoxLayout within a JTabbedPane environment would work? I thought what I could put JTextFields on Tab 1 for the user input (movie title, genre number, whether the product is an Academy Award winner, original cost, and units in stock for that title. Then, Tab 2 could show info like the assigned product number, calculated restocking fee, calculated retail price (original price + restocking fee), and title's inventory value (retail price * units in stock). Tab 3 could display all product info and/or total inventory value. I think I would need to use JPanels to place my components for each tab, wouldn't I?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    JTabbedPane? You are obviously taking the really easy route to a GUI.

    Yes, I think what you suggest would work nicely.
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    Campbell, I've had 8 weeks of online instruction on Java. I have no previous programming experience. I'm smart enough, but we are talking only 8 weeks. And we only got into GUIs a week and a half ago. Now, I spend anywhere from 8 to 14 hours a day, 5 - 7 days a week studying, but, yes, easy was what I was thinking, if it will accomplish what I need.

    After all, everybody tells me to try to keep it simple, take baby steps, and use what will get the job done (as opposed to what will get the job done with glitz and glitter).

    However, I really want to learn. If you think I can do better, then just suggest a better component combo, and I'll work on it. I was thinking of using a JCheckBox to indicate if the movie is an Academy Award winner. I, also, thought that a JComboBox would be a good implementation to use to select movie genre. Will those components work in a JTabbedPane? Or do I need to go a little deeper?
    Jelle Klap
    Bartender

    Joined: Mar 10, 2008
    Posts: 1773
        
        7

    Originally posted by Robin Lane:
    Campbell, I've had 8 weeks of online instruction on Java. I have no previous programming experience. I'm smart enough, but we are talking only 8 weeks. And we only got into GUIs a week and a half ago. Now, I spend anywhere from 8 to 14 hours a day, 5 - 7 days a week studying, but, yes, easy was what I was thinking, if it will accomplish what I need.


    I think he was being sarcastic...


    Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    Originally posted by Jelle Klap:


    I think he was being sarcastic...


    (starts laughing) Am I that easy a mark?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    Originally posted by Robin Lane:
    Am I that easy a mark?
    Yes.

    Originally posted by Jelle Klap:
    I think he was being sarcastic...
    Yes, I was.

    Yes, it will work, but it will take a lot of effort to get there.

    Do it bit by bit. Write 3 lines of code, compile it and execute it. Write 3 lines of code, compile it and execute it. Write 3 lines of code, compile it and execute it. Write 3 lines of code, compile it and execute it.

    That way you will have some idea what is going wrong.

    Write small applications which do a small part of your functionality, and get them working.

    I have had to do that myself, and I can assure you, yes it will work. And after the effort you will remember it.

    You do realise that there is a page in the Java Tutorials for every well-known Swing component explaining how it works?

    Suggest you read the classic GridBagLayout tutorial. Find Cai Horstmann's GBC class and how it makes using GridBag easier. If you ever get GridBag to work (and it is by no means easy) you can put every component onto a single base (eg Pane of JTabbedPane). There are alternatives (search the boards for MigLayout and go through the API for GroupLayout), but using one of these will give a nice appearance and probably a few extra marks.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    Originally posted by Robin Lane:
    I'm smart enough . . . I spend anywhere from 8 to 14 hours a day, 5 - 7 days a week studying.
    However, I really want to learn.
    We know It is precisely because we can see you are prepared to put so much effort into it that we are prepared to help.
    Robin Lane
    Ranch Hand

    Joined: Apr 30, 2008
    Posts: 76
    (impetuously gives Campbell a big virtual hug, then draws back and gasps at her audacity) I keep forgetting that extroverted American Southerners tend to embarrass you reserved British types. Yes, I'm making an assumption that your British (even though your profile only says U.K.), and I base it on your quick trip to a state of embarrassment and your use of the word chap! (starts laughing)

    I have already been working on my coding for the JTabbedPane. I will do as you suggested, because 1) your obviously knowledgeable and 2) it's the way I work anyway. Code, compile, debug, re-compile, execute, code, compile, debug, re-compile, execute.

    By the way, I write my programs in Notepad. That's right--Notepad. I don't use an editor, because I need to thoroughly understand the language of Java before I go trying to make it easier. Learn the hard way and I'm not as likely to forget.
    [ June 05, 2008: Message edited by: Robin Lane ]
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39409
        
      28
    Originally posted by Robin Lane:
    Notepad.




    Dreadful program. Don't use it. Get Notepad++ or Notepad2 instead. They are far better for writing programs with, supporting syntax colouring, automatic indentation and bracket highlighting.

    And you seem to be coming along well. Well done.

    ----------------------------------------------------

    Disclaimer: One of the links posted appears to be the UK version. It will print all over your code if you embarrass it.
     
     
    subject: GUI Pieces and Parts Not Sticking! Help!