Why these lines are necessary for swing application? - java

public class MedicalCenter {
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new Login().setVisible(true); <----------
new TimeAndDate().setVisible(true); <----------
});
}
}
Are these lines used just to start showing main windows of swing application?

new keyword is always used while creating objects

They do create objects but you didn't kept their reference.
So you cannot access those objects later on if you want to.

Related

Fullscreen JavaFX program in the same desktop with other applications?

I'm making a fullscreen JavaFX program, but I want it to run as a screensaver in the background with other applications simultaneously running on top of it. Right now, it automatically creates a separate desktop just for the program. Any solutions?
Swing is definitely an option. Here is a place to start:
public class MyClass {
public void myAction () {
// your logic goes here
System.out.println("hello");
}
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.myAction();
}
}

How do you get event notifications back to the main program class of a Java console app?

I'm coming to Java from C#, and I'm really just trying to figure out how to do things in Java world. I'm running Java 8 in IntelliJ IDEA. I found this explaining events in Java as basically being hand-made through manual registration and an interface method call. The code example has enough problems that I assume it was never compiled. After cleaning that up a bit I have this:
Interface MetronomeEvent:
public interface MetronomeEvent {
void Tick(Date tickDate);
}
Class EventFiringSource:
public class EventFiringSource {
// Our collection of classes that are subscribed as listeners of our
protected List<MetronomeEvent> _listeners=new ArrayList();
// Method for listener classes to register themselves
public void addMetronomeEventListener(MetronomeEvent listener)
{
_listeners.add(listener);
}
// "fires" the event
protected void fireMetronomeEvent()
{
if (_listeners != null && !_listeners.isEmpty())
{
for (MetronomeEvent e:_listeners)
{
e.Tick(new Date());
}
}
}
public void Start()
{
fireMetronomeEvent();
}
}
Main console application:
public class MainApp implements MetronomeEvent {
public static void main(String[] args) {
EventFiringSource source = new EventFiringSource();
source.addMetronomeEventListener(this); // Adds itself as a listener for the event
source.Start();
}
public void Tick(Date tickDate)
{
System.out.println(tickDate.toString());
}
}
The one remaining error is source.addMetronomeEventListener(this); where the compiler complains that it cannot reference MyApp.this from a static context. That makes sense, but I don't see any way then that I could, after implementing the MetronomeEvent interface on the main program class, actually pass it to source.addMetronomeEventListener() for registration. Is it impossible to directly register the main program class for events? Am I supposed to create and register a Listener class that implements MetronomeEvent and will act on behalf of the main application? Like this?
public class Listener implements MetronomeEvent {
public void Tick(Date tickDate){
System.out.println(tickDate.toString());
}
}
And then:
public static void main(String[] args) {
EventFiringSource source = new EventFiringSource();
Listener l=new Listener();
source.addMetronomeEventListener(l); // Adds another object to listen on behalf of main()
source.Start();
}
This is not about events, it's about main() and static methods in general.
I would suggest writing your main() as
public static void main(String[] args) {
new MainApp(args).execute();
}
This way you're immediately jumping from static function world into object-oriented world.
Based on Vince Emigh's comment/answer I was led to this Oracle doc on lamda expressions and to this one on method references. I've found 3 ways to do this so far.
1) Anonymous class:
source.addMetronomeEventListener(
new MetronomeEvent() {
#Override
public void Tick(Date tickDate) {
System.out.println("anonymous class:");
System.out.println(tickDate.toString());
}
}
); // Adds itself as a listener for the event
2) Lambda expression:
source.addMetronomeEventListener(d -> System.out.println("lambda:\n"+d.toString()));
3) Method reference, which is the closest to what I am accustomed to. A method is defined in the main class:
public static void processTick(Date tickDate){
System.out.println("method reference:");
System.out.println(tickDate.toString());
}
...and then in the body of main() it is added as an event handler like this:
source.addMetronomeEventListener(MainApp::processTick);

Where should I put my initialisation code?

I have written a programme in java for command line. Now to convert it to gui I used Netbeans GUI Builder. The problem is I do not know where to put my initialisation codes(from the old main class).
There is a main in gui but I do not think I can put there all those codes. Even then I do not think it would not be a good idea. So how can I run my initialisation codes from old main class?
I believe you would have the beginnings of this from Netbeans, correct?
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
... some stuff here automatically created by Netbeans (leave it).
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//enter initialization code here
Main mainWindow = null;
try {
//enter more initialization code here
mainWindow = new Main();
} catch (IOException ex) {
System.exit(1);
}
//enter even more initialization code here
mainWindow.setVisible(true);
}
});
}
Of course, edit as you like. I would highly recommend that you DO use Netbeans automated features, especially if you're new at creating your own GUIs. Copy and paste your code from your command line app right into this automated main. Hope that helps.

Show popup at the start if file is missing

I am creating a small GUI java application that it will store some user credentials in a file.
If the file is missing or has the wrong properties then I want a pop to get brought up that will inform the user to register his credentials (so a new file can be created with the proper ones).
I have nailed down the logic of when the file is incorrect and/or missing but what I can't figure out (due to my inexperience with JFrame) is where exactly in the code to check if the user needs to enter his credentials so he can be prompted.
Let's say that the function showWarning() is the one that will check and display the popup if needed and this is my main JFrame function (this was generated from Netbeans mostly):
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
Do I put the showWarning() function inside the main function? If yes, do I put it right after new GUI().setVisible(true);? What is the proper way of doing this?
EDIT: I am stumbling to the same problem I did before. This is my showWarning() that I drafted quickly for testing purposes:
public void showWarning(){
File propertiesFile = new File("config.properties");
if (propertiesFile.exists() && propertiesExist(propertiesFile)) {
JOptionPane.showMessageDialog(rootPane, "Creds are ok");
} else {
JOptionPane.showMessageDialog(rootPane, "Creds are not ok");
}
}
The problem that I am having is that I can't make this method static in order to use it without an object because of the rootPane which is a non-static object. The problem that this caused is that I can't just write:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
showWarning();
}
});
}
I can't use showWarning() like that since it's a non-static method.
Do I need to have the GUI object in a variable properly or is there a way to make the showWarning() a static method?
If you want the check to run right when the program starts, you would want to put your function call after the main JFrame gui is set visible. See edited code below. Of course, I'm using the ambiguous showWarning() function here, but you should talor that line of code to your need. If calling a function, then right the function, but if wanting to call a new popup jframe you will need to do more lines of code there.
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
LoginForm login = new LoginForm();
login.setVisible(true);
}
});
}
Now here you would want to change the variables accordingly. The LoginForm is a Jframe already created.
You probably want your popup dialog to be modal, so the program does not continue until the user has handled and fixed the problem. To do this, do not use a JFrame but a JDialog for your popup dialog and make it modal. Then you can simply put the showWarning() call everywhere you want. I think I would put it inside the main.
Use JDialog for creating the pop up.
And either you add the showWarning() method call in main like this :
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
showWarning();
}
});
}
or better you can invoke the method showWarning() when the user credentials have to be enetered in the file. If checked just before it, it would be optimal.

Java GUI internal classse to separate files

I am writing a java program which have a big amount of different GUI objects and GUI class file became huge. I wanted to ask if there is a way to separate these internal files in different files and if so, how to do that.
The general structure of the GUI(Runner)class is following
public class Gui extends JFrame{
<componendt definition>
public Gui()
{
<component initialization>
<containers and adding objects to container>
<attaching listeners>
// for example
generate_button.addActionListener(new generate_ButtonHandler());
}
// I want to separate these classes in different files
class generate_ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
<some suff>
}
}
public static void main(String[] args) {
JFrame f = new Gui();
f.setVisible (true);
f.setDefaultCloseOperation (EXIT_ON_CLOSE);
}
}
Or may be there is another solution how to handle these big files
You could try implement each UI part as separate component, and encapsulate most
code in the component. That will reduce amount of service code.

Categories