GUI in Java using Swing

99封情书 提交于 2019-12-23 15:24:41

问题


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



来源:https://stackoverflow.com/questions/5837325/gui-in-java-using-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!