GUI in Java using Swing

2019-06-28 04:30发布

问题:

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.

回答1:

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!


回答2:

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.



回答3:

There are also some pretty good tutorials