【Java】利用Swing實現登入頁面
阿新 • • 發佈:2021-09-27
package com.company; import javax.swing.*; import java.awt.*; class FrameTest { JFrame jFrame = new JFrame("登入"); Container c = jFrame.getContentPane(); JLabel a1 = new JLabel("使用者名稱:"); JTextField username = new JTextField(); JLabel a2 = new JLabel("密碼:"); JPasswordField password= new JPasswordField(); JButton okbtn = new JButton("確定"); JButton cancelbtn = new JButton("取消"); public FrameTest() { //設定窗體的位置及大小 jFrame.setBounds(600, 200, 300, 220); //設定一層相當於桌布的東西 c.setLayout(new BorderLayout());//佈局管理器 //設定按下右上角X號後關閉 jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//初始化--往窗體裡放其他控制元件 init(); //設定窗體可見 jFrame.setVisible(true); } public void init() { /*標題部分--North*/ JPanel titlePanel = new JPanel(); titlePanel.setLayout(new FlowLayout()); titlePanel.add(new JLabel("XXX登入系統")); c.add(titlePanel, "North");/*輸入部分--Center*/ JPanel fieldPanel = new JPanel(); fieldPanel.setLayout(null); a1.setBounds(50, 20, 50, 20); a2.setBounds(50, 60, 50, 20); fieldPanel.add(a1); fieldPanel.add(a2); username.setBounds(110, 20, 120, 20); password.setBounds(110, 60, 120, 20); fieldPanel.add(username); fieldPanel.add(password); c.add(fieldPanel, "Center"); /*按鈕部分--South*/ JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(okbtn); buttonPanel.add(cancelbtn); c.add(buttonPanel, "South"); } public static class Main { public static void main(String[] args) { new FrameTest(); } } }
效果