Swing建立文字欄位

2019-10-16 22:03:48

以下範例展示了如何在Java Swing應用程式中建立和使用文字欄位。

使用以下API -

  • JTextField - 建立文字欄位。
  • JTextField.getText() - 輸入文字。

範例

package com.yiibai.swingdemo;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingTester {
    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    public SwingTester() {
        prepareGUI();
    }

    public static void main(String[] args) {
        SwingTester swingControlDemo = new SwingTester();
        swingControlDemo.showTextFieldDemo();
    }

    private void prepareGUI() {
        mainFrame = new JFrame("Swing建立文字欄位(tw511.com)");
        mainFrame.setSize(400, 400);
        mainFrame.setLayout(new GridLayout(3, 1));

        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }
        });
        headerLabel = new JLabel("", JLabel.CENTER);
        statusLabel = new JLabel("", JLabel.CENTER);
        statusLabel.setSize(350, 100);

        controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

    private void showTextFieldDemo() {
        headerLabel.setText("Control in action: JTextField");

        JLabel namelabel = new JLabel("使用者名: ", JLabel.RIGHT);
        JLabel passwordLabel = new JLabel("密碼: ", JLabel.CENTER);
        final JTextField userText = new JTextField(6);
        final JPasswordField passwordText = new JPasswordField(6);

        JButton loginButton = new JButton("登入");
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String data = "使用者名 " + userText.getText();
                data += ", 密碼: " + new String(passwordText.getPassword());
                statusLabel.setText(data);
            }
        });
        controlPanel.add(namelabel);
        controlPanel.add(userText);
        controlPanel.add(passwordLabel);
        controlPanel.add(passwordText);
        controlPanel.add(loginButton);
        mainFrame.setVisible(true);
    }
}

執行上面範例程式碼,得到以下結果: