Mihai Neacsu
Mihai Neacsu

Reputation: 2115

Basic Java GUI design

In the GUI book we use in class there are many examples of how graphical user interfaces are made in Java. So many examples, that I'm very confused regarding which one should be used when it comes down to a big application.

So I've seen examples

Sure, I can work with all of these, but right now, as I don't have any kind of experience, I don't see the benefit of using any of them. Is actually one of them the correct way to do it or it depends on my sittuation?

Thank you!

Upvotes: 6

Views: 675

Answers (4)

Adi Mor
Adi Mor

Reputation: 2165

in which the main class extends JFrame

  • the main calss doesn't have to extend JFrame. if it doesn't you should create a JFrame object like you do with any other class

where the JFrame object is created inside the main method

  • If the MainClass extend JFrame it created inside the c'tor (in the super() ).

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168845

"Is A" or "Has A"? This is the question that should be asked when considering extending a class. If the new class "Is A" frame, extend frame, but if the class just needs a reference to a frame, don't extend.

In fact, if a custom component is required, extend a JComponent or JPanel, then add that to a frame, ..applet, window, JInternalFrame, dialog, constraint of a layout, part of a split pane..

Listeners

As to the listeners. Rather than traverse a huge if/else structure in the single actionPerformed() method to determine the required action, it is more optimal to either:

  1. Create a listener for each control that needs it.
  2. Create an instance of an AbstractAction that might be used for multiple controls ('copy' button, menu item etc.).

Summary

So (generally) for the:

  1. JFrame, don't extend.
  2. Listeners, create and add as needed.

Upvotes: 6

mishadoff
mishadoff

Reputation: 10789

Standard approach: use EventQueue in method main, that creates main form. In that case all your operations will be asynchronous

Upvotes: 0

Mechkov
Mechkov

Reputation: 4324

Honestly, it depends on the situation. One basic rule when coding is to "code to abstract classes or interfaces".

So, in a nutshell, have a class extending (or implementing) a JFrame (or whatever interface or class) and/or have one doing the same thing with ActionListener.

It is all about the maintainability, flexibility and cleanness of your code.

Upvotes: 2

Related Questions