4

I really need some guidance on how to create a GUI in Java. I'm a student in college and it's one of the the thing they never focus on. I currently have the rest of my program set up and working and now I'm trying to make the GUI. I'm creating a new GUI class for this. (I'm under the impression that this is the best practice for this). I kind of understand how to make the basic setup but I don't understand how to interact with the the GUI afterwards. What I want to do is make a window on startup and then it displays two pictures side by side with a label for each underneath. I want the images to be clickable and when clicked two new images are loaded in their place(labels are changed to underneath). I haven't done anything like this and I've also ran across a lot of different ways to add an image and I'm wondering if there is a best practice.

I can provide code if needed but I didn't think it would be needed with how my question is posed.

Thanks in advance for all the help.

Rumel
  • 917
  • 1
  • 9
  • 21
  • 9
    you should probably start reading the [Swing trail](http://download.oracle.com/javase/tutorial/uiswing/). – asgs Apr 29 '11 at 20:58
  • 1
    If you are using an ide Netbeans has some great tutorials as well http://netbeans.org/kb/docs/java/quickstart-gui.html – grantk Apr 29 '11 at 21:07
  • "how my question is posed." Just a point that a question ends in '?' and that text is lacking a '?'. To put that another way - there is no question. – Andrew Thompson Apr 30 '11 at 04:06

3 Answers3

7

Some suggestions:

  • Put your images into ImageIcons. Consider having an ArrayList of ImageIcons.
  • Display your ImageIcons in a JLabel. You can change the icon by calling setIcon(...).
  • Display your text in the same JLabel (or if you desire, a different JLabel held beneath the image JLabel both held by a BorderLayout-using JPanel). Change the JLabel text via its setText(...) method.
  • Add a MouseListener to the image-holding JLabel and change the JLabel's icon in the listener's mousePressed method. You can get a reference to the label clicked via the mousePressed MouseEvent parameter's getSource() method.
  • The tutorials mentioned in asgs's comments will help you with all of this.

Edit 1:

  • Even better -- go with Puce's recommendation in the comments below my post!
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 3
    Or display die imageicons on JButtons (you can unset the border, if you don't like it). Then you can listen for ActionEvents (high-level) instead of MouseEvents (low-level). – Puce Apr 29 '11 at 21:32
3

Two personal tips from my 5-years experience in Swing.

Learn to write GUIs with LayoutManagers instead of a GUI builder. (MigLayout the best choice)

Learn how to write a TableModel instead of using the DefaultTableModel.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
0

There are also some pretty good tutorials

Greg Adamski
  • 1,099
  • 7
  • 7