GUI programming
I. Introduction
Core technology of GUI: AWT, Swing
Reasons for not being popular:
-
Because the interface is not beautiful
-
Need jre environment
Why should we study?
- You can write some gadgets, plug-ins and so on you want
- When working, you may also need to maintain the swing interface, which is very unlikely
- Understand MVC architecture and monitoring
II. AWT
2.1 - AWT introduction
-
It contains many classes and interfaces! GUI: graphical user interface programming, Eclipse ➡ Java writing
-
Elements: window, button, text box
-
java.awt
2.2 - Components and containers
-
Frame
package com.gui; import java.awt.*; //The first interface of GUI public class GuiFrame { public static void main(String[] args) { //Frame, JDK, look at the source code Frame frame = new Frame("My first java Graphical interface window"); //Set Visible frame.setVisible(true); //Set window size frame.setSize(500,500); //Set background Color frame.setBackground(new Color(32,92,9)); //Set initial position frame.setLocation(300,300); //Set fixed size frame.setResizable(false); } }
- Problem: if the installation port cannot be closed, stop Java operation!
- Review packaging:
public class GuiFrame { public static void main(String[] args) { //Show multiple windows new MyFrame(100,100,200,200,Color.darkGray); new MyFrame(300,100,200,200,Color.blue); new MyFrame(100,300,200,200,Color.red); new MyFrame(300,300,200,200,Color.magenta); } } class MyFrame extends Frame{ static int id = 0;//There may be multiple windows, we need a counter public MyFrame(int x,int y,int w,int h,Color color){ super("MyFrame+ " + (++id));//Frame setVisible(true); //Set Visible setBounds(x,y,w,h);//Set window size and initial position setBackground(color);//Set background color } }
-
Panel panel
- Closed event resolved
//The Panel can be regarded as a space, but it cannot exist alone and needs to be placed in the Frame public class GuiPanel { public static void main(String[] args) { Frame frame = new Frame(); //Concept of layout Panel panel = new Panel(); //Set layout frame.setLayout(null); //coordinate frame.setBounds(300,300,500,500); frame.setBackground(new Color(128, 173, 64)); //Panel setting coordinates, relative to frame panel.setBounds(50,50,400,400); panel.setBackground(new Color(179, 65, 65)); //panel join frame frame.add(panel); frame.setVisible(true); //Listen to the event. Listen to the window closing event system exit(0) /* Adapter mode 23 A kind of design pattern */ frame.addWindowListener(new WindowAdapter() { //What to do when clicking close @Override public void windowClosing(WindowEvent e) { // super.windowClosing(e); //End program System.exit(0); } }); } }
2.3 - Layout Manager
-
Streaming layout
public class GuiFlowLayout { public static void main(String[] args) { Frame frame = new Frame(); //assembly ➡ Button Button button1 = new Button("button1"); Button button2 = new Button("button2"); Button button3 = new Button("button3"); //Set as streaming layout // frame.setLayout(new FlowLayout()); Center frame.setLayout(new FlowLayout(FlowLayout.LEFT));//Keep to the left frame.setSize(200,200); //Add the button frame.add(button1); frame.add(button2); frame.add(button3); //display frame.setVisible(true); } }
-
East, West, North and South
public class GuiBorderLayOut { public static void main(String[] args) { Frame frame = new Frame("BorderLayout"); //Set button Button east = new Button("East"); Button west = new Button("West"); Button south = new Button("South"); Button north = new Button("North"); Button center = new Button("Center"); //Join frame frame.add(east,BorderLayout.EAST); frame.add(west,BorderLayout.WEST); frame.add(south,BorderLayout.SOUTH); frame.add(north,BorderLayout.NORTH); frame.add(center,BorderLayout.CENTER); //Set frame frame.setSize(200,200); frame.setVisible(true); } }
-
Table layout
public class GuiGridLayout { public static void main(String[] args) { //Set btn Frame frame = new Frame(); Button btn1 = new Button("btn1"); Button btn2 = new Button("btn2"); Button btn3 = new Button("btn3"); Button btn4 = new Button("btn4"); Button btn5 = new Button("btn5"); Button btn6 = new Button("btn6"); //Join frame frame.setLayout(new GridLayout(3,2)); frame.add(btn1); frame.add(btn2); frame.add(btn3); frame.add(btn4); frame.add(btn5); frame.add(btn6); //frame settings frame.pack();//Java function! The function is to optimize the layout frame.setVisible(true); } }
-
Interface practice (Frame + Panel + Button)
public class GuiLayoutTest { public static void main(String[] args) { Frame frame = new Frame("Interface practice"); frame.setSize(400,300); frame.setLocation(300,400); frame.setBackground(Color.GRAY); frame.setVisible(true); //Upper and lower parts (table layout upper and lower - two rows and one column) frame.setLayout(new GridLayout(2,1)); //Four panels //above Panel p1 = new Panel(new BorderLayout()); Panel p2 = new Panel(new GridLayout(2,1)); p1.add(new Button("East1"),BorderLayout.EAST); p1.add(new Button("West1"),BorderLayout.WEST); p2.add(new Button("p2-btn-1")); p2.add(new Button("p2-btn-2")); p1.add(p2,BorderLayout.CENTER); frame.add(p1); //below Panel p3 = new Panel(new BorderLayout()); Panel p4 = new Panel(new GridLayout(2,2)); p3.add(new Button("East2"),BorderLayout.EAST); p3.add(new Button("West2"),BorderLayout.WEST); for (int i = 1; i <= 4; i++) { p4.add(new Button("p4-btn-"+i)); } p3.add(p4); frame.add(p3); //lsnrctl stop frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
2.4 - event monitoring
-
Button monitoring
public class GuiActionEvent { public static void main(String[] args) { //Press the button to start some events Frame frame = new Frame(); Button button = new Button(); //Because addActionListener() needs an ActionListener, we construct a MyActionListener implements ActionListener MyActionListener myActionListener = new MyActionListener(); button.addActionListener(myActionListener); frame.add(button,BorderLayout.CENTER); frame.pack(); frame.setVisible(true); windowClosing(frame); } //Turn off form event listening public static void windowClosing(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } //event listeners class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println("AAA"); } }
-
Multiple buttons share a listening event
public class GuiActionEvent { public static void main(String[] args) { /* Two buttons realize the same monitoring Start, stop */ Frame frame = new Frame("start-stop it"); Button startBtn = new Button("start"); Button stopBtn = new Button("stop"); /* The displayed definition will return the command. If the definition is not displayed, the default value will be taken You can write only one listening class for multiple buttons, which can be shared by listening classes. */ startBtn.setActionCommand("startBtn-start"); stopBtn.setActionCommand("stopBtn-stop"); MyMonitor myMonitor = new MyMonitor(); startBtn.addActionListener(myMonitor); stopBtn.addActionListener(myMonitor); frame.add(startBtn,BorderLayout.NORTH); frame.add(stopBtn,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); windowClosing(frame); } //Turn off form event listening public static void windowClosing(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } //event listeners class MyMonitor implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //e.getActionCommand() gets the information of the button System.out.println("Button clicked: msg ➡ "+ e.getActionCommand()); if(e.getActionCommand().equals("startBtn-start")){ System.out.println("Start playing");//Depending on the return value of e.getActionCommand(), there will be different operations } if(e.getActionCommand().equals("stopBtn-stop")){ System.out.println("stop playing"); } } }
2.5 - input box TextField monitor
-
Listen for text in text box
public class GuiTextField { public static void main(String[] args) { //start-up new MyFrame(); } } class MyFrame extends Frame{ public MyFrame(){ TextField textField = new TextField(); add(textField); //Press Enter to trigger the text input in the listening text box textField.addActionListener(new MyActionListener()); //Set code textField.setEchoChar('*'); pack(); setVisible(true); } } class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { TextField field = (TextField) e.getSource();//Get some resources and return an object System.out.println(field.getText());//Gets the text of the input box field.setText("");//Press enter to clear. null is the object and "" is the string } }
2.6 - simple calculator, combination + internal class review
-
oop principle, composition > inheritance
class A extends B{ //inherit } class A{ public B b;//Combination to reduce coupling }
-
Current calculator
public class GuiCalc { public static void main(String[] args) { new Calculator(); } } //Calculator class class Calculator extends Frame{ public Calculator(){ //3 text boxes TextField num1 = new TextField(10); TextField num2 = new TextField(10); TextField num3 = new TextField(20); //A label Label label = new Label("+"); //A button Button button = new Button("="); button.addActionListener(new CalculatorListener(num1,num2,num3)); //layout setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } } //Listener class class CalculatorListener implements ActionListener{ //Get three variables private TextField num1,num2,num3; public CalculatorListener(TextField num1,TextField num2,TextField num3 ){ this.num1 = num1; this.num2 = num2; this.num3 = num3; } @Override public void actionPerformed(ActionEvent e) { //1. Get num1 num2 int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); //2. Put this value into the third box after operation num3.setText(""+(n1+n2)); //3. Clear the first two boxes num1.setText(""); num2.setText(""); } }
-
The combination mode is completely transformed into oop
public class GuiCalc { public static void main(String[] args) { new Calculator().loadFrame(); } } //Calculator class class Calculator extends Frame{ //attribute TextField num1,num2,num3; //method public void loadFrame(){ //assembly num1 = new TextField(10);//Number of characters num2 = new TextField(10); num3 = new TextField(20); Label label = new Label("+"); Button button = new Button("="); //monitor button.addActionListener(new CalculatorListener(this)); //layout setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } } //Listener class class CalculatorListener implements ActionListener{ //Get the calculator object and combine another class in one class Calculator calculator = null; public CalculatorListener(Calculator calculator){ this.calculator = calculator; } @Override public void actionPerformed(ActionEvent e) { //1. Get num1 num2 int n1 = Integer.parseInt(calculator.num1.getText()); int n2 = Integer.parseInt(calculator.num2.getText()); //2. Put this value into the third box after operation calculator.num3.setText(""+(n1+n2)); //3. Clear the first two boxes calculator.num1.setText(""); calculator.num2.setText(""); } }
-
Inner class
- Better packaging
public class GuiCalc { public static void main(String[] args) { Calculator calculator = new Calculator(); calculator.loadFrame(); closing(calculator); } public static void closing(Frame frame){ frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } } //Calculator class class Calculator extends Frame{ //attribute TextField num1,num2,num3; //method public void loadFrame(){ //assembly num1 = new TextField(10);//Number of characters num2 = new TextField(10); num3 = new TextField(20); Label label = new Label("+"); Button button = new Button("="); //monitor button.addActionListener(new CalculatorListener()); //layout setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } //Listener class //The biggest advantage of internal classes is that they can access the properties and methods of external classes unimpeded! private class CalculatorListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //1. Get num1 num2 int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); //2. Put this value into the third box after operation num3.setText(""+(n1+n2)); //3. Clear the first two boxes num1.setText(""); num2.setText(""); } } }
2.7 - brush
-
Simple operation
public class GuiPaint { public static void main(String[] args) { new MyPaint().loadFrame(); } } class MyPaint extends Frame{ public void loadFrame(){ setBounds(200,200,600,400); setVisible(true); } @Override public void paint(Graphics g) { //The brush needs to have color to draw g.setColor(Color.RED); // g.drawOval(100,100,100,100);// Hollow circle ⚪ g.fillOval(100,100,100,100);//disc g.setColor(Color.GREEN); g.fillRect(150,200,200,200);//Solid rectangle //Make it a habit to use up the brush and restore it to its original color } }
2.8 - mouse monitoring
-
Purpose: to achieve mouse painting!
//Mouse monitoring events public class GuiMouseListener { public static void main(String[] args) { new MyPaintFrame("Draw a picture"); } } //Own Frame class MyPaintFrame extends Frame{ //You need a brush to draw, you need to monitor the current position of the mouse, and you need a collection to store this point ArrayList points; public MyPaintFrame(String title){ super(title); setBounds(200,200,400,300); //Save mouse points points = new ArrayList<>(); setVisible(true); //Mouse listener, facing this window this.addMouseListener(new MyMouseListener()); } @Override public void paint(Graphics g) { //Draw and monitor mouse events Iterator iterator = points.iterator(); while (iterator.hasNext()){ Point point = (Point) iterator.next(); g.setColor(Color.BLUE); g.fillOval(point.x,point.y,10,10); } } //Add a point to the interface public void addPaint(Point point){ points.add(point); } //Adapter mode private class MyMouseListener extends MouseAdapter { //Mouse: Press, pop up, hold down @Override//Press public void mousePressed(MouseEvent e) { MyPaintFrame myPaintFrame = (MyPaintFrame) e.getSource(); //When you click here, a point will be generated in the interface! //This point is the point of the mouse myPaintFrame.addPaint(new Point(e.getX(),e.getY())); //You need to redraw every time you click the mouse myPaintFrame.repaint();//Refresh } } }
2.9 - window monitoring
-
The most commonly used windows are closing and activating
public class GuiWindowListener { public static void main(String[] args) { new WindowFrame(); } } class WindowFrame extends Frame{ public WindowFrame(){ setBackground(Color.BLUE); setBounds(100,100,200,200); setVisible(true); this.addWindowListener(new WindowAdapter() { //close window @Override public void windowClosing(WindowEvent e) { System.out.println("windowClosing"); System.exit(0); } //activation @Override public void windowActivated(WindowEvent e) { WindowFrame source = (WindowFrame) e.getSource(); source.setTitle("Activated"); System.out.println("windowActivated"); } }); } }
2.10 - keyboard monitoring
-
Different results will be produced according to different operations
public class GuiKeyListener { public static void main(String[] args) { new KeyFrame(); } } class KeyFrame extends Frame{ public KeyFrame(){ setBounds(100,200,300,400); setVisible(true); this.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //Which key is the current key int keyCode = e.getKeyCode();//You do not need to record this hexadecimal value, but use the static attribute VK directly_ xxx System.out.println(keyCode); if(keyCode == KeyEvent.VK_UP){ System.out.println("You pressed the up button!"); } } }); } }
Three Swing
3.1 - Windows, panels
-
The first case (JFrame, JLabel)
public class JFrameDemo { public static void main(String[] args) { //Create a window new MyJFrame().init(); } } class MyJFrame extends JFrame{ public void init(){ this.setBounds(10,10,200,300); this.setVisible(true); JLabel label = new JLabel("Welcome to java world"); this.add(label); //Center the text label and set the horizontal alignment label.setHorizontalAlignment(SwingConstants.CENTER); //Get a container Container container = this.getContentPane(); container.setBackground(Color.CYAN); } }
3.2 - pop up window
-
JDialog, binding JButton event
//main window public class DialogDemo extends JFrame { public static void main(String[] args) { new DialogDemo(); } public DialogDemo() { this.setVisible(true); this.setSize(700,500); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //Put things in JFrame ➡ container Container container = this.getContentPane(); //Absolute layout container.setLayout(null); //Button JButton button = new JButton("Click to pop up a dialog box");//establish button.setBounds(30,30,200,50); container.add(button); //When you click the button, a pop-up window pops up button.addActionListener(new ActionListener() {//monitor @Override public void actionPerformed(ActionEvent e) { //Spring frame new MyDialog(); } }); } } //Pop up window class MyDialog extends JDialog{ public MyDialog(){ this.setVisible(true); this.setBounds(100,100,500,500); Container container = this.getContentPane(); container.setLayout(null); container.add(new Label("Welcome to the Java world")); } }
3.3 - Labels
-
Label
new JLabel("xxx");
-
Icon icon
//Icon, need to implement class, Frame inheritance public class IconDemo extends JFrame implements Icon { private int width; private int height; /* Structure without / with parameters */ public IconDemo(){} public IconDemo(int width,int height){ this.width = width; this.height = height; } public void init(){ IconDemo icon = new IconDemo(15, 15); //Icons can be placed on labels or buttons! JLabel label = new JLabel("icon test", icon, SwingConstants.CENTER); Container container = getContentPane(); container.add(label); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new IconDemo().init(); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.fillOval(x,y,width,height); } @Override public int getIconWidth() { return this.width; } @Override public int getIconHeight() { return this.height; } }
-
Picture Icon (logo)
//Picture (logo) public class ImageIconDemo extends JFrame { public ImageIconDemo() { JLabel label = new JLabel("ImageIcon"); //Get the address of the picture URL url = ImageIconDemo.class.getResource("tree.png"); ImageIcon imageIcon = new ImageIcon(url);//Do not conflict in naming label.setIcon(imageIcon); label.setHorizontalAlignment(SwingConstants.CENTER); Container container = getContentPane(); container.add(label); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setBounds(100,200,400,400); } public static void main(String[] args) { new ImageIconDemo(); } }
3.4 - panel
-
JPanel
public class JPanelDemo extends JFrame { public static void main(String[] args) { new JPanelDemo(); } public JPanelDemo() { Container container = this.getContentPane(); container.setLayout(new GridLayout(2,1,10,10));//The following parameters mean spacing JPanel panel1 = new JPanel(new GridLayout(1, 3)); JPanel panel2 = new JPanel(new GridLayout(1, 2)); JPanel panel3 = new JPanel(new GridLayout(2, 1)); JPanel panel4 = new JPanel(new GridLayout(3, 2)); panel1.add(new JButton("1")); panel1.add(new JButton("1")); panel1.add(new JButton("1")); panel2.add(new JButton("2")); panel2.add(new JButton("2")); panel3.add(new JButton("3")); panel3.add(new JButton("3")); panel4.add(new JButton("4")); panel4.add(new JButton("4")); panel4.add(new JButton("4")); panel4.add(new JButton("4")); panel4.add(new JButton("4")); panel4.add(new JButton("4")); container.add(panel1); container.add(panel2); container.add(panel3); container.add(panel4); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setVisible(true); this.setSize(500,500); } }
-
JscrollPanel
public class JScrollDemo extends JFrame { public JScrollDemo(){ Container container = this.getContentPane(); //Text field JTextArea textArea = new JTextArea(20,50); textArea.setText("Welcome to study Java"); //Scroll panel JScrollPane scrollPane = new JScrollPane(textArea); container.add(scrollPane); this.setVisible(true); this.setBounds(100,100,300,350); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JScrollDemo(); } }
3.5 - buttons
-
Picture button
public class JButtonDemo extends JFrame { public JButtonDemo(){ Container container = this.getContentPane(); //Program picture Icon URL resource = JButtonDemo.class.getResource("tree.png"); Icon icon = new ImageIcon(resource); //Put the icon on the button JButton button = new JButton(); button.setIcon(icon); button.setToolTipText("Button picture!"); //Add container container.add(button); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo(); } }
-
Radio box, round
public class JButtonDemo extends JFrame { public JButtonDemo(){ Container container = this.getContentPane(); //Program picture Icon URL resource = JButtonDemo.class.getResource("tree.png"); Icon icon = new ImageIcon(resource); //Radio JRadioButton radioButton01 = new JRadioButton("JRadioButton01"); JRadioButton radioButton02 = new JRadioButton("JRadioButton02"); JRadioButton radioButton03 = new JRadioButton("JRadioButton03"); //Since only one radio box can be selected, it is generally divided into one group. ButtonGroup group = new ButtonGroup(); group.add(radioButton01); group.add(radioButton02); group.add(radioButton03); //Upper, middle and lower container.add(radioButton01,BorderLayout.CENTER); container.add(radioButton02,BorderLayout.SOUTH); container.add(radioButton03,BorderLayout.NORTH); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo(); } }
-
Multiple selection box, box
public class JButtonDemo extends JFrame { public JButtonDemo(){ Container container = this.getContentPane(); //Program picture Icon URL resource = JButtonDemo.class.getResource("tree.png"); Icon icon = new ImageIcon(resource); //Radio JCheckBox checkBox01 = new JCheckBox("checkBox01"); JCheckBox checkBox02 = new JCheckBox("checkBox02"); JCheckBox checkBox03 = new JCheckBox("checkBox03"); //Multiple selections do not need grouping //Upper, middle and lower container.add(checkBox01,BorderLayout.CENTER); container.add(checkBox02,BorderLayout.SOUTH); container.add(checkBox03,BorderLayout.NORTH); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JButtonDemo(); } }
3.6 - List
-
Drop down box
public class ComboboxDemo extends JFrame { public ComboboxDemo(){ Container container = this.getContentPane(); JComboBox status = new JComboBox(); status.addItem(null); status.addItem("It's showing"); status.addItem("Removed from the shelf"); status.addItem("Coming soon"); container.add(status); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new ComboboxDemo(); } }
-
list box
public class ComboboxDemo extends JFrame { public ComboboxDemo(){ Container container = this.getContentPane(); //Generate the contents of the list // String[] contents = {"1","2","3"}; Vector contents = new Vector(); contents.add("Zhang San"); contents.add("Li Si"); contents.add("Wang Wu"); //The list needs to be filled JList list = new JList(contents); container.add(list); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new ComboboxDemo(); } }
-
Application scenario
- Drop down to select region or some individual options
- List, display information, usually dynamic capacity expansion
3.7 - text box
-
Text box
public class TextDemo extends JFrame { public TextDemo(){ Container container = this.getContentPane(); JTextField field01 = new JTextField("hello"); JTextField field02 = new JTextField("world",20); container.add(field01,BorderLayout.NORTH); container.add(field02,BorderLayout.SOUTH); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TextDemo(); } }
-
Password box
public class TextDemo extends JFrame { public TextDemo(){ Container container = this.getContentPane(); //panel JPasswordField field = new JPasswordField();//**** field.setEchoChar('*'); container.add(field); this.setVisible(true); this.setSize(500,300); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new TextDemo(); } }
-
Text field
public class JScrollDemo extends JFrame { public JScrollDemo(){ Container container = this.getContentPane(); //Text field JTextArea textArea = new JTextArea(20,50); textArea.setText("Welcome to study Java"); //Scroll panel JScrollPane scrollPane = new JScrollPane(textArea); container.add(scrollPane); this.setVisible(true); this.setBounds(100,100,300,350); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args) { new JScrollDemo(); } }
Greedy snake
-
Frame, if the time slice is small enough, it is animation. 30 frames a second, 60 frames pass through the human eye, which is similar to 30 frames. Connect is animation, open is static picture!
-
Keyboard monitor
-
Timer timer
//Data center public class Data { private static URL headerURL = Data.class.getResource("statics/header.png"); public static ImageIcon header = new ImageIcon(headerURL); private static URL upURL = Data.class.getResource("statics/up.png"); private static URL downURL = Data.class.getResource("statics/down.png"); private static URL leftURL = Data.class.getResource("statics/left.png"); private static URL rightURL = Data.class.getResource("statics/right.png"); public static ImageIcon up = new ImageIcon(upURL); public static ImageIcon down = new ImageIcon(downURL); public static ImageIcon left = new ImageIcon(leftURL); public static ImageIcon right = new ImageIcon(rightURL); private static URL bodyURL = Data.class.getResource("statics/body.png"); public static ImageIcon body = new ImageIcon(bodyURL); private static URL foodURL = Data.class.getResource("statics/food.png"); public static ImageIcon food = new ImageIcon(foodURL); } //Main startup class of the game public class GameStart { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setBounds(10,10,900,720); frame.setResizable(false);//Window size is immutable frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //The normal game interface should be on the panel! frame.add(new GamePanel()); frame.setVisible(true); } } //Game panel ➡ Main operation public class GamePanel extends JPanel implements KeyListener , ActionListener { //Define the data structure of the snake int length;//Snake length int[] snakeX = new int[600];//X coordinate of snake 25 * 30 int[] snakeY = new int[500];//Y coordinate of snake 25 * 25 String direction;//Initial direction //Failed boolean isFail = false; //Failure status //Coordinates of food int foodX; int foodY; Random random = new Random(); //Current state of the game: start / stop boolean isStart = false; //Default stop //Timer in milliseconds 1000ms = 1s Timer timer = new Timer(100,this);//Execute once every 100 milliseconds //integral int score; public GamePanel(){ init(); //Get focus and keyboard events this.setFocusable(true);//Get focus event this.addKeyListener(this);//Get keyboard listening events timer.start();//The game starts at the beginning score = 0; } //Initialization method public void init(){ length = 3; snakeX[0] = 100; snakeY[0] = 100; //Head coordinates snakeX[1] = 75; snakeY[1] = 100; //Coordinates of the first body snakeX[2] = 50; snakeY[2] = 100; //Coordinates of the second body direction = "R"; //Initial direction right //Randomly distribute the food on the interface foodX = 25 + 25*random.nextInt(34); foodY = 75 + 25*random.nextInt(24); } //Drawing panel, everything in our game, uses this brush @Override protected void paintComponent(Graphics g) { super.paintComponent(g);//Clear screen this.setBackground(Color.WHITE);//Background white, default //Draw static panel Data.header.paintIcon(this,g,25,11);//Draw the ad on the head g.fillRect(25,75,850,600);//Default game interface //Draw integral g.setColor(Color.WHITE); g.setFont(new Font("Microsoft YaHei ",Font.BOLD,18));//Set font g.drawString("length "+length,750,35); g.drawString("fraction "+score,750,50); //Draw food Data.food.paintIcon(this,g,foodX,foodY); //Draw the little snake if(direction.equals("R")){ Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); //The snakehead is initialized to the right and judged by the direction }else if(direction.equals("L")){ Data.left.paintIcon(this,g,snakeX[0],snakeY[0]); //The snakehead is initialized to the right and judged by the direction }else if(direction.equals("U")){ Data.up.paintIcon(this,g,snakeX[0],snakeY[0]); //The snakehead is initialized to the right and judged by the direction }else if(direction.equals("D")){ Data.down.paintIcon(this,g,snakeX[0],snakeY[0]); //The snakehead is initialized to the right and judged by the direction } for (int i = 1; i < length; i++) { Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); //Initialize the first body } //Game status if(isStart==false) { g.setColor(Color.WHITE); g.setFont(new Font("Microsoft YaHei ", Font.BOLD, 40));//Set font g.drawString("Press the space bar to start the game", 300, 300); } //Failure status if(isFail){ g.setColor(Color.RED); g.setFont(new Font("Microsoft YaHei ",Font.BOLD,40));//Set font g.drawString("The game failed. Press the space to start again",300,300); } } //Keyboard listening events @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode();//When getting keyboard keys if(keyCode == KeyEvent.VK_SPACE){//Space if(isFail){ //restart isFail = false; init(); }else{ isStart = !isStart;//Reverse } repaint(); } //Snake Movement if(keyCode == KeyEvent.VK_UP){ direction = "U"; }else if(keyCode == KeyEvent.VK_DOWN){ direction = "D"; }else if(keyCode == KeyEvent.VK_LEFT){ direction = "L"; }else if(keyCode == KeyEvent.VK_RIGHT){ direction = "R"; } } //Event listening ➡ Refresh through fixed events, 1s = 10 times @Override public void actionPerformed(ActionEvent e) { if(isStart && !isFail){//If the game starts, let the snake move //Eat food if(snakeX[0] == foodX && snakeY[0] == foodY){ length++;//Length + 1 score = score + 10;//Points + 10 //Random distribution of food again foodX = 25 + 25*random.nextInt(34); foodY = 75 + 25*random.nextInt(24); } //move for (int i = length - 1; i > 0; i--) {//The next section moves the position of the previous section snakeX[i] = snakeX[i-1]; snakeY[i] = snakeY[i-1]; } if(direction.equals("R")){ snakeX[0] = snakeX[0]+25; if(snakeX[0] > 850){snakeX[0] = 25;} }else if(direction.equals("L")){ snakeX[0] = snakeX[0]-25; if(snakeX[0] < 25){snakeX[0] = 850;} }else if(direction.equals("U")){ snakeY[0] = snakeY[0]-25; if(snakeY[0] < 75){snakeY[0] = 650;} }else if(direction.equals("D")){ snakeY[0] = snakeY[0]+25; if(snakeY[0] > 650 ){snakeY[0] = 75;} } //Failure judgment, bumping into yourself is failure for (int i = 1; i < length; i++) { if(snakeX[0]==snakeX[i] && snakeY[0]==snakeY[i]){ isFail = true; } } repaint();//Redraw page } timer.start();//Timer on } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }
-
Required accessories