Kali ini saya membuat tutorial sederhana untuk membuat sebuah input pada Java (Swing) langsung merubah format isiannya menjadi angka dengan pemisah ribuan, misalnya ketika diinput 1000
akan berubah menjadi 1.000
, namun tetap dengan menyimpan data aslinya, sehingga apabila diinginkan, tetap dapat diambil data asli input tersebut.
Saya berikan dalam 2 file (Class), dimana Class utama dari tutorial ini adalah Class NumberTextField. Sedangkan class Main hanya berfungsi demo saja.
Aplikasi (executable) jar demo ini bisa didownload disini.
Class NumberTextField (file NumberTextField.java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import javax.swing.*; import javax.swing.text.MaskFormatter; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** * Created with IntelliJ IDEA. * Author: Lee * Date: 5/20/2014 * Time: 1:50 PM * To change this template use File | Settings | File Templates. */ public class NumberTextField extends JTextField { private char separator = '.'; public NumberTextField(){ super(); setHorizontalAlignment(SwingConstants.RIGHT); setText("0"); addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent focusEvent) { NumberTextField.super.setText(getText()); NumberTextField.super.selectAll(); } @Override public void focusLost(FocusEvent e){ setText(NumberTextField.super.getText()); } }); addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) { getToolkit().beep(); e.consume(); } } }); // */ } public void setSeparator(char s){ separator = s; } @Override public void setText(String s){ super.setText(formatNumber(s)); } @Override public String getText() { String s = super.getText(); return s.replaceAll("[^0-9]", ""); } public String getNumberFormattedText(){ return super.getText(); } public String formatNumber(String s){ try { int v = Integer.parseInt(s); return String.format("%,d", v).replace(",", separator + ""); } catch (Exception e) { return "0"; } } // */ } |
Class Main (file Main.java)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import sun.awt.HorizBagLayout; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created with IntelliJ IDEA. * User: lee * Date: 6/22/14 * Time: 1:01 PM */ public class Main { public static void main(String[] args){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e){ } final JFrame f = new JFrame(); f.setTitle("Number Formatted Input Field"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setMinimumSize(new Dimension(400, 100)); final JPanel body = new JPanel(); body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); body.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); f.getContentPane().add(body, BorderLayout.CENTER); for(int i = 1; i <= 5; i++){ JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); p.add(new JLabel("Input " + i)); p.add(Box.createHorizontalStrut(10)); NumberTextField input = new NumberTextField(); // misalnya diinginkan separator ribuan yang 'aneh'; // input.setSeparator('-'); p.add(input); body.add(p); body.add(Box.createVerticalStrut(5)); } JButton b = new JButton("Lihat Input"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String res = "", temp; for(int i = 1; i <= 10; i++){ if( i % 2 == 0) continue; JPanel p; try{ p = (JPanel) body.getComponent(i - 1); } catch (Exception e){ System.out.println("Error: " + i); e.printStackTrace(); continue; } temp = String.format("input ke %s diisi %s = %s \n", (i / 2) + 1, ((NumberTextField) p.getComponent(2)).getText(), ((NumberTextField) p.getComponent(2)).getNumberFormattedText() );; if(res.equals("")){ res = temp; } else { res += temp; } } JOptionPane.showMessageDialog(f, res); } }); body.add(b); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } } |
Sebagai catatan, GUI dari aplikasi ini tidak saya buat dengan Builder (misalnya Netbeans), jadi tidak ada operasi drag n drop untuk GUI nya. Lagipula, GUI ini hanya demo saja.
Namun tentu saja jangan lupa, untuk kepentingan format angka yang lebih canggih, ada NumberFormat
di Java.
Enjoy.