简体   繁体   English

单击Java swing中的按钮,使用新名称创建具有新名称的类的新对象

[英]Creating a new object of a class with a new name on clicking a button in java swing

I want to start a new thread with a new object name , of a specific class whenever I click a button in java Swing application. 每当我单击Java Swing应用程序中的按钮时,我都想使用特定类的新对象名启动一个新线程。 For example 例如

Thread t1 = new MyClass();
t1.start();

Thread t2 = new MyClass();
t2.start();

Thread t3 = new MyClass();
t3.start();
...

so on... 等等...

How can I achieve this? 我该如何实现?

I think you should use a ArrayList<E> for this. 我认为您应该为此使用ArrayList<E> First lets create one: 首先让我们创建一个:

ArrayList<Thread> threads = new ArrayList<> ();

Now you have an empty ArrayList of threads. 现在,您有一个空的线程ArrayList When you want to add a new thread, use the add method. 当您要添加新线程时,请使用add方法。

Thread t = new MyClass();
threads.add(t); //Use the array list declared above ^^^^
t.start();

And if you want to get the thread, use the get method. 如果要获取线程,请使用get方法。 For example, 例如,

Thread theFirstThread = threads.get(0);

You probably should declare the array list in the class, not in the method so that a new array list would not be created every time you call the method. 您可能应该在类中而不是在方法中声明数组列表,这样就不会在每次调用该方法时创建新的数组列表。

I know you actually want to create a thread with a different name. 我知道您实际上想要创建一个具有不同名称的线程。 It might be possible with reflection (or not) but I think an ArrayList is more suitable. 反射(或不反射) 可能是可行的,但我认为ArrayList更合适。

EDIT: 编辑:

As MadProgrammer has suggested, a HashMap works as well. 正如MadProgrammer所建议的那样, HashMap可以工作。 Let me show you how to implement a map. 让我向您展示如何实现地图。 First, you create the thing: 首先,创建事物:

HashMap<String, Thread> threadsMap = new HashMap<> ();

To add stuff to the map you need a key, which is a string. 要将内容添加到地图,您需要一个密钥,它是一个字符串。 You can use a counter or something to know the number and append the number to something like "t" or "thread". 您可以使用计数器或其他东西来知道数字,并将数字附加到诸如“ t”或“ thread”之类的东西上。 And then you can add the key (the string) and the value (the thread) to the hash map. 然后,您可以将键(字符串)和值(线程)添加到哈希映射。

threadsMap.put (key, new MyClass()); //key is the string that I mentioned.

And you get the thread by its corresponding key. 然后通过相应的键获取线程。 In this example, I get the first thread: 在这个例子中,我得到了第一个线程:

threadsMap.get("thread1"); //the string is the string you pass in when you add the first thread.

Now the adventage of this method is that you are not limited to numbers as key to get the threads. 现在,此方法的出现是,您不仅可以将数字作为获取线程的关键。 You can use any valid string. 您可以使用任何有效的字符串。 This can increase readability. 这样可以提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM