ncyu_phyedu 板


LINE

GUI简介 GUI是由Component,LayoutManager以及Listener所组成的。Component是画面的主要组成 成分,本身并没有可见的实体,其子类别才有显现的效果。如果Component可以放入其他的 Component,则这种Component就称为是Container。Container里面的Component的排放位置 ,可以用绝对座标,也可以透过LayoutManager加以调整。使用者以Mouse,Keyboard等操作 GUI时,会产生相对应的Event,并由视窗系统将该Event传递给程式设计者所指定的 Listener。例如使用者以Mouse的左键按下Button(一种Component)时,视窗系统会将 ActionEvent传给该Button的ActionListener(设计者实作的物件),由ActionListener决定 采取的步骤。这种由使用者触发的执行动作,和程序式语言由主程式开始呼叫其他程序的 模式不同,我们称之为事件驱动(Event Driven)模式。 AWT(Abstract Window Toolkit, java.awt.*)是JDK 1.0所提出来有关GUI的函式库,在 JDK 1.1时又修改了Event Handling的机制, 成为现在的样子。当初为了快速开发出AWT, 以符合Java出版的时程, 因此在设计上, 是利用视窗系统已有的GUI元件为主。由於Java 原始的设计理念具有跨平台的性质, 因此AWT只好取各家视窗系统(Windows,Open Look, Motif, Machintosh)上元件的交集, 因此AWT颇为阳春。 为了弥补AWT的不足, JDK自1.2以後提供新的JFC(Java Foundation Class)/Swing的程式 库(javax.swing)。Swing是以Java语言所写出来的, 因此提供了更多样化而复杂的元件, 如Image JButton, Image JLabel, JTree, JTable, JTabbedPane, JPopupMenu等等。而 且由於Swing并不依靠底层的视窗系统画出元件的外观, 因此Swing可以让使用者自行选定 其所喜爱的look and feel。 为了让原先使用AWT的应用程式能改用Swing的程式库, AWT内所有的元件都有相对应以J开 头的Swing元件, 如Button对应JButton, TextField对应JTextField。原先AWT的程式只要 把Source Code里面的AWT元件前面加上J即可, 其余Event Handling和LayoutManager均可 沿用(除了JFrame, JDialog, JApplet, JWindow等最上层的Container不能直接加入元件 , 必须透过getContentPane()取得放置的地方)。 在以下的范例中, 我们主要采用AWT, 并在最後面给一个Swing的范例, 以说明两者间的相 似性。 AWT AWT中直接继承Component的子类别有 Button Canvas:空白的方形区域 Checkbox:勾选 Choice:拉下式表单 Container:里面还可以放入其他Component Label:可以显示文字 List:卷轴表单 Scrollbar:卷轴 TextComponent:可用以编辑文字,其子类别有 TextField(单行) TextArea(多行) Container的子类别有 Window:最上层的视窗,又有Frame(可以设定MenuBar的独立视窗), Dialog(必须依附在 Frame下的视窗), FileDialog等子类别。 Panel:没有显示的容器 ScrollPane: 具有ScrollBar的容器 AWT提供的LayoutManager有 BorderLayout: CardLayout FlowLayout: GridBagLayout: GridLayout: AWT定义的Event主要是java.awt.AWTEvent, 其下又有许多子类别(java.awt.event.*) ActionEvent: component-defined action occured AdjustmentEvent: ScrollBar被拉动 ComponentEvent:一般不直接使用, 其子类别有 ContainerEvent: Container加入或移除Component, 也很少用 FocusEvent: Gain or Lose Focus InputEvent: 有两个子类别 KeyEvent MouseEvent PaintEvent: 供AWT内部使用, 不用管他 WindowEvent: 视窗状态改变 HierarchyEvent: AWT自动处理, 不用管他 InputMethodEvent InvocationEvent: 由AWT event dispatcher thread呼叫Runnable物件里的run() ItemEvent: an item was selected or deselected TextEvent: an object's text changed 以上的Event都有相对应的Listener Interface来处理, 如ActionEvent相对应的是 ActionListener 井字游戏 import java.awt.*; import java.awt.event.*; public class OXMain extends Frame implements ActionListener { private OX oxBoard; private OXMain() { super("井字游戏"); Menu m; MenuBar mb; oxBoard = new OX(this); this.add(oxBoard); CloseWindow close = new CloseWindow(this, true); this.setMenuBar(mb = new MenuBar()); mb.add(m = new Menu("游戏")).add(new MenuItem("新游戏 ")).addActionListener(this); m.add(new MenuItem("结束")).addActionListener(close); mb.add(new Menu("说明")).add(new MenuItem("关於本游戏 ")).addActionListener(this); this.addWindowListener(close); pack(); setVisible(true); } public static void main(String argv[]) { new OXMain(); } // implements the ActionListener interface public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("关於本游戏")) { new ErrorDialog(this,"俞旭昇写好玩的"); } else if (command.equals("新游戏")) { oxBoard.newGame(); } } } class OX extends Component implements MouseListener { public static final byte EMPTY = 0; public static final byte CIRCLE = 1; public static final byte CROSS = 2; private byte[] board = new byte[9]; private byte playing = CIRCLE; private Dimension mySize = new Dimension(300,300); private Frame parent; private byte[][] directions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}}; public OX(Frame p) { this.addMouseListener(this); parent = p; } // The following 5 functions implement the MouseListener interface public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) { int row = e.getY()/100; int col = e.getX()/100; if (row >= 3 || col >= 3) return; // 超过边界 if (board[row*3+col] == EMPTY) { // 此位置可以下 board[row*3+col] = playing; repaint(); // notify Window Manager // Anyone Win? for (int i=0; i < directions.length; i++) { int j; for (j = 0; j < 3 && board[directions[i][j]]==playing; j++) ; if (j==3) { if (playing == CIRCLE) { new ErrorDialog(parent,"圆圈赢了"); } else if (playing == CROSS) { new ErrorDialog(parent,"叉叉赢了"); } this.newGame(); return; } } playing ^= 0x03; } } // override paint() defined in Component public void paint(Graphics g) { g.drawLine(0,100,300,100); g.drawLine(0,200,300,200); g.drawLine(100,0,100,300); g.drawLine(200,0,200,300); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i*3+j] == CIRCLE) { g.drawOval(50+j*100-25,50+i*100-25,50,50); } else if (board[i*3+j] == CROSS) { g.drawLine(25+j*100,25+i*100,75+j*100,75+i*100); g.drawLine(75+j*100,25+i*100,25+j*100,75+i*100); } } } } public void newGame() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i*3+j] = EMPTY; } } playing = CIRCLE; repaint(); } // override getPreferredSize defined in Component, // so that the Component has proper size on screen public Dimension getPreferredSize() { return mySize; } } // WindowAdapter implements the WindowLister interface // We extends WindowAdapter to reduce the line numer of code class CloseWindow extends WindowAdapter implements ActionListener { private Window target; private boolean exit; public CloseWindow(Window target, boolean exit) { this.target = target; this.exit = exit; } public CloseWindow(Window target) { this.target = target; } public void windowClosing(WindowEvent e) { target.dispose(); if (exit) System.exit(0); } public void actionPerformed(ActionEvent e) { target.dispose(); if (exit) System.exit(0); } } class AddConstraint { public static void addConstraint(Container container, Component component, int grid_x, int grid_y, int grid_width, int grid_height, int fill, int anchor, double weight_x, double weight_y, int top, int left, int bottom, int right) { GridBagConstraints c = new GridBagConstraints(); c.gridx = grid_x; c.gridy = grid_y; c.gridwidth = grid_width; c.gridheight = grid_height; c.fill = fill; c.anchor = anchor; c.weightx = weight_x; c.weighty = weight_y; c.insets = new Insets(top,left,bottom,right); ((GridBagLayout)container.getLayout()).setConstraints(component,c); container.add(component); } } class ErrorDialog extends Dialog { public ErrorDialog(Frame parent, String all[]) { this(parent, all, null); } public ErrorDialog(Frame parent, String all[], String msg) { super(parent,"",true); StringBuffer sb = new StringBuffer(); for (int i=0; i < all.length; i++) { sb.append(all[i]); sb.append('\n'); } if (msg!=null) { sb.append(msg); } setup(parent, sb.toString()); } public ErrorDialog(Frame parent, String message) { super(parent,"",true); setup(parent, message); } private void setup(Frame parent, String message) { this.setLayout(new GridBagLayout()); int row=0, col=0, i, width=0; Font font = new Font("Serif", Font.PLAIN, 16); char c=' '; for (i = 0; i < message.length(); i++) { c = message.charAt(i); if (c=='\n') { row++; if (width > col) { col = width; } width=0; } else if (c == '\t') { width += 7-width%7; } else { if (c > 0x00FF) { width+=2; } else { width++; } } } if (c!='\n') { row++; if (width > col) { col = width; } } col++; // 希望视窗出来不要太大或太小 row = (row > 24) ? 24 : row; if (row < 5) { row=5; } if (col < 20) { col = 20; } TextArea tx = new TextArea(message,row,col); tx.setEditable(false); tx.setFont(font); AddConstraint.addConstraint(this, tx, 0, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1,1,0,0,0,0); Button b = new Button("确定"); b.setFont(font); AddConstraint.addConstraint(this, b, 0, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1,0,0,0,0,0); CloseWindow cw = new CloseWindow(this); this.addWindowListener(cw); b.addActionListener(cw); pack(); setVisible(true); } } 井字游戏的Swing版本 /** * Program Name: SwingOXMain.java * Purpose: Showing how to Swing to write 井字游戏 * Modify Date: 2005/03/29 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingOXMain extends JFrame implements ActionListener { private OX oxBoard; private SwingOXMain() { super("井字游戏"); JMenu m; JMenuBar mb; oxBoard = new OX(this); this.getContentPane().add(oxBoard); CloseWindow close = new CloseWindow(this, true); this.setJMenuBar(mb = new JMenuBar()); mb.add(m = new JMenu("游戏")).add(new JMenuItem("新游戏 ")).addActionListener(this); m.add(new JMenuItem("结束")).addActionListener(close); mb.add(new JMenu("说明")).add(new JMenuItem("关於本游戏 ")).addActionListener(this); this.addWindowListener(close); pack(); setVisible(true); } public static void main(String argv[]) { new SwingOXMain(); } // implements the ActionListener interface public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("关於本游戏")) { new ErrorDialog(this,"俞旭昇写好玩的"); } else if (command.equals("新游戏")) { oxBoard.newGame(); } } } class OX extends Component implements MouseListener { public static final byte EMPTY = 0; public static final byte CIRCLE = 1; public static final byte CROSS = 2; private byte[] board = new byte[9]; private byte playing = CIRCLE; private Dimension mySize = new Dimension(300,300); private JFrame parent; private byte[][] directions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}}; public OX(JFrame p) { this.addMouseListener(this); parent = p; } // The following 5 functions implement the MouseListener interface public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) { int row = e.getY()/100; int col = e.getX()/100; if (row >= 3 || col >= 3) return; // 超过边界 if (board[row*3+col] == EMPTY) { // 此位置可以下 board[row*3+col] = playing; repaint(); // notify Window Manager // Anyone Win? for (int i=0; i < directions.length; i++) { int j; for (j=0; j &tl; 3 && board[directions[i][j]]==playing; j++) ; if (j==3) { if (playing == CIRCLE) { new ErrorDialog(parent,"圆圈赢了"); } else if(playing == CROSS) { new ErrorDialog(parent,"叉叉赢了"); } this.newGame(); return; } } playing ^= 0x03; } } // override paint() defined in Component public void paint(Graphics g) { g.drawLine(0,100,300,100); g.drawLine(0,200,300,200); g.drawLine(100,0,100,300); g.drawLine(200,0,200,300); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i*3+j] == CIRCLE) { g.drawOval(50+j*100-25,50+i*100-25,50,50); } else if (board[i*3+j] == CROSS) { g.drawLine(25+j*100,25+i*100,75+j*100,75+i*100); g.drawLine(75+j*100,25+i*100,25+j*100,75+i*100); } } } } public void newGame() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i*3+j] = EMPTY; } } playing = CIRCLE; repaint(); } // override getPreferredSize defined in Component, // so that the Component has proper size on screen public Dimension getPreferredSize() { return mySize; } } // WindowAdapter implements the WindowLister interface // We extends WindowAdapter to reduce the line numer of code class CloseWindow extends WindowAdapter implements ActionListener { private Window target; private boolean exit; public CloseWindow(Window target, boolean exit) { this.target = target; this.exit = exit; } public CloseWindow(Window target) { this.target = target; } public void windowClosing(WindowEvent e) { target.dispose(); if (exit) System.exit(0); } public void actionPerformed(ActionEvent e) { target.dispose(); if (exit) System.exit(0); } } class AddConstraint { public static void addConstraint(Container container, Component component, int grid_x, int grid_y, int grid_width, int grid_height, int fill, int anchor, double weight_x, double weight_y, int top, int left, int bottom, int right) { GridBagConstraints c = new GridBagConstraints(); c.gridx = grid_x; c.gridy = grid_y; c.gridwidth = grid_width; c.gridheight = grid_height; c.fill = fill; c.anchor = anchor; c.weightx = weight_x; c.weighty = weight_y; c.insets = new Insets(top,left,bottom,right); ((GridBagLayout)container.getLayout()).setConstraints(component,c); container.add(component); } } class ErrorDialog extends JDialog { public ErrorDialog(JFrame parent, String all[]) { this(parent, all, null); } public ErrorDialog(JFrame parent, String all[], String msg) { super(parent,"",true); StringBuffer sb = new StringBuffer(); for (int i = 0; i < all.length; i++) { sb.append(all[i]); sb.append('\n'); } if (msg != null) { sb.append(msg); } setup(parent, sb.toString()); } public ErrorDialog(JFrame parent, String message) { super(parent,"",true); setup(parent, message); } private void setup(JFrame parent, String message) { this.getContentPane().setLayout(new GridBagLayout()); int row=0, col=0, i, width=0; Font font = new Font("Serif", Font.PLAIN, 16); char c=' '; for (i=0; i < message.length(); i++) { c = message.charAt(i); if (c=='\n') { row++; if (width > col) { col = width; } width=0; } else if (c=='\t') { width += 7-width%7; } else { if (c > 0x00FF) { width+=2; } else { width++; } } } if (c!='\n') { row++; if (width > col) { col = width; } } col++; // 希望视窗出来不要太大或太小 row = (row > 24) ? 24 : row; if (row < 5) { row=5; } if (col < 20) { col = 20; } JTextArea tx = new JTextArea(message,row,col); tx.setEditable(false); tx.setFont(font); AddConstraint.addConstraint(this.getContentPane(), tx, 0, 0, 1, 1, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1,1,0,0,0,0); JButton b = new JButton("确定"); b.setFont(font); AddConstraint.addConstraint(this.getContentPane(), b, 0, 1, 1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1,0,0,0,0,0); CloseWindow cw = new CloseWindow(this); this.addWindowListener(cw); b.addActionListener(cw); pack(); setVisible(true); } } 文字编辑器 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.io.*; public class Editor extends WindowAdapter implements ActionListener { JFrame topWindow; JTextArea jta; public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("Open")) { JFileChooser fd = new JFileChooser("."); fd.setDialogType(JFileChooser.OPEN_DIALOG); int returnVal = fd.showOpenDialog(topWindow); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File file = fd.getSelectedFile(); BufferedReader fin = new BufferedReader(new FileReader(file)); StringBuffer sb = new StringBuffer(); String x; while ((x=fin.readLine()) != null) { sb.append(x); sb.append("\n"); } jta.setText(sb.toString()); } catch(Exception epp) {} jta.setCaretPosition(0); } } else if (command.equals("Save")) { JFileChooser fd = new JFileChooser("."); fd.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fd.showSaveDialog(topWindow); if (returnVal == JFileChooser.APPROVE_OPTION) { try { File file = fd.getSelectedFile(); FileWriter fout = new FileWriter(file); fout.write(jta.getText()); fout.close(); } catch(Exception epp) {} } } else if (command.equals("Find")) { String x = jta.getText(); int at = x.indexOf("int", jta.getCaretPosition()); if (at >= 0) { jta.setCaretPosition(at); jta.setSelectionStart(at); jta.setSelectionEnd(at+3); } } else { System.out.println("Unknown "+command); } } public void windowClosing(WindowEvent e) { topWindow.dispose(); System.exit(0); } public Editor() { Font myFont = new Font("细明体", Font.PLAIN, 20); topWindow = new JFrame("My IDE"); // get the root container of JFrame Container c = topWindow.getContentPane(); c.setLayout(new GridLayout(1,1)); JMenuBar jmb = new JMenuBar(); JMenu m = new JMenu("File"); m.setFont(myFont); JMenuItem mi = new JMenuItem("Open"); mi.setFont(myFont); mi.addActionListener(this); m.add(mi); mi = new JMenuItem("Save"); mi.setFont(myFont); mi.addActionListener(this); m.add(mi); mi = new JMenuItem("Find"); mi.setFont(myFont); mi.addActionListener(this); m.add(mi); jmb.add(m); topWindow.setJMenuBar(jmb); jta = new JTextArea(24,80); jta.setFont(myFont); jta.setCursor(new Cursor(Cursor.HAND_CURSOR)); JScrollPane jsp = new JScrollPane(jta); c.add(jsp); topWindow.addWindowListener(this); topWindow.pack(); // 压缩到最适当的大小 topWindow.show(); // 显示JFrame } public static void main(String[] argv) { new Editor(); } } 键盘事件处理范例 /* Program Name: Field.java Subject: 单一栏位输入 Author: 俞旭昇 Shiuh-Sheng Yu National ChiNan University Department of Information Management Since 1997/08/17 Last Update Date: 08/23/1998 2003/12/17, fix delete, tab 2004/04/26, 支援jdk1.2以後版本使用Ctrl-C,Ctrl-V复制贴上功能 ToolKit: JDK1.1.6 */ package ncnu.gui; import java.awt.*; import java.awt.event.*; import java.sql.Types; import java.awt.datatransfer.*; import java.io.IOException; public class Field implements ActionListener, KeyListener, Transferable, ClipboardOwner { static { try { if (System.getProperty("java.version").startsWith("1.1")) { checkCopy = false; } else { checkCopy = true; } } catch(Exception ex) { } } public DataFlavor[] getTransferDataFlavors() { DataFlavor[] myFlavors = new DataFlavor[1]; myFlavors[0] = DataFlavor.stringFlavor; return myFlavors; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(DataFlavor.stringFlavor); } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { return myData; } public void lostOwnership(Clipboard clipboard, Transferable contents) { } static String myData; static boolean checkCopy; public static final int OVR=0; public static final int INS=1; TextField t; int limit; int type; int decimalDigits; int mode=0; KeyJump parent; public Field(KeyJump parent, TextField t, int limit, int type, int decimalDigits) { this.t = t; this.limit = limit; this.type = type; this.decimalDigits = decimalDigits; this.parent = parent; this.mode = OVR; t.addActionListener((ActionListener)this); t.addKeyListener((KeyListener)this); } public void keyPressed(KeyEvent e) { String s; int pos,sstart,send; StringBuffer sb; switch(e.getKeyCode()) { case KeyEvent.VK_PASTE: case KeyEvent.VK_COPY: case KeyEvent.VK_UNDO: case KeyEvent.VK_CUT: case KeyEvent.VK_FIND: return; case KeyEvent.VK_INSERT: if (mode==OVR) { mode = INS; } else { mode = OVR; } e.consume(); break; case KeyEvent.VK_TAB: case KeyEvent.VK_ENTER: case KeyEvent.VK_DOWN: parent.next(t); e.consume(); break; case KeyEvent.VK_UP: parent.previous(t); e.consume(); break; case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_HOME: case KeyEvent.VK_END: return; case KeyEvent.VK_PAGE_UP: parent.pageUp(t); e.consume(); break; case KeyEvent.VK_PAGE_DOWN: parent.pageDown(t); e.consume(); break; case KeyEvent.VK_DELETE: e.consume(); if (!t.isEditable()) { return; } s = t.getText(); pos = t.getCaretPosition(); sstart=t.getSelectionStart(); send=t.getSelectionEnd(); if (send>sstart) { sb = new StringBuffer(s.substring(0,sstart)); if (send!=s.length()) { sb.append(s.substring(send)); } if ((type==Types.NUMERIC||type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(sstart); } else { if (pos==s.length()) { return; } sb = new StringBuffer(s.substring(0,pos)); sb.append(s.substring(pos+1)); if ((type==Types.NUMERIC || type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(pos); } return; case KeyEvent.VK_BACK_SPACE: e.consume(); if (!t.isEditable()) { return; } s = t.getText(); pos = t.getCaretPosition(); sstart=t.getSelectionStart(); send=t.getSelectionEnd(); if (send>sstart) { sb = new StringBuffer(s.substring(0,sstart)); if (send!=s.length()) { sb.append(s.substring(send)); } if ((type==Types.NUMERIC||type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(sstart); } else { if (pos==0) { return; } if (pos<=1) { sb = new StringBuffer(); } else { sb = new StringBuffer(s.substring(0,pos-1)); } sb.append(s.substring(pos)); if ((type==Types.NUMERIC||type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(pos-1); } return; } } public void keyTyped(KeyEvent e) { String s; int pos,sstart,send; StringBuffer sb; if (!t.isEditable()) { e.consume(); return; } char ch = e.getKeyChar(); // 3copy, 22 paste,127 delete,8 backspace if (checkCopy) { if (ch==3) { e.consume(); s = t.getText(); pos = t.getCaretPosition(); sstart=t.getSelectionStart(); send=t.getSelectionEnd(); if (send>sstart) { myData = s.substring(sstart,send); } else { myData = ""; } Toolkit.getDefaultToolkit().getSystemClipboard().setContents(this,this); } if (ch==22) { e.consume(); Transferable tt = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this); if (tt != null) { String data; try { data = (String)tt.getTransferData(DataFlavor.stringFlavor); } catch(Exception eppp) { System.out.println(eppp); return; } s = t.getText(); pos = t.getCaretPosition(); sstart=t.getSelectionStart(); send=t.getSelectionEnd(); if (send>sstart) { // 有选起来 sb = new StringBuffer(s.substring(0,sstart)); sb.append(data); if (send!=s.length()) { sb.append(s.substring(send)); } if ((type==Types.NUMERIC||type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(sstart); } else { sb = new StringBuffer(s.substring(0,pos)); sb.append(data); if (pos < s.length()) { sb.append(s.substring(pos)); } if ((type==Types.NUMERIC || type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } t.setText(sb.toString()); t.setCaretPosition(pos); } } } } if (ch==3 || ch==22 || ch==8 || ch==127 || ch=='\t' || ch=='\n') { e.consume(); return; } if (ch!=KeyEvent.CHAR_UNDEFINED) { s = t.getText(); sstart=t.getSelectionStart(); send=t.getSelectionEnd(); if (send>sstart) { sb = new StringBuffer(s.substring(0,sstart)); sb.append(ch); if (send!=s.length()) { sb.append(s.substring(send)); } } else { pos = t.getCaretPosition(); sb = new StringBuffer(s.substring(0,pos)); sb.append(ch); if (pos!=s.length()) { if (mode==INS) { sb.append(s.substring(pos)); } else { sb.append(s.substring(pos+1)); } } } if ((type==Types.NUMERIC||type==Types.DECIMAL) && !legalNumber(sb.toString())) { return; } pos = t.getCaretPosition(); t.setText(inputTruncate(sb.toString())); t.setCaretPosition(pos+1); } e.consume(); } public void keyReleased(KeyEvent e) { return; } public void actionPerformed(ActionEvent e) { int currentIndex, i; TextComponent next; switch(e.getID()) { case ActionEvent.ACTION_PERFORMED: parent.next(t); break; default: break; } } protected String inputTruncate(String s) { int i,j=limit; if (type==Types.NUMERIC||type==Types.DECIMAL) { int k=0, leading; if (decimalDigits==0) { leading = limit; } else { leading = limit-decimalDigits; } if (s.charAt(0)=='-') { k++; } for (; k < leading && k < s.length(); k++) { if (!(s.charAt(k) >='0' && s.charAt(k) <='9')) { break; } } if (decimalDigits!=0) { k += decimalDigits+1; } j = k; } if (s.getBytes().length>j) { for (i=s.length()-1; i > 0 ;i--) { if (s.substring(0,i).getBytes().length<=j) { break; } } return (s.substring(0,i)); } return s; } protected boolean legalNumber(String s) { int leading; int i=0,j=0; if (s.length()==0) { return true; } if (decimalDigits == 0) { leading = limit; } else { leading = limit - decimalDigits; } if (s.charAt(i)=='-') { j++; } for (;(j < s.length()) && (j < leading); j++) { if (!(s.charAt(j) >='0' && s.charAt(j) <='9')) { break; } } if (j==s.length()) { return true; } if (decimalDigits==0) { return false; } else { if (s.charAt(j)=='.') { j++; for (i=j; i!=s.length() && i-j < decimalDigits; i++) { if (!(s.charAt(i) >='0' && s.charAt(i) <='9')) { break; } } if (i==s.length()) { return true; } } return false; } } } --



※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.58.22.74







like.gif 您可能会有兴趣的文章
icon.png[问题/行为] 猫晚上进房间会不会有憋尿问题
icon.pngRe: [闲聊] 选了错误的女孩成为魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一张
icon.png[心得] EMS高领长版毛衣.墨小楼MC1002
icon.png[分享] 丹龙隔热纸GE55+33+22
icon.png[问题] 清洗洗衣机
icon.png[寻物] 窗台下的空间
icon.png[闲聊] 双极の女神1 木魔爵
icon.png[售车] 新竹 1997 march 1297cc 白色 四门
icon.png[讨论] 能从照片感受到摄影者心情吗
icon.png[狂贺] 贺贺贺贺 贺!岛村卯月!总选举NO.1
icon.png[难过] 羡慕白皮肤的女生
icon.png阅读文章
icon.png[黑特]
icon.png[问题] SBK S1安装於安全帽位置
icon.png[分享] 旧woo100绝版开箱!!
icon.pngRe: [无言] 关於小包卫生纸
icon.png[开箱] E5-2683V3 RX480Strix 快睿C1 简单测试
icon.png[心得] 苍の海贼龙 地狱 执行者16PT
icon.png[售车] 1999年Virage iO 1.8EXi
icon.png[心得] 挑战33 LV10 狮子座pt solo
icon.png[闲聊] 手把手教你不被桶之新手主购教学
icon.png[分享] Civic Type R 量产版官方照无预警流出
icon.png[售车] Golf 4 2.0 银色 自排
icon.png[出售] Graco提篮汽座(有底座)2000元诚可议
icon.png[问题] 请问补牙材质掉了还能再补吗?(台中半年内
icon.png[问题] 44th 单曲 生写竟然都给重复的啊啊!
icon.png[心得] 华南红卡/icash 核卡
icon.png[问题] 拔牙矫正这样正常吗
icon.png[赠送] 老莫高业 初业 102年版
icon.png[情报] 三大行动支付 本季掀战火
icon.png[宝宝] 博客来Amos水蜡笔5/1特价五折
icon.pngRe: [心得] 新鲜人一些面试分享
icon.png[心得] 苍の海贼龙 地狱 麒麟25PT
icon.pngRe: [闲聊] (君の名は。雷慎入) 君名二创漫画翻译
icon.pngRe: [闲聊] OGN中场影片:失踪人口局 (英文字幕)
icon.png[问题] 台湾大哥大4G讯号差
icon.png[出售] [全国]全新千寻侘草LED灯, 水草

请输入看板名称,例如:Boy-Girl站内搜寻

TOP