比如一个按钮,不用鼠标点按钮就能能过代码看到按钮被按下(当然以后就是监听器处理了)。注意:不要直接调用actionPerformed方法,那样达不到效果。最好能给出一段代码,谢谢各位老师
解决方案 »
- 关于ArrayList和数组的疑惑,求解答。
- 怎么让Integer.parseInt得到我想要的值呢
- tableViewer显示数据时table的列宽自动改变
- 如何实现鼠标停留到某Component上时,出现一个类似批注或注释框?
- java中如何侦听键盘输入事件同是侦听鼠标移动事件的??
- 使用iText转换html2pdf中的中文问题!
- 这是什么错误啊?
- 请问后缀名为clw的文件要用什么程序打开
- jbuilder访问sqlserver的简单问题,高分了!!!!!!!
- 我是Java的初学者,还请各位大侠给介绍几本好书!再次多谢了!
- 最近学习JAVA,新写的简单图书馆运行时出现的问题
- 菜菜菜菜鸟求助关于线程的问题
JButton jb = new JButton();
jb.doClick();
不知道这是不是你想要的
不知道Button有没有doClick()方法呢?我看下
Robot 中是有mousePress、mouseRelease方法,但这样好像不能出发某个具体的Button的事件吧???不确定,等待中知道的人解答
先使用 mouseMove 移动到 Button 所在的 坐标,然后模拟点击
但是问题有两个:
1.虽然背景确实改变了,但是没有看按钮被按下的直观效果,好象代码只是后台运行了。
2.如果把下面程序中注释掉的代码启用,则只看到最后一个按钮起作用了,即只看到背景被设为了蓝色,没看到红色和绿色的背景。请高手们看下该如何解决这两个问题?
import java.awt.*;
import java.awt.event.*;public class MyTestRobot extends Frame implements ActionListener {
Button btnStart,btnRed,btnGreen,btnBlue;
public MyTestRobot()
{
setTitle("用代码模仿点击按钮");
setSize(450,300);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent wevent){
System.exit(0);
}
});
setLayout(new FlowLayout());
btnStart=new Button("开始模仿");
btnRed=new Button("红色");
btnGreen=new Button("绿色");
btnBlue=new Button("蓝色");
btnStart.addActionListener(this);
btnRed.addActionListener(this);
btnGreen.addActionListener(this);
btnBlue.addActionListener(this);
add(btnStart);
add(btnRed);
add(btnGreen);
add(btnBlue); } public void actionPerformed(ActionEvent e){
if(e.getSource()==btnStart)
simulate();
else if(e.getSource()==btnRed)
setBackground(Color.red);
else if(e.getSource()==btnGreen)
setBackground(Color.green);
else if(e.getSource()==btnBlue)
setBackground(Color.blue);
}
private void simulate(){
int x,y;
Robot rob;
try{
//红色按钮
x=btnRed.getX();
y=btnRed.getY();
rob=new Robot();
rob.mouseMove(x+10, y+10);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(1000);
/*以下是注释掉的代码
//绿色按钮
x=btnGreen.getX();
y=btnGreen.getY();
rob.mouseMove(x+10, y+10);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(1000);
//蓝色按钮
x=btnBlue.getX();
y=btnBlue.getY();
rob.mouseMove(x+10, y+10);
rob.mousePress(InputEvent.BUTTON1_MASK);
rob.mouseRelease(InputEvent.BUTTON1_MASK);
注释到此结束*/
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[])
{
MyTestRobot frm=new MyTestRobot();
frm.setVisible(true);
}
}
robo.mouseMove(currentPosition.x + 10,currentPosition.y + 10);
无非就是一个点下和一个释放的效果。button周围的,阴影部分绘制一遍就行了。