日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

开发一个Swing功能时的一点总结

發布時間:2025/3/17 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 开发一个Swing功能时的一点总结 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

對JTextField進行效驗,有兩個途徑:
(1)是使用javax.swing.InputVerifier在獲取焦點時進行校驗
(2)在點擊“確定”按鈕的監聽事件中對控件的值進行校驗

鑒于涉及的業務比較多,代碼結構已經確定,如果在“確定”按鈕的監聽事件中進行效驗,需要增加一個步驟,并且并不是所有的業務都需要這個效驗,
就傾向于使用javax.swing.InputVerifier進行,這樣做有兩個好處,(1)分離業務邏輯與前端 (2)代碼更優雅

javax.swing.InputVerifier用的不多,用了之后發現這個控件的特性和以前UE的不同:
“校驗器并非問題很安全。如果點擊了某個按鈕,而這個按鈕在無效構件再次獲得焦點之前通知了它的動作監聽器,那么這個動作監聽器就會未通過校驗的構件中得到一個無效的結果。這種行為的原因在于:用戶可能希望點擊Cancel按鈕,而無需訂正無效輸入

還有個問題,如果控件JTextField在java.awt.Container中沒有獲得焦點,則相關校驗就不起作用

(Abstract)java.awt.FocusTraversalPolicy調整焦點順序(沒有生效)
或在Container上增加監聽,在Container執行setVisile(true)后
addWindowFocusListener(new WindowAdapter() {
??? public void windowGainedFocus(WindowEvent e) {
??????? textField.requestFocusInWindow();
??? }
});

進行這樣的處理后,在win7上程序出現一些意外的異常情況,并且由于增加監聽,也增加了程序的處理邏輯,進行了結構的調整

鑒于以上的情況,最終在“確定”按鈕的監聽中的處理流程中增加constraintCheck的邏輯

查找最小可用ID的一個算法:

package algorithm;import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;/*2015-6-26*/ public class FindMinUsefulValue {private static final int MIN = 1;public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>() {private static final long serialVersionUID = 1L;{add(1);add(2);add(5);add(3);add(10);add(100);add(9);}};Collections.sort(list);for (Integer item : list) {System.out.print(item + " ");}System.out.println("Result:" + search(list));}private static int search(List<Integer> list) {int max = list.get(list.size() - 1);if (max == list.size() + MIN - 1) {return max + 1;}int targetNum = MIN;for (int i = 0; i < list.size(); i++) {targetNum = MIN + i;if (list.get(i) == MIN + i) {continue;}break;}return targetNum;}/*** 查找最接近目標值的數,并返回* * @param array* @param targetNum* @return*/public static Integer binarysearchKey(Object[] array, int targetNum) {Arrays.sort(array);int targetindex = 0;int left = 0, right = 0;for (right = array.length - 1; left != right;) {int midIndex = (right + left) / 2;int mid = (right - left);int midValue = (Integer) array[midIndex];if (targetNum == midValue) {return midIndex;}if (targetNum > midValue) {left = midIndex;} else {right = midIndex;}if (mid <= 2) {break;}}System.out.println("和要查找的數:" + targetNum + "最接近的數:"+ array[targetindex]);return (Integer) (((Integer) array[right] - (Integer) array[left]) / 2 > targetNum ? array[right]: array[left]);} }

?

Output:

1 2 3 5 9 10 100 Result:4

?










Tutorials上的一個Sample:

package misc;import java.awt.*; import java.awt.event.*;import java.util.Vector;import javax.swing.*;/** FocusTraversalDemo.java requires no other files.*/ public class FocusTraversalDemo extends JPanelimplements ActionListener {static JFrame frame;JLabel label;JCheckBox togglePolicy;static MyOwnFocusTraversalPolicy newPolicy;public FocusTraversalDemo() {super(new BorderLayout());JTextField tf1 = new JTextField("Field 1");JTextField tf2 = new JTextField("A Bigger Field 2");JTextField tf3 = new JTextField("Field 3");JTextField tf4 = new JTextField("A Bigger Field 4");JTextField tf5 = new JTextField("Field 5");JTextField tf6 = new JTextField("A Bigger Field 6");JTable table = new JTable(4,3);togglePolicy = new JCheckBox("Custom FocusTraversalPolicy");togglePolicy.setActionCommand("toggle");togglePolicy.addActionListener(this);togglePolicy.setFocusable(false); //Remove it from the focus cycle.//Note that HTML is allowed and will break this run of text//across two lines.label = new JLabel("<html>Use Tab (or Shift-Tab) to navigate from component to component.<p>Control-Tab (or Control-Shift-Tab) allows you to break out of the JTable.</html>");JPanel leftTextPanel = new JPanel(new GridLayout(3,2));leftTextPanel.add(tf1, BorderLayout.PAGE_START);leftTextPanel.add(tf3, BorderLayout.CENTER);leftTextPanel.add(tf5, BorderLayout.PAGE_END);leftTextPanel.setBorder(BorderFactory.createEmptyBorder(0,0,5,5));JPanel rightTextPanel = new JPanel(new GridLayout(3,2));rightTextPanel.add(tf2, BorderLayout.PAGE_START);rightTextPanel.add(tf4, BorderLayout.CENTER);rightTextPanel.add(tf6, BorderLayout.PAGE_END);rightTextPanel.setBorder(BorderFactory.createEmptyBorder(0,0,5,5));JPanel tablePanel = new JPanel(new GridLayout(0,1));tablePanel.add(table, BorderLayout.CENTER);tablePanel.setBorder(BorderFactory.createEtchedBorder());JPanel bottomPanel = new JPanel(new GridLayout(2,1));bottomPanel.add(togglePolicy, BorderLayout.PAGE_START);bottomPanel.add(label, BorderLayout.PAGE_END);add(leftTextPanel, BorderLayout.LINE_START);add(rightTextPanel, BorderLayout.CENTER);add(tablePanel, BorderLayout.LINE_END);add(bottomPanel, BorderLayout.PAGE_END);setBorder(BorderFactory.createEmptyBorder(20,20,20,20));Vector<Component> order = new Vector<Component>(7);order.add(tf1);order.add(tf2);order.add(tf3);order.add(tf4);order.add(tf5);order.add(tf6);order.add(table);newPolicy = new MyOwnFocusTraversalPolicy(order);}//Turn the custom focus traversal policy on/off,//according to the checkboxpublic void actionPerformed(ActionEvent e) {if ("toggle".equals(e.getActionCommand())) {frame.setFocusTraversalPolicy(togglePolicy.isSelected() ?newPolicy : null);}}/*** Create the GUI and show it. For thread safety,* this method should be invoked from the* event-dispatching thread.*/private static void createAndShowGUI() {//Create and set up the window.frame = new JFrame("FocusTraversalDemo");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Create and set up the content pane.JComponent newContentPane = new FocusTraversalDemo();newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane);//Display the window. frame.pack();frame.setVisible(true);}public static void main(String[] args) {/* Use an appropriate Look and Feel */try {//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");} catch (UnsupportedLookAndFeelException ex) {ex.printStackTrace();} catch (IllegalAccessException ex) {ex.printStackTrace();} catch (InstantiationException ex) {ex.printStackTrace();} catch (ClassNotFoundException ex) {ex.printStackTrace();}/* Turn off metal's use of bold fonts */UIManager.put("swing.boldMetal", Boolean.FALSE);//Schedule a job for the event-dispatching thread://creating and showing this application's GUI.javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() {createAndShowGUI();}});}public static class MyOwnFocusTraversalPolicyextends FocusTraversalPolicy{Vector<Component> order;public MyOwnFocusTraversalPolicy(Vector<Component> order) {this.order = new Vector<Component>(order.size());this.order.addAll(order);}public Component getComponentAfter(Container focusCycleRoot,Component aComponent){int idx = (order.indexOf(aComponent) + 1) % order.size();return order.get(idx);}public Component getComponentBefore(Container focusCycleRoot,Component aComponent){int idx = order.indexOf(aComponent) - 1;if (idx < 0) {idx = order.size() - 1;}return order.get(idx);}public Component getDefaultComponent(Container focusCycleRoot) {return order.get(0);}public Component getLastComponent(Container focusCycleRoot) {return order.lastElement();}public Component getFirstComponent(Container focusCycleRoot) {return order.get(0);}} }

?



public abstract class InputVerifier extends Object
此類的用途是通過帶文本字段的 GUI 幫助客戶端支持流暢的焦點導航。在允許用戶導航到文本字段以外之前,這類 GUI 常常需要確保用戶輸入的文本是有效的(例如,文本具有正確的格式)。為做到這一點,客戶端要使用 JComponent 的 setInputVerifier 方法創建 InputVerifier 的子類,并將其子類的實例附加到想要驗證其輸入的 JComponent 中。在將焦點轉移到另一個請求它的 Swing 組件之前,要調用輸入驗證器的 shouldYieldFocus 方法。只在該方法返回 true 時才轉移焦點。

以下示例有兩個文本字段,其中第一個字段期望用戶輸入字符串 "pass"。如果在第一個文本字段中輸入該字符串,那么用戶可以通過在第二個文本字段上單擊或按下 TAB 前進到第二個文本字段。不過,如果將其他字符串輸入到第一個文本字段中,則用戶無法將焦點轉移到第二個文本字段。

import java.awt.*;import java.util.*;import java.awt.event.*;import javax.swing.*;// This program demonstrates the use of the Swing InputVerifier class.// It creates two text fields; the first of the text fields expects the// string "pass" as input, and will allow focus to advance out of it// only after that string is typed in by the user.public class VerifierTest extends JFrame {public VerifierTest() {JTextField tf1 = new JTextField ("Type \"pass\" here");getContentPane().add (tf1, BorderLayout.NORTH);tf1.setInputVerifier(new PassVerifier());JTextField tf2 = new JTextField ("TextField2");getContentPane().add (tf2, BorderLayout.SOUTH);WindowListener l = new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0); }};addWindowListener(l);}class PassVerifier extends InputVerifier {public boolean verify(JComponent input) {JTextField tf = (JTextField) input;return "pass".equals(tf.getText());}}public static void main(String[] args) {Frame f = new VerifierTest();f.pack();f.setVisible(true);}}

?







?

總結

以上是生活随笔為你收集整理的开发一个Swing功能时的一点总结的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。