【发布时间】:2015-03-06 22:35:32
【问题描述】:
我想创建一个有两个按钮的 GUI,这样当第一个按钮被点击时,它的颜色会在蓝色和白色之间来回变化,当第二个按钮被点击时,它的颜色会在蓝色和白色之间来回变化黄色和绿色。我希望两个按钮的颜色变化能够同时发生,所以我创建了两个类 Button1 和 Button2,它们都扩展了 Thread 类。但是,我现在遇到一个问题:在 Button1/Button2 类中,您无法访问主类(Gui 类)中的 button1/button2。我希望 Button1/Button2 扩展 Thread 和 Gui,但这是不可能的; Java 不支持多重继承。 “public class Button1 extends Thread, Gui”和“public class Button1 extends Thread extends Gui”都不起作用。我该如何解决这个问题?
这是我的代码:
Gui.java:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Gui implements ActionListener{
private JFrame frame;
private JButton button1;
private JButton button2;
private Button1 buttonone;
private Button2 buttontwo;
public Gui(){
frame = new JFrame("");
frame.setVisible(true);
frame.setSize(500,500);
buttonone = new Button1();
buttontwo = new Button2();
button1 = new JButton("button1");
button2 = new JButton("button2");
button1.addActionListener(this);
button2.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
container.setLayout(new FlowLayout());
container.add(button1);
container.add(button2);
}
public static void main(String[] args){
Gui gui = new Gui();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
buttonone.start();
}
if (e.getSource() == button2) {
buttontwo.start();
}
}
}
Button1.java:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Button1 extends Thread
{
public void run(){
while (true){
button1.setBackground(Color.blue); //here's where the problem is
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
button1.setBackground(Color.white);
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
Button2.java 类似(略)。
【问题讨论】:
-
你的类应该都不扩展。
-
我认为您不了解
extends所做的设计...也许您应该阅读一下 Inheritance 在 java 中的作用 -
切题相关:为什么要在构造函数而不是 main 方法中初始化,为什么要在 Gui 类中创建 Gui 的新实例?
-
@mstbaum:请在上面解释您的评论。我不确定我是否看到了问题。
-
另外,我认为您不了解并行性。按钮不应该是线程。该按钮应该启动一个异步任务。单击按钮时,将异步任务提交到线程池中。按钮单击以及任何其他 GUI 事件都应该发生在单个线程(GUI 线程)上。
标签: java multithreading swing user-interface