Stap 4: Starten van eenvoudige
Nu gaan we programmeren! * en er was veel vreugde * (sorry voor de cheesy Monty Python humor)
We gaan door de bouw van de primaire klasse, die ik TopClass belde, en zullen we gewoon het skelet bouwen zoals je hieronder zien. Alles wat dit doet tot nu toe is het creëren van een volledig scherm-frame zonder inhoud.
De belangrijkste methode gewoon creëert een nieuwe thread waaruit de GUI-gebouw en algemene spel functie werkt. U wilt uw spel in een andere thread om de GUI te blijven functionele uitvoeren. Als u dit niet doet, zou de game lus lock-up de interface, niet zodat de gebruiker het programma sluit tijdens het spelen van het spel.
De opmerkingen moeten uitleggen van de rest van de code.
import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import javax.swing.*; public class TopClass { //global constant variables private static final int SCREEN_WIDTH = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(); private static final int SCREEN_HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight(); //global variables //global swing objects private JFrame f = new JFrame("Flappy Bird Redux"); //other global objects private static TopClass tc = new TopClass(); /** * Default constructor */ public TopClass() { } /** * Main executable method invoked when running .jar file * args */ public static void main(String[] args) { //build the GUI on a new thread javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { tc.buildFrame(); //create a new thread to keep the GUI responsive while the game runs Thread t = new Thread() { public void run() { //in here we will call a function to start the game } }; t.start(); } }); } /** * Method to construct the JFrame and add the program content */ private void buildFrame() { Image icon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/blue_bird.png")); f.setContentPane(createContentPane()); //adds the main content to the frame f.setResizable(true); //true, but game will not function properly unless maximized! f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setAlwaysOnTop(false); f.setVisible(true); f.setMinimumSize(new Dimension(SCREEN_WIDTH*1/4, SCREEN_HEIGHT*1/4)); //set to prevent collapse to tiny window upon resizing f.setExtendedState(JFrame.MAXIMIZED_BOTH); //maximize the JFrame f.setIconImage(icon); //set the icon } private JPanel createContentPane() { topPanel = new JPanel(); //top-most JPanel in layout hierarchy return topPanel; //return a blank panel } }