SourcePost_____


このページのコンテンツ一覧(5個位までにしてください。上が最新で下が最古です)

宿題スレPart59 >>363 への回答 中断可能な計算

JDK5で作成。例外処理は書いてません。

   // CalculatorDemo.java
   public class CalculatorDemo {
       public static void main(String[] args) {
           CalculatorFrame frame = new CalculatorFrame();
           frame.setTitle("CalculatorFrame");
           frame.setSize(300, 100);
           frame.setVisible( true );
           frame.setDefaultCloseOperation( CalculatorFrame.EXIT_ON_CLOSE );
       }
   }
   // CalculatorFrame.java
   import java.awt.BorderLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.io.BufferedWriter;
   import java.io.File;
   import java.io.FileWriter;
   import java.io.IOException;
   import java.math.BigInteger;
   import java.text.NumberFormat;
   import java.util.Date;
   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JOptionPane;
   import javax.swing.JPanel;
   import javax.swing.JTextArea;
   import javax.swing.JTextField;
   
   public class CalculatorFrame extends JFrame implements ActionListener, Runnable {
       private JTextField startText, endText;
       private BigInteger start, end;
       private JTextArea messageArea;
       private JButton button;
       private Thread thread;
       private boolean reserveStop;
       private File file;
       
       public CalculatorFrame() {
           startText = new JTextField(5);
           endText = new JTextField(5);
           JPanel panel = new JPanel(new BorderLayout());
           JPanel panel1 = new JPanel();
           panel1.add(new JLabel("add from"));
           panel1.add(startText);
           panel1.add(new JLabel("to"));
           panel1.add(endText);
           button = new JButton("=");
           button.addActionListener(this);
           panel1.add(button);
           panel.add(panel1, BorderLayout.NORTH);
           messageArea = new JTextArea();
           panel.add(messageArea, BorderLayout.CENTER);
           getContentPane().add(panel);
           thread = new Thread(this);
       }
       
       public void actionPerformed(ActionEvent e) {
           if (e.getActionCommand().equals("=")) {
               try {
                   start = new BigInteger(startText.getText());
                   end = new BigInteger(endText.getText());
                   thread.start();
               } catch (NumberFormatException e1) {
                   e1.printStackTrace();
               }
           } else if (e.getActionCommand().equals("pause")) {
               reserveStop = true;
               button.setText("restart");
           } else if (e.getActionCommand().equals("restart")) {
               thread.interrupt();
               button.setText("pause");
           }
       }
       
       public void run() {
           button.setText("pause");
           BigInteger sum = new BigInteger("0");
           final BigInteger ONE = new BigInteger("1");
           for (BigInteger i = start; i.compareTo(end) != 1; i=i.add(ONE)) {
               sum = sum.add( i );
               messageArea.setText("the sum from " + start + " to " + i + ":\n"
                       + NumberFormat.getInstance().format(sum));
               synchronized (thread) {
                   if( reserveStop ) {
                       reserveStop = false;
                       try {
                           thread.wait();
                       } catch(InterruptedException ie) {
                       }
                   }
               }
           }
           button.setVisible(false);
           JOptionPane.showMessageDialog(this, "I've just finished your calculation!");
           writeToFile();
           JOptionPane.showMessageDialog(this, "I wrote the result to " + file.getName() + ".");
       }
       
       private void writeToFile() {
           file = new File("result_" + new Date().getTime() + ".txt");
           BufferedWriter bw = null;
           try {
               bw = new BufferedWriter( new FileWriter(file) );
               bw.write( messageArea.getText() );
               bw.flush();
           } catch (IOException e) {
               e.printStackTrace();
           } finally {
               if( bw != null ) {
                   try {
                       bw.close();
                   } catch (IOException e) {}
               }
           }
       }
   }

宿題スレPart57 >>800 への回答 複数の銀行に対する口座開設

http://pc8.2ch.net/test/read.cgi/tech/1152253441/800n の答案です。
事情で2chに書き込めないので、気づいた人が>>800に教えてあげてください。

   // CreateSequentialFile.java
   import java.awt.Button;
   import java.awt.Choice;
   import java.awt.Frame;
   import java.awt.GridLayout;
   import java.awt.Label;
   import java.awt.TextField;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.io.DataOutputStream;
   import java.io.FileOutputStream;
   import java.io.IOException;
   
   public class CreateSequentialFile extends Frame implements ActionListener {
       private TextField accountField, firstNameField, lastNameField, balanceField;
       private Choice bankChoice;
       private Button enter, done;
       private DataOutputStream fooOutput, barOutput;
   
       public CreateSequentialFile() {
           super("Create Client File");
   
           try {
               fooOutput = new DataOutputStream(new FileOutputStream("foo.dat", true));
               barOutput = new DataOutputStream(new FileOutputStream("bar.dat", true));
           } catch (IOException e) {
               System.err.println("File not opened properly\n" + e.toString());
               System.exit(1);
           }
   
           setSize(300, 150);
           setLayout(new GridLayout(6, 2));
           
           
           add(new Label("Bank Name"));
           bankChoice = new Choice();
           bankChoice.add("");
           bankChoice.add("foo bank");
           bankChoice.add("bar bank");
           add(bankChoice);
           
           add(new Label("Account Number"));
           accountField = new TextField();
           add(accountField);
   
           add(new Label("First Name"));
           firstNameField = new TextField(20);
           add(firstNameField);
   
           add(new Label("Last Name"));
           lastNameField = new TextField(20);
           add(lastNameField);
   
           add(new Label("Balance"));
           balanceField = new TextField(20);
           add(balanceField);
   
           enter = new Button("Enter");
           enter.addActionListener(this);
           add(enter);
   
           done = new Button("Done");
           done.addActionListener(this);
           add(done);
   
           setVisible(true);
       }
   
       /**
        * check user input
        * 
        * Account Number: should not be null & should be int type
        * First Name: should not be null
        * Last Name: should not be null
        * Ballance: should not be null & should be double type
        * @return error message
        */
       private String checkInput() {
           String bankChoiceString = bankChoice.getSelectedItem();
           String accountNumberString = accountField.getText();
           String firstNameString = firstNameField.getText();
           String lastNameString = lastNameField.getText();
           String balanceString = balanceField.getText();
           // mandatory check
           if( bankChoiceString.length() == 0 || accountNumberString.length() == 0 
               || firstNameString.length() == 0
               || lastNameString.length() == 0 || balanceString.length() == 0) {
               return "every input field is required.";
           } else {
               // type check of account number
               try {
                   int accountNumber = Integer.parseInt( accountNumberString );
                   if( accountNumber <= 0 ) {
                       return "account number is invalid(should be more than 0).";
                   }
               } catch( NumberFormatException nfe ) {
                   return "account number should be int type.";
               }
               // type check of balance
               try {
                   double balance = Double.parseDouble(balanceString);
                   if( balance == Double.NaN ) {
                       return "balance is invalid.";
                   }
               } catch( NumberFormatException nfe ) {
                   return "balance shold be double type.";
               }
           }
           return null;
       }
       
       private DataOutputStream selectOutputFile(String bankName) {
           if( bankName.equals( "foo bank" ) ) {
               return fooOutput;
           } else if( bankName.equals("bar bank") ) {
               return barOutput;
           } else {
               return null;
           }
       }
       
       public void addRecord(DataOutputStream output) {
           
           int accountNumber = 0;
           Double d;
   
           // if inputs are correct
           String errorMessage = checkInput();
           if( errorMessage == null ) {
               try {
                   accountNumber = Integer.parseInt(accountField.getText());
                   output.writeInt(accountNumber);
                   output.writeUTF(firstNameField.getText());
                   output.writeUTF(lastNameField.getText());
                   d = new Double(balanceField.getText());
                   output.writeDouble(d.doubleValue());
   
                   accountField.setText("");
                   firstNameField.setText("");
                   lastNameField.setText("");
                   balanceField.setText("");
                   
                   System.out.println( "accepted." );
               } catch (IOException io) {
                   System.err.println("Error during write to file\n" + io.toString());
                   System.exit(1);
               }
           // if each of inputs is incorrect
           } else {
               System.err.println( errorMessage );
           }
       }
   
       public void actionPerformed(ActionEvent e) {
           DataOutputStream output = selectOutputFile(bankChoice.getSelectedItem());
           if( e.getSource() == enter ) {
               addRecord(output);
           } else if (e.getSource() == done) {
               if( checkInput() == null ) {
                   addRecord(output);
                   try {
                       output.close();
                   } catch (IOException io) {
                       System.err.println("File not closed properly\n" + io.toString());
                       System.exit(0);
                   }
               }
               System.exit(0);
           }
       }
   
       public static void main(String[] args) {
           new CreateSequentialFile();
       }
   }
   // CreditInquiry.java
   import java.io.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.text.DecimalFormat;
   
   public class CreditInquiry extends Frame implements ActionListener {
   
       private TextArea recordDisplay;
       private Button done, credit, debit, zero;
       private Panel buttonPanel;
       private RandomAccessFile fooInput, barInput;
       private String accountType;
       private RandomAccessFile[] inputStreams;
       private String[] bankNames;
       private int index;
   
       public CreditInquiry() {
           super("Credit Inquiry Program");
           try {
               fooInput = new RandomAccessFile("foo.dat", "r");
               barInput = new RandomAccessFile("bar.dat", "r");
           } catch (IOException e) {
               System.err.println(e.toString());
               System.exit(1);
           }
   
           inputStreams = new RandomAccessFile[] { fooInput, barInput, };
           bankNames = new String[] { "foo bank", "bar bank", };
           
           setSize(400, 150);
   
           buttonPanel = new Panel();
           credit = new Button("Credit balances");
           credit.addActionListener(this);
           buttonPanel.add(credit);
           debit = new Button("Debit balances");
           debit.addActionListener(this);
           buttonPanel.add(debit);
           zero = new Button("Zero balances");
           zero.addActionListener(this);
           buttonPanel.add(zero);
           done = new Button("Done");
           done.addActionListener(this);
           buttonPanel.add(done);
           recordDisplay = new TextArea(4, 40);
   
           add(recordDisplay, BorderLayout.NORTH);
           add(buttonPanel, BorderLayout.SOUTH);
   
           setVisible(true);
       }
   
       public void actionPerformed(ActionEvent e) {
           if (e.getSource() != done) {
               accountType = e.getActionCommand();
               readRecords();
           } else {
               try {
                   for( index=0; index<inputStreams.length; index++ ) {
                       inputStreams[index].close();
                   }
               } catch (IOException ioe) {
                   System.err.println("File not closed properly\n" + ioe.toString());
                   System.exit(1);
               }
               System.exit(0);
           }
       }
   
       public void readRecords() {
           int account;
           String first, last;
           double balance;
           DecimalFormat twoDigits = new DecimalFormat("0.00");
           recordDisplay.setText("The accounts are: \n");
           try {
               for( index=0; index<inputStreams.length; ) {
                   try {
                       account = inputStreams[index].readInt();
                       first = inputStreams[index].readUTF();
                       last = inputStreams[index].readUTF();
                       balance = inputStreams[index].readDouble();
                       if (shouldDisplay(balance)) {
                           recordDisplay.append(bankNames[index] + "\t" + account + "\t" + first + "\t" + last + "\t" + twoDigits.format(balance) + "\n");
                       }
                   } catch (EOFException e) {
                       inputStreams[index].seek(0);
                       index++;
                   }
               }
           } catch (IOException e) {
               System.err.println("Error during read from file\n" + e.toString());
               System.exit(1);
           }
       }
   
       public boolean shouldDisplay(double balance) {
           if (accountType.equals("Credit balances") && balance < 0) {
               return true;
           } else if (accountType.equals("Debit balances") && balance > 0) {
               return true;
           } else if (accountType.equals("Zero balances") && balance == 0) {
               return true;
           }
           return false;
       }
   
       public static void main(String args[]) {
           new CreditInquiry();
       }
   }
   // ReadSequentialFile.java
   import java.io.*;
   import java.awt.*;
   import java.awt.event.*;
   
   public class ReadSequentialFile extends Frame implements ActionListener {
   
       private TextField bankField, accountField, firstNameField, lastNameField, balanceField;
       private Button next, done;
       private DataInputStream fooInput, barInput;
       private DataInputStream[] inputStreams;
       private String[] bankNames;
           
       private int index = 0;
   
       public ReadSequentialFile() {
           super("Read Client File");
           try {
               fooInput = new DataInputStream(new FileInputStream("foo.dat"));
               barInput = new DataInputStream(new FileInputStream("bar.dat"));
           } catch (IOException e) {
               System.err.println("File not opened properly\n" + e.toString());
               System.exit(1);
           }
   
           inputStreams = new DataInputStream[] { fooInput, barInput, };
           bankNames = new String[] { "foo bank", "bar bank", };
           
           setSize(300, 150);
           setLayout(new GridLayout(6, 2));
           
           add(new Label("Bank Name"));
           bankField = new TextField();
           bankField.setEditable(false);
           add(bankField);
           
           add(new Label("Account Number"));
           accountField = new TextField();
           accountField.setEditable(false);
           add(accountField);
   
           add(new Label("First Name"));
           firstNameField = new TextField(20);
           firstNameField.setEditable(false);
           add(firstNameField);
   
           add(new Label("Last Name"));
           lastNameField = new TextField(20);
           lastNameField.setEditable(false);
           add(lastNameField);
   
           add(new Label("Balance"));
           balanceField = new TextField(20);
           balanceField.setEditable(false);
           add(balanceField);
   
           next = new Button("Next");
           next.addActionListener(this);
           add(next);
   
           done = new Button("Done");
           done.addActionListener(this);
           add(done);
   
           setVisible(true);
   
       }
   
       public void actionPerformed(ActionEvent e) {
           if (e.getSource() == next)
               readRecord();
           else {
               for( int i=0; i<inputStreams.length; i++ ) {
                   closeFile(i);
               }
               System.exit(0);
           }
       }
   
       public void readRecord() {
           int account;
           String first, last;
           double balance;
   
           try {
               account = inputStreams[index].readInt();
               first = inputStreams[index].readUTF();
               last = inputStreams[index].readUTF();
               balance = inputStreams[index].readDouble();   
             
               bankField.setText(bankNames[index]);
               accountField.setText(String.valueOf(account));
               firstNameField.setText(first);
               lastNameField.setText(last);
               balanceField.setText(String.valueOf(balance));
           } catch (EOFException eof) {
               closeFile( index );
               index++;
           } catch (IOException e) {
               e.printStackTrace();
           } catch( ArrayIndexOutOfBoundsException aioobe ) {
               System.exit(0);
           }
       }
   
       private void closeFile(int index) {
           try {
               inputStreams[index].close();
               System.out.println( "file of \"" + bankNames[index] + "\" is closed..." );
           } catch (IOException e) {
               System.err.println("Error closing file\n" + e.toString());
               System.exit(1);
           }
       }
   
       public static void main(String args[]) {
           new ReadSequentialFile();
       }
   }

宿題スレPart55 >>682 への回答 ホテル利用客管理

   // Main.java
   package a5;
   
   import java.io.BufferedReader;
   import java.io.IOException;
   import java.io.InputStreamReader;
   import java.util.ArrayList;
   
   public class Main {
   
       public static void main(String[] args) throws IOException {
   
           Person[] myPeople = A5Arrays.getPersonArray();
   
           // Debug start
           System.out.println("-----");
           for (int i = 0; i < myPeople.length; i++) {
               System.out.println(myPeople[i]);
           }
           System.out.println("-----");
           // Debug end
   
           System.out.println("Total guests are " + myPeople.length);
           System.out.println("Avarage age is " + getAverage(myPeople));
           System.out.println("Oldest guest name is " + getOldestPersonNames(myPeople) + " and this guest age is " + getOldestAge(myPeople));
           System.out.println("Youngest guest name is " + getYoungestPersonNames(myPeople) + " and this guest age is " + getYoungestAge(myPeople));
           System.out.println("Minor(Under 18) guests have " + getMinor(myPeople));
           System.out.println("Senior(Over 55) guests have " + getSenior(myPeople));
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
           System.out.print("Input Initial > ");
           String line = br.readLine();
           int count = getInitialCount(myPeople, line);
           System.out.println("Typed initial people have " + count + ".");
       }
   
       public static double getAverage(Person[] myPeople) {
           double total = 0;
           for (int i = 0; i < myPeople.length; i++) {
               total += myPeople[i].getAge();
           }
           return total / myPeople.length;
       }
   
       public static int getOldestAge(Person[] myPeople) {
           int result = Integer.MIN_VALUE;
           for( int i=0; i<myPeople.length; i++ ) {
               result = Math.max( result, myPeople[i].getAge() );
           }
           return result;
       }
   
       public static int getYoungestAge(Person[] myPeople) {
           int result = Integer.MAX_VALUE;
           for( int i=0; i<myPeople.length; i++ ) {
               result = Math.min( result, myPeople[i].getAge() );
           }
           return result;
       }
   
       public static String getOldestPersonNames( Person[] myPeople ) {
           StringBuilder buffer = new StringBuilder();
           Person[] persons = getPersonByAge( myPeople, getOldestAge(myPeople) );
           for( int i=0; i<persons.length; i++ ) {
               buffer.append( persons[i].getFirst() + " " + persons[i].getLast() + ", " );
           }
           return buffer.toString();
       }
       
       public static String getYoungestPersonNames( Person[] myPeople ) {
           StringBuilder buffer = new StringBuilder();
           Person[] persons = getPersonByAge( myPeople, getYoungestAge(myPeople) );
           for( int i=0; i<persons.length; i++ ) {
               buffer.append( persons[i].getFirst() + " " + persons[i].getLast() + ", " );
           }
           return buffer.toString();
       }
   
       
       /**
        * 第2引数の年齢と等しいPerson[]オブジェクトを第1引数のPerson[]リストから取得して返却。
        * 戻り値が配列なのは、第2引数の年齢の人がリストに1人しかいないとは限らないから。
        * 
        * @param myPeople Person[]リスト
        * @param age 年齢
        * @return 指定した年齢のPersonをリストから取得したもの
        */
       private static Person[] getPersonByAge(Person[] myPeople, int age) {
           ArrayList<Person> result = new ArrayList<Person>();
           for (int i = 0; i < myPeople.length; i++) {
               if (myPeople[i].getAge() == age) {
                   result.add( myPeople[i] );
               }
           }
           return result.toArray( new Person[0] );
       }
   
       public static int getMinor(Person[] myPeople) {
           int minorTotal = 0;
           for (int i = 0; i < myPeople.length; i++) {
               if (myPeople[i].getAge() <= 18) {
                   minorTotal++;
               }
           }
           return minorTotal;
       }
   
       public static int getSenior(Person[] myPeople) {
           int seniorTotal = 0;
           for (int i = 0; i < myPeople.length; i++) {
               if (myPeople[i].getAge() >= 55) {
                   seniorTotal++;
               }
           }
           return seniorTotal;
       }
   
       public static int getInitialCount( Person[] myPeople, String initial ) {
           int count = 0;
           for( int i=0; i<myPeople.length; i++ ) {
               if( myPeople[i].getLast().toLowerCase().startsWith( initial.toLowerCase() ) ) {
                   count++;
               }
           }
           return count;
       }
   }
   // Person.java
   package a5;
   
   class Person {
   
       public static final String DEFAULT_LAST = "BAR";
   
       public static final String DEFAULT_FIRST = "FOO";
   
       public static final int DEFAULT_AGE = -1;
   
       private String lastName;
   
       private String firstName;
   
       private int age;
   
       public Person() {
           this(DEFAULT_LAST, DEFAULT_FIRST, DEFAULT_AGE);
       } // end default constructor
   
       public Person(String lName, String fName, int anAge) {
           lastName = lName;
           firstName = fName;
           age = anAge;
       } // end constructor
   
       public void setLast(String lName) {
           lastName = lName;
       } // end setLast
   
       public void setFirst(String fName) {
           firstName = fName;
       } // end setFirst
   
       public void setAge(int anAge) {
           age = anAge;
       }
   
       public String getLast() {
           return lastName;
       }
   
       public String getFirst() {
           return firstName;
       }
   
       public int getAge() {
           return age;
       }
       
       /**
        * for Debug
        */
       public String toString() {
           return this.firstName + " " + this.lastName + " (" + this.age + ")";
       }
   }

宿題スレPart55 >>435 への回答 音楽ダウンロードサービスのユーザインタフェース(途中)

やる気なくなりました。明日続きをやるかも。やらないかも。
JDK5.0です。

   // MusicServiceDemo.java
   public class MusicServiceDemo {
       public static void main(String[] args) {
           MusicServiceFrame frame = new MusicServiceFrame();
           frame.setTitle( "ログイン画面" );
           frame.setSize( 240, 320 );
           frame.setVisible( true );
           frame.setDefaultCloseOperation( MusicServiceFrame.EXIT_ON_CLOSE );
       }
   }
   // MusicServiceFrame.java
   import java.awt.BorderLayout;
   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.awt.event.FocusEvent;
   import java.awt.event.FocusListener;
   import java.util.ArrayList;
   
   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JLabel;
   import javax.swing.JPanel;
   import javax.swing.JTextField;
   
   public class MusicServiceFrame extends JFrame implements FocusListener, ActionListener {
       JTextField nameField, mailField, idField, lastFocused;
       ArrayList<JButton> buttonList = new ArrayList<JButton>();
       JButton loginButton;
       public MusicServiceFrame() {
           JPanel panel = new JPanel( new BorderLayout() );
           JPanel panel1 = new JPanel( new GridLayout( 3, 2 ) );
           panel1.add( new JLabel("名前") );
           panel1.add( nameField = new JTextField() );
           panel1.add( new JLabel("メールアドレス") );
           panel1.add( mailField = new JTextField() );
           panel1.add( new JLabel("会員番号") );
           panel1.add( idField = new NumberInputJTextField() );
           nameField.addFocusListener( this );
           mailField.addFocusListener( this );
           idField.addFocusListener( this );
           nameField.setEditable( false );
           mailField.setEditable( false );
           idField.setEditable( false );
           JPanel panel2 = new JPanel( new GridLayout( 8, 5 ) );
           // アルファベット
           for( int i=0; i<26; i++ ) buttonList.add(new JButton( "" + (char)(i+97) ) );
           // 数字
           for( int j=0; j<10; j++ ) buttonList.add(new JButton( "" + (char)(j+48) ) );
           // 記号(手抜き)
           buttonList.add( new JButton( "@" ) );
           buttonList.add( new JButton( "." ) );
           buttonList.add( new JButton( "-" ) );
           buttonList.add( new JButton( "_" ) );
           for( int i=0; i<buttonList.size(); i++ ) {
               JButton button = buttonList.get( i );
               button.addActionListener( this );
               panel2.add( button );
           }
           panel.add( BorderLayout.NORTH, panel1 );
           panel.add( BorderLayout.CENTER, panel2 );
           panel.add( BorderLayout.SOUTH, loginButton = new JButton( "dive" ) );
           loginButton.addActionListener( this );
           add( panel );
       }
   
       public void focusGained(FocusEvent fe) {
           JTextField tf = (JTextField)fe.getSource();
           tf.setSelectionStart( 0 );
           tf.setSelectionEnd( tf.getText().length() );
           if( tf instanceof NumberInputJTextField ) enableOnlyNumberButton();
           else enableAllButton();
       }
       
       private void enableOnlyNumberButton() {
           for( int i=0; i<buttonList.size(); i++ ) {
               JButton button = buttonList.get( i );
               try {
                   Integer.parseInt( button.getActionCommand() );
                   button.setEnabled( true );                
               } catch( NumberFormatException nfe ) {
                   button.setEnabled( false );
               }
           }        
       }
       
       private void enableAllButton() {
           for( int i=0; i<buttonList.size(); i++ ) {
               JButton button = buttonList.get( i );
               button.setEnabled( true );
           }
       }
       
       public void focusLost(FocusEvent fe) {
           lastFocused = (JTextField)fe.getSource();
       }
   
   
       public void actionPerformed(ActionEvent ae) {
           if( ae.getSource() == loginButton ) {
               // TODO
           } else {
               lastFocused.setEditable(true);
               lastFocused.cut();
               lastFocused.setText( lastFocused.getText() + ae.getActionCommand() );
               lastFocused.setEditable(false);
           }
       }
   }
   // NumberInputJTextField.java
   import javax.swing.JTextField;
   import javax.swing.text.AttributeSet;
   import javax.swing.text.BadLocationException;
   import javax.swing.text.Document;
   import javax.swing.text.PlainDocument;
   
   /**
    * @see ttp://satoshi.kinokuni.org/tech/SwingTipsString.html
    */
   public class NumberInputJTextField extends JTextField {
   
       /**
        * デフォルトコンストラクタ
        *
        */
       public NumberInputJTextField() {
           this(0);
       }
       
       /**
        * コンストラクタ
        */
       public NumberInputJTextField(int columns){
           super(columns);
       }
   
       /**
        * ドキュメントクラスを作成して取得します。<br>
        * 入力文字種を制限するためにカスタマイズしたドキュメントクラスを作成します。
        * <p>
        *
        * @return このクラスのドキュメントクラス
        */
       protected Document createDefaultModel() {
           return new NumberInputDocument();    // <-- ここ
       }
   
       /* --------------------------------------------- */
       /* ここからドキュメントクラスのカスタマイズ         */
       /* --------------------------------------------- */
   
       /**
        * カスタマイズしたドキュメントクラスです。
        */
       private class NumberInputDocument extends PlainDocument {
   
           /**
            * フィールドに文字列が挿入される際に呼び出される挿入処理です。
            * <p>
            * 入力された文字種を判断して、数字のみを挿入します。
            * <p>
            *
            * @param offs オフセット(挿入開始位置)
            * @param str  挿入文字列
            * @param a    AttributeSet(文字の属性)
            * @exception  BadLocationException
            */
           public void insertString(int offs, String str, AttributeSet a)
               throws BadLocationException {
   
               // 文字列が入ってきていないのにメソッドが呼ばれた場合は何もしない。
               if (str == null) return;
               // 5文字以上は入力できない
               if( str.length() > 5 ) str = str.substring(0, 5);
               
               // 実際に挿入をするオフセット
               int realOffs = offs;
              
               // 入力文字列を一文字ずつ判定
               for (int i = 0; i < str.length(); i++){
                   char c = str.charAt(i);
                                   
                   switch( c ) {
                   	case '0':
                   	case '1':
                   	case '2':
                   	case '3':
                   	case '4':
                   	case '5':
                   	case '6':
                   	case '7':
                   	case '8':
                   	case '9':
                   	    // 上記の文字なら挿入
                   	    super.insertString(realOffs, String.valueOf(c), a);
                   	    realOffs++;
                       default :
                           break;
                   }
               }
           }
       }
   }
   

宿題スレPart55 >>353 への回答 (3)ストップウォッチ

   // StopWatchApplet.java
   import java.applet.Applet;
   import java.awt.Font;
   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import java.text.DecimalFormat;
   
   import javax.swing.JButton;
   import javax.swing.JPanel;
   import javax.swing.JTextField;
   
   /*
    * <applet code="StopWatchApplet" width="250" height="100">StopWatchApplet</applet>
    */
   public class StopWatchApplet extends Applet implements ActionListener, Runnable {
       
       private volatile Thread blinker;
       private JTextField textField;
       private JButton startstopButton, resetButton;
       
       private long start, now, stack;
       
       public void init() {
           setLayout( new GridLayout(2, 1) );
           JPanel panel2 = new JPanel();
           textField = new JTextField( "00.0" );
           textField.setFont( new Font("Dialog", Font.PLAIN, 14) );
           textField.setEditable(false);
           textField.setHorizontalAlignment( JTextField.RIGHT );
           textField.setSize( 50, 30 );
           startstopButton = new JButton( "Start" );
           resetButton = new JButton( "Reset" );
           startstopButton.addActionListener( this );
           resetButton.setEnabled(false);
           resetButton.addActionListener( this );
           panel2.add( startstopButton );
           panel2.add( resetButton );
           add( textField );
           add( panel2 );
       }
   
       public void stop() {
           blinker = null;
       }
       
       public void actionPerformed(ActionEvent ae) {
           if( ae.getActionCommand().equals("Start") ) {
               startstopButton.setText("Stop");
               resetButton.setEnabled(false);
               this.blinker = new Thread(this);
               start = System.currentTimeMillis();
               blinker.start();
           } else if( ae.getActionCommand().equals("Stop") ) {
               startstopButton.setText("Start");
               resetButton.setEnabled(true);
               stop();
               stack += now - start;
           } else if( ae.getActionCommand().equals("Reset") ) {
               resetButton.setEnabled(false);
               textField.setText( "00.0" );
               stack = 0;
           }
       }
   
       public void run() {
           Thread thisThread = Thread.currentThread();
           DecimalFormat df = new DecimalFormat("00");
           StringBuilder builder = new StringBuilder();
           while( blinker == thisThread ) {
               try {
                   Thread.sleep(50);
               } catch( InterruptedException ie ) {}
               synchronized( this ) {
                   if( blinker == thisThread ) {
                       now = System.currentTimeMillis();
                       long erapsed = (now-start+stack)/100;
                       long seisu = erapsed/10;
                       builder.delete(0, builder.length());
                       boolean hasHour = false;
                       if( seisu>=60*60 ) {
                           builder.append( df.format( seisu/3600 ) + ":" );
                           seisu -= (seisu/3600)*3600;
                           hasHour = true;
                       }
                       if( seisu>=60 || hasHour ) {
                           builder.append( df.format( seisu/60 ) + ":" );
                           seisu -= (seisu/60)*60;
                       }
                       builder.append(df.format( seisu ));
                       textField.setText( ""+ builder + "." + erapsed%10 );
                   }
               }
           }
       }
   }
written by iys

CONTENTS

最新の20件

2020-11-14 2005-12-06 2006-11-04 2012-07-15 2009-06-19 2011-03-03 2006-12-13 2007-11-05 2014-07-22 2014-07-19
  • SourcePost_____
2014-07-09 2014-01-14 2012-09-03 2012-03-28

今日の11件

人気の30件

  • counter: 5616
  • today: 1
  • yesterday: 0
  • online: 1