|
右上のボタンを押すと、左上のテキストフィールドの文字列を下のテキストフィールドに表示する。 |
プログラムを実行中のOSのLook&Feelのクラス名を得るためには、javax.swing.UIManager クラスの getSystemLookAndFeelClassName メソッドを使います。このメソッドによって得たクラス名を、setLookAndFeel メソッドを使って設定します。
(例)
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
java.awt.Toolkit クラスの getScreenSize メソッドを使います。戻り値は Dimention です。
(例)
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
TextField、JTextField の addActionListener を呼びます。
(例)
inputTextField.addActionListener(this);
Swing の部品にショートカットキーを付けるには、setMnemonic メソッドを呼びます。
(例)
JButton button = new JButton("output");
button.setMnemonic('o');
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* Sample1.java
* 2003/06/29
* kota
*/
/**
* @author kota
*/
public class Sample1 extends JFrame implements ActionListener {
private JButton button;
private JTextField inputTextField;
private JTextField outputTextField;
public static void main(String[] args) {
// ウィンドウの作成
Sample1 sample1 = new Sample1("Sample1");
// ウィンドウを閉じたら終了
sample1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ウィンドウの位置を設定
sample1.setLocation(sample1.getCenterLocation(sample1));
// ウィンドウを表示
sample1.setVisible(true);
}
public Sample1(String title) {
// タイトルの表示
super(title);
// Look & Feel の変更
changeLookAndFeel();
Container container = getContentPane();
// outputボタン
button = new JButton("output");
button.addActionListener(this);
button.setMnemonic('o');
// 入力用テキストフィールド
inputTextField = new JTextField("input");
inputTextField.addActionListener(this);
// 出力用テキストフィールド
outputTextField = new JTextField("output");
outputTextField.setEnabled(false);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(inputTextField);
panel.add(button);
container.setLayout(new GridLayout(2, 1));
container.add(panel);
container.add(outputTextField);
// ウィンドウのサイズの決定
pack();
}
/**
* ウィンドウをディスプレイの中心に配置するための点を取得する。
* @param frame ウィンドウ
* @return ウィンドウの左上隅の点
*/
public Point getCenterLocation(JFrame frame) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - frame.getWidth()) / 2;
int y = (d.height - frame.getHeight()) / 2;
return new Point(x, y);
}
/*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
String text = inputTextField.getText();
inputTextField.setText("");
outputTextField.setText(text);
}
/**
* Look & Feel をOSのものに変更
*/
private void changeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
SITE TOP BGM : BECK - ODELAY