Programming     Travel Logs     Life Is Good     Surfing Online     About Me
Play iterated games. All the returns in life, whether in wealth, relationships, or knowledge, come from compound interest.
-Naval Ravikant
Programming    [Java] 
2018-07-22 22:30:06

Copy this link when reproducing:
http://www.casperlee.com/en/y/blog/226

Although I normally don't want to use Java to create a GUI, I'm gonna do it this time, because I want to develop a Socket Server with Java, and it is better to have a User Interface then have nothing. Actually creating a GUI with Java is not that complex. 

Just like before, let's take it easy and enjoy a few beautiful photos first.

1. To develop and run Java programs in Windows, you need to install JDK (Java Development Kit) and probably Eclipse too. Check this link http://www.casperlee.com/x/y/blog/78 for detail if necessary.

2. Create a Java project.

    I. Run Eclipse, select "File -> New -> Project..." from the main menu, a dialog will be popped up:

    II. Select "Java -> Java Project", and click "Next >" to continue.

    III. Type in the project name and click "Next >" to continue.

    IV. Click "Finish" to continue.

    V. Click "Open Perspective", if you see the dialog above. Eclipse will create a Java project.

3. Create the main form.

    I. Right click on "src" in the Package explorer, select "New -> Class" from the popped menu, a dialog will be popped up:

    II. Type in the class name, tick "public static void main(String[] args)", and click "Finish", Eclipse will create a class named "MainForm".

    III. Open the file MainForm.java, put the following text in:

package com.casperlee.CSocketServer;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class MainForm extends JFrame {
	
	// Widgets
	GridLayout glMain = new GridLayout(0, 1);
	JLabel lblTop = new JLabel("This is a common socket server.");
	JTextField tfPort = new JTextField();
    JButton btnStart = new JButton("Start");
    JButton btnStop = new JButton("Stop");
    JButton btnViewLog = new JButton("View Log");
    JButton btnQuit = new JButton("Quit");
    
	// Constants
	private static final long serialVersionUID = 1562493580742512448L;
	
    // Fields
    private CServer server;
    
    // Constructors
    public MainForm() {
    	
    	super("Casper Socket Server");
    	this.addComponents();
    	this.initialize();
    }
    
    // Private functions
    private void addComponents() {
    	
    	this.setLayout(glMain);
    	this.add(lblTop);
    	this.add(tfPort);
    	this.add(btnStart);
    	this.add(btnStop);
    	this.add(btnViewLog);
    	this.add(btnQuit);
    }
    private void initialize() {
    	
    	this.tfPort.setText(Integer.toString(CServer.defaultPortNum));
    	this.btnStart.addActionListener(new ButtonClickListener());
    	this.btnStop.addActionListener(new ButtonClickListener());
    	this.btnViewLog.addActionListener(new ButtonClickListener());
    	this.btnQuit.addActionListener(new ButtonClickListener());
    }
    private void updateUI() {
    	
    	if (this.server.isAlive()) {
    		
    		this.btnStart.setEnabled(false);
    		this.btnStop.setEnabled(true);
    		this.lblTop.setText("Casper Socket Server Started!");
    		
    	} else {
    		
    		this.btnStart.setEnabled(true);
    		this.btnStop.setEnabled(false);
    		this.lblTop.setText("Casper Socket Server Stopped!");
    	}
    }
    
    // Event handlers
    private void performStartAction(ActionEvent e) {
    	
    	if (this.server != null && this.server.isAlive()) {
    		
    		return;
    	}
    	
    	this.server = new CServer();
    	this.server.start();
    	this.updateUI();
    }
    private void performStopAction(ActionEvent e) {
    	
    	if (!this.server.isAlive()) {
    		
    		return;
    	}
    	
    	this.server.interrupt();
    	try {
    		
			this.server.join();
			
		} catch (InterruptedException e1) {
			
			e1.printStackTrace();
		}
    	
    	this.updateUI();
    }
    private void performViewLogAction(ActionEvent e) {
    	
    }
    private void performQuitAction(ActionEvent e) {
    	
    }
    
    // private classes
    private class ButtonClickListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			
			if (e.getSource() instanceof JButton) {
				
				JButton btn = (JButton)e.getSource();
				if (btn == btnStart) {
					
					performStartAction(e);
					
				} else if (btn == btnStop) {
					
					performStopAction(e);
					
				} else if (btn == btnViewLog) {
					
					performViewLogAction(e);
					
				} else if (btn == btnQuit) {
					
					performQuitAction(e);
				}
			}
		}
    }
	
    // Main function
	public static void main(String[] args) {
		
		MainForm f = new MainForm();
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
	}
}

4. As you may already noticed, the main form is using a class named "CServer". Here is the code of the CServer class:

package com.casperlee.CSocketServer;

public class CServer extends Thread {
	
	// Constants
	public static final int defaultPortNum = 9527;
	
	// Fields
	private int portNum;
	
	// Constructor
	public CServer(int aPort) {
		super();
		this.portNum = aPort;
	}
	public CServer() {
		super();
		this.portNum = defaultPortNum;
	}
	
	// Override functions
	@Override
	public void run() {
		
		while (true) {
			
			if (this.isInterrupted()) {
				
				break;
			}
		}
	}	
}

5. Done!