mytext1とかmybutton1とかの名前ではプログラムが複雑になると苦しくなってきます。インスタンス名は自由に決められるので、わかりやすく変えてみます。
例えば温度の換算で説明しましょう。華氏温度(℉)と摂氏温度(℃)の換算なのでFを入れるJTextFieldをmytext1でなくて、fahr、Cを入れるところをmytext2でなくてcelsとしました。語源が Fahrenheit と Celsius という人名なのですが、とりあえず1文字目が f か c かでわかります。
ボタンの名前も FからCへの換算をするボタンをf2c、CからFをc2fとしました。FtoCでもいいのですが、2とtoの発音が同じことからくるダジャレです。(forを4と書くのもよくあります)
こうしておくと、f2cボタンだったら、fahrから文字列をgetして、celsにsetするというのが間違いなく書けます。
if (e.getSource() == f2c) { double x; x = Double.parseDouble(fahr.getText()); cels.setText( Double.toString( ( x - 32 ) / 1.8 ) ); }
華氏(F)から摂氏(℃)へ変換。換算式は次の通り。
(華氏温度) = 1.8 * (摂氏温度) + 32
華氏温度は日本では全く使われないのですが、アメリカでは一般的な温度の単位で、日常会話で体温や気温を言うときにはこれを使います。旅行する人は知っておくとよいでしょう。Fで表します。(正しくは℃とおなじく°がつきます)、
もともとドイツのファーレンハイトという人が考えた単位で、氷に塩を混ぜて作られる0℃以下の低温を0F、人間の体温を100Fとしたのが始まりです。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class KanSan3 extends JFrame implements ActionListener{
/* フィールド */
JTextField fahr; //Fahrenheit
JTextField cels; //Celsius
JButton f2c; //F to C
JButton c2f; //C to F
JLabel label;
/* コンストラクタ */
public KanSan3(){
setDefaultCloseOperation(EXIT_ON_CLOSE); //終了処理を追加
fahr = new JTextField(20);
cels = new JTextField(20);
f2c = new JButton("↓");
c2f = new JButton("↑");
label = new JLabel("単位の換算",JLabel.CENTER);
/*タイトル付き枠*/
fahr.setBorder(BorderFactory.createTitledBorder("F"));
cels.setBorder(BorderFactory.createTitledBorder("C"));
/*右寄せ*/
fahr.setHorizontalAlignment(JTextField.RIGHT);
cels.setHorizontalAlignment(JTextField.RIGHT);
/*配置*/
setLayout(new BorderLayout());
add(fahr,BorderLayout.NORTH);
add(cels,BorderLayout.SOUTH);
add(label, BorderLayout.CENTER);
add(f2c,BorderLayout.WEST);
add(c2f,BorderLayout.EAST);
/*イベント監視*/
f2c.addActionListener(this);
c2f.addActionListener(this);
pack();
setVisible(true);
}
/* イベントがあったらここに来る */
public void actionPerformed(ActionEvent e) {
/* F → C */
if (e.getSource() == f2c) {
double x;
x = Double.parseDouble(fahr.getText());
cels.setText( Double.toString( ( x - 32 ) / 1.8 ) );
}
/* C → F */
else if (e.getSource() == c2f) {
double x;
x = Double.parseDouble(cels.getText());
fahr.setText( Double.toString( x * 1.8 + 32 ) );
}
}
/********* main **********/
public static void main(String[] args){
/* フレームを作成(事実上のプログラム実行) */
KanSan3 myframe = new KanSan3();
}
}