Java UDP Socket訪微信qq即時聊天工具——(一)登錄界面

項目地址:https://github.com/ListeningRift/think

登陸界面這個東西是很門面的,要高級,要大氣;但很明顯——

我做不到。

但根據觀察和想象,QQ和微信的登陸界面都不擔心大小更改的問題,所以強制設定了窗口大小和不允許更改大小設置,並且使用了絕對定位。

效果圖:
在這裏插入圖片描述

本章涉及文件:src/app/login (不再大篇幅貼代碼)

這裏有幾個要提及的點:

  1. 圓角輸入框,JTextField和JPasswordField實現方法一樣,主要是重寫繼承自JComponent的paintBorder()方法,將邊框畫出來之後,設置一個margin即可。
public class Input extends JTextField {
    public Input(String content, int columns) {
        super(content, columns);
        setMargin(new Insets(0, 10, 2, 10));
    }

    @Override
    protected void paintBorder(Graphics g) {
        int h = getHeight();// 從JComponent類獲取高寬
        int w = getWidth();
        Graphics2D g2d = (Graphics2D) g;
        Shape shape = g2d.getClip();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setClip(shape);
        g2d.drawRoundRect(0, 0, w - 2, h - 2, h, h);
        g2d.dispose();
        super.paintBorder(g2d);
    }
}
  1. 居中輸入,主要是使用setHorizontalAlignment()這個方法。
JTextField.setHorizontalAlignment(JTextField.CENTER);
  1. 後續考慮將按鈕也做成圓角按鈕。
  2. 默認提示符,也就是在失去焦點且爲空的時候顯示Username這一類字符,在獲得焦點時就不顯示。
public class Prompt implements FocusListener {
    private String info;
    private JTextField textField;
    public Prompt(String info, JTextField textField) {
        this.info = info;
        this.textField = textField;
        this.textField.setText(info);
        this.textField.setForeground(Color.gray);
    }

    @Override
    public void focusGained(FocusEvent e) {
        if (textField.getText().equals(info)) {
            textField.setText("");
            textField.setForeground(Color.black);
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        if (textField.getText().equals("")) {
            textField.setText(info);
            textField.setForeground(Color.gray);
        }
    }
}

這麼一說,就很明顯是要用焦點事件了。之後會考慮用其他方案,例如paintComponent()實現一個支持更好的,因爲可以看到這種方法在JPasswordField內的使用是有問題的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章