我的JFrame里面有一个按钮。当用户单击框架上的任何位置时,我想检查按钮是否在其之前被按下或单击。
例如,如果用户点击框架而没有先点击按钮,则应该说"按钮未按下"但是如果用户点击按钮然后按下框架上的任何地方,那么它应该按下"按钮"。
我的代码:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test1
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Test 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
frame.add(panel,BorderLayout.NORTH);
final JButton btnRectangle = new JButton("Rectangle");
panel.add(btnRectangle);
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
int x = event.getX() ;
int y = event.getY() ;
System.out.println("you have press the mouse at X : " + x + " and Y : " + y);
if(btnRectangle.getModel().isSelected())
System.out.println("the button is pressed");
else
System.out.println("the button is NOT pressed");
}
public void mouseReleased(MouseEvent event){}
public void mouseClicked(MouseEvent event){}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
}
MousePressListener mListener = new MousePressListener();
frame.addMouseListener(mListener);
frame.setVisible(true);
}
}
正如您所看到的,我试图检查JFrame MousePressed Listener中是否单击了该按钮。但没有成功。我也看看这个问题:
How can I check that JButton is pressed? If the isEnable() is not work?
但似乎无处可去,请帮忙
答案 0 :(得分:0)
已完成以下步骤,
public class Test2
{
static boolean isPressed = false;
public static void main(String[] args)
{
.....
btnRectangle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
isPressed = true;
}
});
.....
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event)
{
if(!isPressed){
System.out.println("the button is NOT pressed");
}else{
System.out.println("the button is pressed");
}
.....
}
}
}
}
见输出,