単純なプログラムを書換えよう(Java編)−オリジナルソース
題名の通りの企画です.書き換える元になるソースは以下の二つ(View.java,Main.java)です.
元のソースに悪い点があるために書き換えるのではありません.良し悪しではなく「別の書き方を模索してみるだけ」という意図です.したがって,書き換える前よりも書き換えた後の方が優れているわけでもありません.念のため.
また,Java編以外ができるかどうかは未定です.
//View.java import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; public class View extends WindowAdapter implements ActionListener{ private Label value=new Label("0"); public View(){ Frame frame=new Frame(); Panel buttons=new Panel(); Button inc=new Button("inc"); Button dec=new Button("dec"); buttons.add(inc); buttons.add(dec); inc.addActionListener(this); dec.addActionListener(this); frame.add(buttons,BorderLayout.SOUTH); frame.add(value,BorderLayout.CENTER); frame.addWindowListener(this); frame.pack(); frame.show(); } public void actionPerformed(ActionEvent actionEvent){ if(actionEvent.getActionCommand()=="inc"){ value.setText(Integer.toString(Integer.parseInt(value.getText())+1)); } else{ value.setText(Integer.toString(Integer.parseInt(value.getText())-1)); } } public void windowClosing(WindowEvent windowEvent){ System.exit(0); } } //end //Main.java public class Main{ public static void main(String[] args){ View view=new View(); } } //end
この二つのソースをコンパイルして
javac Main.java View.java
動かすと
java Main
こんな画面を表示します.
incボタンを押すと表示している数値を一づつ加算,decボタンで一づつ減算します.