如果我第一次按下按钮,它将输出按摩对话框"屏幕已保存" 如果我在按钮上按下其他次数,它将输出按摩对话框"屏幕保存在 desctop 上"。我只是不知道该怎么做。我尝试使用标签,如果结构,但它仍然不起作用,请帮助我。
screenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedImage image = new BufferedImage(
window.getWidth(),
window.getHeight(),
BufferedImage.TYPE_INT_RGB
);
window.paint( image.getGraphics() );
try {
File temp = File.createTempFile("screenshot", ".png");
ImageIO.write(image, "png",new File(getDir(),"screen.png"));
} catch (IOException ioe) {
System.out.println(" ");
}
if (showDialog==false){
JOptionPane.showMessageDialog(screenButton, "Screen saved");
}
}
});
if (showDialog) {
screenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(screenButton,"Screen saved on a desctop");
showDialog=true;
}
});
}
不要尝试将两个 ActionListener 添加到同一个按钮。
逻辑应自包含在单个ActionListener
中。然后,使用Boolean
变量来确定要执行的进程。
像这样:
JButton button = new JButton("Click Me");
button.addActionListener( new ActionListener()
{
private boolean firstTime = true;
@Override
public void actionPerformed(ActionEvent e)
{
if (firstTime)
{
System.out.println( "First Message" );
firstTime = false;
}
else
System.out.println( "Another Message" );
}
});
我看不出你在哪里声明了你的布尔showDialog
,但我会尝试解释解决你的问题的基本原理。
boolean showDialog = false;
if(!showDialog) {
//Show the first dialog
showDialog = true;
}
if(showDialog){
//show the second dialog
showDialog = false;
}
您的问题是,您忘记更改showDialog
的值。
if (showDialog==false){
JOptionPane.showMessageDialog(screenButton, "Screen saved");
showDialog = true; //You forgot this line
}
因为在第一个if
之后,showDialog
布尔值仍然false
并且只有在showDialog
为真的情况下才能到达您的第二个if
。