Main.java
class Main { public static void main(String[] args) { new FrameTest(); } }
FrameTest.java
package com.company; import javax.swing.*; import java.awt.*; class FrameTest { JFrame frame =new JFrame("登錄"); Container c = frame.getContentPane();//創建視圖 JLabel userLabel=new JLabel("用戶名"); JTextField username= new JTextField(); JLabel passwdLabel=new JLabel("密碼"); JPasswordField password=new JPasswordField(); JButton okbutton = new JButton("確定"); JButton cancelbttton = new JButton("取消"); public FrameTest(){ frame.setBounds(600, 200, 300, 220);//設置窗體位置&大小 c.setLayout(new BorderLayout());//設置視圖的布局 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設置❌功能 init();//初始化,把控件放在布局里 frame.setVisible(true);//設置窗體可見 } public void init(){ // 標題——上方 JPanel titlePanel =new JPanel();//創建一個放置標題的面板 titlePanel.setLayout(new FlowLayout()); titlePanel.add(new JLabel("歡哥OS")); c.add(titlePanel, "North");//加入視圖中 // 輸入框——中間 JPanel inputPanel =new JPanel(); inputPanel.setLayout(null); userLabel.setBounds(50, 20, 50, 20);//標簽位置 passwdLabel.setBounds(50, 60, 50, 20); inputPanel.add(userLabel); inputPanel.add(passwdLabel); username.setBounds(110, 20, 120, 20); password.setBounds(110, 60, 120, 20); inputPanel.add(username); inputPanel.add(password); c.add(inputPanel, "Center"); // 按鈕底部 JPanel buttonPanel =new JPanel(); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(okbutton); buttonPanel.add(cancelbttton); c.add(buttonPanel, "South"); } }