高手支招 java FocusListener焦点事件如何实现在两个JTextField中确认焦点!
发布网友
发布时间:2022-07-05 00:13
我来回答
共2个回答
热心网友
时间:2023-11-28 18:47
刚才写了个程序,楼主看看符合要求不
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
class TestFocus extends JFrame implements FocusListener {
JButton btn;
JTextArea text1,text2;
boolean b=true;
public TestFocus() {
btn=new JButton("切换焦点");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b) {
//text2.setRequetFocusEnabled(fasle);
text1.grabFocus();
b=false;
}
else{
text2.grabFocus();
b=true;
}
}
});
JPanel p1=new JPanel(new FlowLayout());
p1.add(Box.createGlue());
p1.add(btn);
p1.add(Box.createGlue());
JPanel p2=new JPanel(new FlowLayout());
text1=new JTextArea();
text2=new JTextArea();
p2.add(create(text1,"第一个文本域"));
p2.add(create(text2,"第二个文本域"));
text1.addFocusListener(this);
text2.addFocusListener(this);
getContentPane().add(p1,"North");
getContentPane().add(p2,"Center");
setVisible(true);
setSize(200,200);
}
public static void main(String [] args) {
new TestFocus();
}
public JScrollPane create(JTextArea text,String s) {
text.setLineWrap(true);
JScrollPane jsp=new JScrollPane(text);
Border border=BorderFactory.createLineBorder(Color.blue);
jsp.setBorder(BorderFactory.createTitledBorder(border,s,TitledBorder.LEFT,TitledBorder.TOP));
return jsp;
}
public void focusGained(FocusEvent e) {
JTextArea text=(JTextArea)e.getSource();
if(text==text1) {
text1.setText("");
text1.setText("获得焦点");
}
if(text==text2) {
text2.setText("");
text2.setText("获得焦点");
}
}
public void focusLost(FocusEvent e) {
JTextArea text=(JTextArea)e.getSource();
if(text==text1) {
text1.setText("");
text1.setText("失去焦点");
}
if(text==text2) {
text2.setText("");
text2.setText("失去焦点");
}
}
}
热心网友
时间:2023-11-28 18:48
我也不太清楚,向回答者学习!