I am new to Java and Netbeans, and want to write a Swing project to learn by.
Naturally I want to separate the "guts" of the code from the GUI class.
How should I go about it, best practice ?
Should I:
Use public static void main(String[] args) in the GUI class. Then
create an instance of a "controller". Calling controller functions
via GUI events (passing only data) ?
Use public static void main(String[] args) in the "controller",
and pass an instance of the controller to the GUI class ?
Create instances, or use classes statically ?
And what of this invokeLater business ?
[ some little code samples would be lovely ]
Thanks.
Anthony.
Three: Put main() in its own class and intitialize all objects as needed.
I'd create a Main class or other entry class that contains main. This would be responsible for preparing the system, initialising common library elements and general house keeping.
As to which element needs to be "started" will depend on the structure of your code and your implementation of the MCV
Related
I am a newbie in java and I am working on a small university project, I have about 30 classes.
My project is to develop a game about constructing a city, and my expected game should include following features:
different kinds of construction(roads, building, and rooms) and inside objects (exit);
interaction between players and game objects, for instance, players can enter/leave the room.
I am just trying to avoid getting my main class so big with different objects, for example my game will be about 20 buildings and each building has different number of rooms and exits..
For reaching the design, I need to solve following questions:
Do I have to write all these objects inside the main?
Can I build it in another class for starting the game with players in the main?
I'm interpreting your question as being how to split up responsibilities to avoid classes becoming too cluttered and complex. That's a very good question but unfortunately there's no simple answer: there are many techniques and the ones that will work best in your case will depend a lot on your problems space.
You may have heard of the Single Responsibility Principle. Essentially this means that each class has responsibility for a single piece of functionality. Taking to its logical extreme this will mean your code will have many small classes that just do one simple thing. The only reason to change a class is if that one thing changes. So, for example, your main method might be responsible for staring the UI, but not setting up all the game data.
So how do you achieve this? There are several techniques for splitting logic out from a class to avoid it becoming long and cluttered but the most important (IMO) is Delegation. This involves delegating a piece of functionality to another class and then calling methods in that class.
For example:
class Game {
public static void main(String[] args) {
Game game = new Game();
game.setUpUI();
game.configureGameData();
game.start();
}
public void setUpUI() {
}
public void configureGameData() {
}
public void start() {
}
}
Might become:
class Game {
private final UI_Maker uiMaker;
private final GameData gameData;
private final GameStarter gameStarter;
public static void main(String[] args) {
Game game = new Game();
game.start();
}
private void start() {
uiMaker.makeUI();
gameData.loadData();
gameStarter.start();
}
}
This structure has a lot of advantages:
its generally more obvious to the reader what the class does
the delegates should be individually testable
you can change the implementation of the delegate without impacting the user
you can reuse delegated functionality elsewhere
refactoring structures is more straightforward
You can create the classes in the same package as the main(separate java files for the main, buildings, players, etc.) and as long as each class is public or protected(protected allows objects or variables to be accessed anywhere inside the package you are currently executing in), you will be able to create those objects in the main as you please.
As for creating the game, you will want to call the classes to generate the map in the main first then buildings, players and whatever else you need. Then call the methods on the objects that you need to run however your game is supposed to work.
This may seem like a stupid queestion to most of you, but I have been learning Java using BlueJ, and BlueJ is created for learning, and as such Main Methods are not necessary given the BlueJ extensions provided by my University.
Therefore, now that I am playing around in both NetBeans and IntelliJ - I really want to get a good idea of when to declare a Main Method.
I know the Main method is the entry point of a package when it is compiled and run. But that is the extent of my knowledge.
If I am to build some apps in a full blown IDE, should I place all of my Class methods within a Main Method? Should the Main method be seperate from all others? Do I declare instance Variables within the Main Method?
Are there any good sites, or tutorial materials available that can help me structure my BlueJ Java knowledge into an IDE that requires a Main Method?
Thanks
Ok.
Main method is an entry point to your application.
If you watch any Java related tutorial, you'll probably see something like this.
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
This has been taken from Oracle's website.
When working with IntelliJ, you'll be presented with a package main on the top, or something else.
You see. Java unlike some other languages distinguish between namespaces using those packages. Think of them as a little packages full of Java classes that you can reuse.
For example, if you look at Log4J's repo => here, all these folders are essentially packages.
That way you can have many packages, and a single file that will trigger your main method, and start everything else.
That's how it's usually done.
But if you really want to learn Java from scratch. My suggestion is go to YouTube. Derek has done some marvelous job with his tutorials.
Best of luck.
While technically you can have more than one main method, for most use cases you only need one.
You should define it where it makes sense to do so in some "central" class responsible for bootstrapping your application and getting everything going.
The main method is static though so it can't access your class' instance. Typically this is how you'd get around this.
class TicTacToe {
public void theEntryPointToYourApplication() {
// ...
}
public static void main(String[] args) {
// This doesn't necessarily have to be the same class where you
// defined your main method
TicTacToe ticTacToe = new TicTacToe();
ticTacToe.theEntryPointToYourApplication();
}
}
This is just a small example though there are many ways and different approaches depending on your specific use case and needs.
Personally I have never used BlueJ.I've always been a netbeans fan.But the answer to your question is a general rule that most of the Object Oriented Programming Languages follow.You know that main method is the entry point of a package when it is compiled and run.Let me explain it in simple language.
Consider a soccer game.Assume that the field is the main method.The players are different functions.You are free to define any number of functions, but only 22 functions are called in the field.The whole game is controlled and played by these 22 functions only.So what do you learn from this?
We learn that java is only concerned with what is present in its main method just like the fans sitting in the stadium are only concerned with the 22 players who are currently playing.So if a programmer is writing a small program,normally the whole logic goes into the main method.But if its a large program,the program is distributed into various modules/functions and then these functions are called in the main method so that they get executed.
We can write a java program with one non-public class containing a main method -- it'll compile and run just fine. Why do people make the main class public?
Is there any benefit?
There is no benefit of making the class public for the sake of it having a main method.
That being said, there isn't really much of a reason not to either. Chances are the main class is either going to be very short with few, if any, substantial methods in it, or it's going to be baked into one of the core classes like
class Server {
public static void main(String[] args) {
Server s = new Server();
s.start();
}
// rest of Server class here
}
And typically those core classes are something you'd want to be public.
But this isn't about the benefits of having classes be public. This is about the benefits of having a class be public because it has the main method and there are no direct benefits as a result of that.
Simply because clients will have access to create objects of your class based on the accessibility you specify for your class. If you look at Java source libraries you will see lot of private (inner classes) classes too. Depends whom do you want to allow access to create objects of your class.
Benefit you will have only when classes you are using in main method doesn't belong to same package.Public class will have visibility across all the packages.
I created a class A that reads a text file and alters some lines within the text, and the code is written in main() of this class. I also created another class B that has a Frame, the Frame contains a list of text files of a directory and a button. What I don't know how to do is this: When I click on the selected item on the list and click the button, the function main is called and the selected item is being read by main().
Any suggestion is welcomed and thanks in advance.
When you have code in the static main method, you have a non-object oriented code block, one that won't easily be used by other object oriented-compliant portions of your program. The best solution here is to get all code but the minimal out of main and create a true OOP-compliant class, one that can be more easily used by your other classes.
Your other issue is the mixing of your text-processing code with your GUI code, and this may require further fixing, especially if the text-processing code takes a while to complete or is a CPU hog. If so, you'll need to take care to do the text-processing in a thread that is background to the GUI thread, and again, this is much more easily performed if the text-processing code is in a well-behaved OOP class.
The main method is just like any other method, you call it the same way.
class A {
public static void main(String... args) {
String filename = args[0];
}
}
class B {
public void onFilename(String filename) {
A.main(filename);
}
}
You might want to use a background thread instead of locking up the GUI while it is processing. ;)
How much logic do you normally put in the main class? Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
If you have any suggestions on this topic (or external articles), I'd appreciate it.
For small tools, I'm happy to have most or all of the logic in the main class - there tends to be less of a model to work with. (For very small tools, I confess I usually don't bother with unit tests. In particular, there's less benefit on the design side of things than there is if you're building something which will be a component in a larger app.)
For large scale apps, the main class is really just involved with setting things up and getting them in motion. If you're using a DI framework that can be very little code indeed; if you're not using dependency injection then the main class often acts as a "manual" dependency injection framework.
Should logic in the main class be at minimum, only instantiating other, specialized classes, and running all the tasks from there?
Yes. main method and its surrounding class should ideally be used only as an entry point to start the program. The mere existence of the surrounding class is just an artifact of the way Java programs are composed (everything must be inside some class), and there's no reason why it should contain other stuff in addition to the main method (but there definitely are reasons why it shouldn't).
When you get the interesting classes (those that form the actual program) separated, you open doors for all kinds of flexibility. Perhaps some of those classes could be used in some other projects. Perhaps some day you'll want to replace some of them with better implementations. Maybe you'll find a better order to instantiate all those classes - so just swap a few lines. Or how about executing lengthy startup loadings and instantiations in parallel threads? Just wrap some of them to suitable Executors. Good luck trying this with a 1000+ line main class.
This kind of flexibility matters for everything except maybe for 100-line elementary examples, prototypes and such. But given that even small tools tend to grow, why not do it correctly right from the beginning?
It's not so much a question of whether a class is "the main class". It's a question of how much logic is in the public static void main(String args[]) method. Ideally, it should contain very little logic. It should essentially construct one or two objects, and then call methods on those objects. One of those objects might be a this() - an instance of the main class, and that's ok.
You have to put the main() method somewhere - there's no need to create a special class just to hold that method.
As a general rule, try to avoid having too much in static methods - static methods can't be mocked for testing.
The main class should be an entry point to your program and should thus be relatively small. However this all depends on your actual program. If it's 50 lines long, it might be overkill to create two files for it.
As an example, consider the default Swing Application Framework Desktop Application as it would be generated by the NetBeans template, which is simple and short, and whose main() method is a single line that launches it:
public class MyApp extends SingleFrameApplication {
#Override protected void startup() {
show(new MyView(this));
}
#Override protected void configureWindow(java.awt.Window root) {}
public static MyApp getApplication() {
return Application.getInstance(MyApp.class);
}
public static void main(String[] args) {
launch(MyApp.class, args);
}
}