おそらく、特定の文字が入力されたときに色を変更してクリックさせたいですかJButton
?JTextArea
JTextField
これが私が作った例です:
が.押されると、ボタンの背景が青に変わります (そしてSPACE、'.' の後に自動挿入するボタン メソッドが呼び出されます)。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Test {
final JFrame frame = new JFrame();
final JTextField jtf = new JTextField(15);
final JButton button = new JButton("SPACE");
public Test() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
insertSpace();
}
});
final Color defaultColor = button.getBackground();
jtf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, true), "period rel");
jtf.getActionMap().put("period rel", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
//button.doClick(); //I dont like this as it makes JBUtton look like its being clicked where as we want a color change
insertSpace();
button.setBackground(defaultColor);
}
});
jtf.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0), "period pressed");
jtf.getActionMap().put("period pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
button.setBackground(Color.CYAN);
}
});
frame.add(jtf, BorderLayout.NORTH);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
private void insertSpace() {
String s = jtf.getText();
jtf.setText(s + " ");
}
}