JTextFieldなどのテキスト表示コンポーネントにショートカットキーをつけるためには、setFocusAccelerator()を使います。
下の例の場合は、ALT + D でURL入力部分にカーソルが移動します。
(例)
JTextField urlTextField = new JTextField();
urlTextField.setFocusAccelerator('d');
JEditorPaneを使用することにより、HTML文書の表示が可能になります。 HTMLを表示するためには、setEditable(false); としてJEditorPane上でのテキストの編集を不可能にする必要があります。 JEditorPaneのインスタンスの設定をした後、setPage(String url)メソッドを呼ぶことにより、Web上のHTMLを読むことができます。
(例)
JEditorPane htmlPane = new JEditorPane();
htmlPane.setEditable(false);
htmlPane.setContentType("text/html");
htmlPane.setPage("http://www.yahoo.co.jp");
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/*
* Sample5.java
* 2003/12/13
* Kota
*/
/**
* @author Kota
*/
public class Sample5 extends JFrame {
private JTextField urlTextField;
private JButton moveButton;
private JEditorPane htmlPane;
public static void main(String[] args) {
JFrame frame = new Sample5();
frame.setVisible(true);
}
public Sample5() {
super("Sample5");
changeLookAndFeel();
JLabel label = new JLabel("アドレス(D):");
urlTextField = new JTextField();
urlTextField.setFocusAccelerator('d');
urlTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setPage();
}
});
moveButton = new JButton("移動(M)");
moveButton.setMnemonic('m');
moveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setPage();
}
});
htmlPane = new JEditorPane();
htmlPane.setEditable(false);
htmlPane.setContentType("text/html");
Container container = getContentPane();
container.setLayout(new BorderLayout());
JPanel northPanel = new JPanel(new BorderLayout());
northPanel.add(label, BorderLayout.WEST);
northPanel.add(urlTextField, BorderLayout.CENTER);
northPanel.add(moveButton, BorderLayout.EAST);
JScrollPane scroll = new JScrollPane(htmlPane);
scroll.setPreferredSize(new Dimension(400, 400));
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
container.add(northPanel, BorderLayout.NORTH);
container.add(scroll, BorderLayout.CENTER);
pack();
setCenterLocation(this);
}
/**
* JTextFieldに記述されたURLをJEditorPaneに表示する。
*/
private void setPage() {
String url = urlTextField.getText().trim();
if (url.length() > 0) {
try {
htmlPane.setPage(url);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "読み込みエラーが発生しました。", "読み込みエラー", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Look & Feel をOSのものに変更
*/
private void changeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ウィンドウをディスプレイの中心に配置する。
* @param frame ウィンドウ
*/
private void setCenterLocation(JFrame frame) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - frame.getWidth()) / 2;
int y = (d.height - frame.getHeight()) / 2;
frame.setLocation(x, y);
}
}
SITE TOP BGM : Harvard - Lesson