📄 focuseventdemo.java
字号:
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class FocusEventDemo extends JFrame{ private JTextField jtf1, jtf2; private JLabel label1, label2; public FocusEventDemo() {/* Two JLabels and two JTextFields are created */ jtf1 = new JTextField(20); jtf1.setBorder(BorderFactory.createLineBorder(Color.black)); jtf1.setBackground(Color.lightGray); jtf1.addFocusListener(new FocusHandler()); jtf2 = new JTextField(20); jtf2.setBorder(BorderFactory.createLineBorder(Color.black)); jtf2.setBackground(Color.lightGray); jtf2.addFocusListener(new FocusHandler()); label1 = new JLabel("Line 1"); label1.setForeground(Color.black); label2 = new JLabel("Line 2"); label2.setForeground(Color.black);/* The components are placed on the JFrame using a BoxLayout */ JPanel p1 = new JPanel(); p1.add(label1); p1.add(jtf1); JPanel p2 = new JPanel(); p2.add(label2); p2.add(jtf2); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(p1); panel.add(p2); getContentPane().add(panel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 200); setVisible(true); }/* The FocusListener is implemented as an inner class. Whenever *//* one of the JTextField objects gains keyboard focus, a FocusEvent *//* is generated and sent to the focusGained() method. *//* The background color of the JTextField that generated the event *//* is set to pink. Similarly, if a JTextField loses keyboard *//* focus the focusLost() method is called and the background color *//* is set to light gray. */ class FocusHandler implements FocusListener { public void focusGained(FocusEvent event) { JTextField tf = (JTextField)event.getComponent(); tf.setBackground(Color.pink); } public void focusLost(FocusEvent event) { JTextField tf = (JTextField)event.getComponent(); tf.setBackground(Color.lightGray); } } public static void main(String args[]) { FocusEventDemo demo = new FocusEventDemo(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -