Yadagiri Reddy

Yadagiri Reddy

  • NA
  • 3.3k
  • 1m

how to work with two jbuttons in jswings

Sep 19 2016 6:54 AM

I have two JButtons in a JFrame.

i want to execute some code when i click on first button. this code has to run till i click on second button.but here when i click on first button next i'm not able to click second button bcz the focus is on first button only.

below is my code.

when i click on start it starts printing "hello", i want to stop this only when i click on stop button.

import java.awt.Dimension;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class UI implements ActionListener {

public JFrame frame;

public JButton startBtn,stopBtn;

static boolean quit=false;

public UI() {

frame=new JFrame("Screen Shot");

frame.setPreferredSize(new Dimension(200, 200));

frame.setLocation(200, 200);

JPanel panel = new JPanel();

panel.setLayout(null);

startBtn=new JButton("Start");

startBtn.setBounds(40, 40, 100, 30);

panel.add(startBtn);

stopBtn=new JButton("Stop");

stopBtn.setBounds(40, 80, 100, 30);

panel.add(stopBtn);

startBtn.addActionListener(this);

stopBtn.addActionListener(this);

frame.add(panel);

frame.pack();

frame.setResizable(false);

frame.setVisible(true);

}

public static void main(String[] args) {

new UI();

}

@Override

public void actionPerformed(ActionEvent e) {

if(e.getSource()==startBtn)

{

System.out.println("hello");

Thread t1=new Thread(new PrintIt());

t1.start();

while(true){

if(quit==true)

break;

System.out.println("hello");

}

}

else if(e.getSource()==stopBtn)

{

quit=true;

}

}

}


Answers (1)