I have been coding for about 3 months now, (I've never had any programming experience) and I ran into a bit of an issue. I'm working on an idle clicking game, but I can't seem to access textArea
.
I need to update textArea
from outside its class since I am multi-threading and need separate run()
methods.
class AddOne extends Thread {
public static int money = 0;
public static boolean flag = false;
public void run() {
try {
money++;
System.out.println(money);
//update textArea with new money value
}
catch(Exception e){
System.out.println("The exceptions are: " + e);
}
}
}
class AddOnePerSec extends Thread {
public void run() {
try {
if(AddOne.flag == false)
{
for(int i = 0; i<=100; i++)
{
AddOne.flag = true;
AddOne.money++;
Thread.sleep(1000);
//update textArea with new money value
}
AddOne.flag = false;
}
else {System.out.println("Please wait...");}
}
catch(Exception e){
System.out.println("The exceptions are: " + e);
}
}
}
public class ClickGame {
private static JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddOne.flag = false;
ClickGame window = new ClickGame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ClickGame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public static void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JButton btnAdd = new JButton("Add 1");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddOne add = new AddOne();
add.start();
}
});
frame.getContentPane().add(btnAdd, BorderLayout.WEST);
JButton btnAddEvery = new JButton("Add 1 every second for 100 seconds");
btnAddEvery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddOnePerSec persec = new AddOnePerSec();
persec.start();
}
});
frame.getContentPane().add(btnAddEvery, BorderLayout.EAST);
JTextArea textArea = new JTextArea();
frame.getContentPane().add(textArea, BorderLayout.CENTER);
}
}
Ideally, the textArea will be updated with the new money variable every time money is changed in each thread.