java tooltip显示"/>
java tooltip显示
我来支一招。
以下demo在JB8中已运行通过。功能:当在JTextField中输入是tool时显示ToolTip,内容为JTextField 中内容。若输入tool后继续输入或者内容不是tool,则立即不显示Tooltip。
说明:
我个人感到这个需求是一个“病”需求,(因为不用ToolTip,用其它方案会更好,不知为什么一定要紧抓ToolTip来做。)故这个demo虽能达到功能,却也是一个“病”方案。程序也就不优化了。抛砖引玉吧。(用JB8写的,有多余代码,也就不删了,一笑了知吧。)
package untitled2;
import javax.swing.UIManager;
import java.awt.*;
public class Application1 {
public Application1() {
Frame1 frame = new Frame1();
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
//Main method
public static void main(String[] args) {
new Application1();
}
}
package untitled2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class Frame1 extends JFrame {
JPanel contentPane;
JTextField jTextField1 = new JTextField();
BorderLayout borderLayout1 = new BorderLayout();
//Construct the frame
public Frame1() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
//Component initialization
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(400, 300));
this.setTitle("Frame Title");
jTextField1.setToolTipText("NO TOOLTIPS");
jTextField1.setSelectionStart(0);
jTextField1.setText("");
jTextField1.setDocument(new mydt(jTextField1)) ;
contentPane.add(jTextField1, BorderLayout.NORTH);
}
//Overridden so we can exit when window is closed
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent
;
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
}
class mydt extends PlainDocument
{
private JTextComponent tc;
private String cc;
private int flag=0;
public mydt (JTextComponent c){tc=c;}
public void insertString(int offs, String str, AttributeSet a) throws javax.swing.text.BadLocationException {
/**@todo Override this javax.swing.text.PlainDocument method*/
super.insertString(offs, str, a);
cc=this.getText(0,this.getLength() );
ToolTipManager.sharedInstance().setDismissDelay(1000) ;
ToolTipManager.sharedInstance().setInitialDelay(10) ;
if(ccpareTo("tool")!=0 )
{
try{
Robot rt=new Robot();
//rt.mousePress(InputEvent.BUTTON3_MASK ) ;
if(flag==1){ flag=0;
rt.mouseMove(400,400) ;
// rt.mousePress(InputEvent.BUTTON1_MASK ) ;
}
}catch(Exception e1){System.out .print(e1) ;}
}
else {
tc.setToolTipText(cc) ;
flag=1;
try{
Robot rt=new Robot();
rt.mouseMove(tc.getLocationOnScreen() .x+12,
tc.getLocationOnScreen() .y+4) ;
// rt.mousePress(InputEvent.BUTTON1_MASK ) ;
}catch(Exception e1){System.out .print(e1) ;}
}
}
}
更多推荐
java tooltip显示
发布评论