1

In JavaScript, I entered a code which opens a Paint JFrame. I made a separate JFrame to change the colour. The button says 'Change Colour' which I plan to write a code which goes to the next colour when clicked. However, I do not know how to make a keypress detection. This is my code:

    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);
        }
    }
user3507600
  • 1,075
  • 9
  • 15
TessellatingPi
  • 105
  • 1
  • 2
  • 6
  • It's java, not javascript. – cy3er Jun 10 '14 at 15:30
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 2) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Jun 11 '14 at 01:14

2 Answers2

2

To detect if a button has been pressed you do the following:

          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.
            }

         });

So basically the action listener "listens" if the button has been clicked. If it has it will then execute the following function.

selena
  • 151
  • 13
1

You have to add a Listner like this example and implement the function actionPerformed:

c.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                System.out.println("You clicked the button");
            }
        });      
Jens
  • 67,715
  • 15
  • 98
  • 113