在JavaScript中,我输入了一个打开Paint JFrame的代码。我制作了一个单独的JFrame来改变颜色。按钮显示“更改颜色”,我打算编写一个代码,单击时会转到下一个颜色。但是,我不知道如何进行按键检测。这是我的代码:
import javax.swing.*;
public class PaintApp extends javax.swing.JFrame {
public static void main(String[] args) {
JFrame main=new JFrame("Tessellating Pi - Paint");
PaintInterface pi=new PaintInterface();
main.add(pi);
main.setSize(1000,1000);
main.setVisible(true);
JFrame j=new JFrame("Colour Chooser");
JButton c=new JButton("Change Colour");
j.add(c);
j.setSize(150,100);
j.setVisible(true);
}
}
答案 0 :(得分:1)
要检测按钮是否被按下,请执行以下操作:
JButton c = new JButton("Change Colour");
c.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//This is where you can write the code to change colour.
}
});
所以基本上是动作监听器"听"如果已单击该按钮。如果有,它将执行以下功能。
答案 1 :(得分:0)
您必须像这个示例一样添加一个Listener并实现函数actionPerformed
:
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});