我正在创建一个Swing应用程序。我创建了一个名为Drone
的类,并在另一个名为UserAccount
的类中创建了它的对象。在JButton
我使用userAccount
调用Drone类的getter但没有执行任何操作。为什么会这样?
这是Drone类的代码
private int x;
private int y;
private String text;
private int a;
private int b;
private String text1;
private int c;
private int d;
private String text2;
public Drone() {
x= 10;
y=150;
a=10;
b=150;
c=1000;
d=150;
text="Drone";
text1="Factory";
text2="Hospital";
setSize(1070,300);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, 1070, 300);
g.setColor(Color.BLACK);
g.drawString(text, x, y);
System.out.println(x + "" + y);
g.drawString(text1, a, b);
g.drawString(text2, c, d);
}
public void factory() throws InterruptedException{
while(true){
while(a<=getWidth()){
b=getHeight()/2;
repaint();
Thread.sleep(1000000);
}
}
}
public void Hospital() throws InterruptedException{
while(true){
while(c<=getWidth()){
d=getHeight()/2;
repaint();
Thread.sleep(1000000);
}
}
}
public void start() throws InterruptedException{
while(true){
while(x <= getWidth()-50){
x++;
y = getHeight()/2;
repaint();
Thread.sleep(150);
}
while(x >= 0){
x--;
y = getHeight()/2;
repaint();
Thread.sleep(150);
}
break;
}
}
public static void main(String[] args) throws InterruptedException{
JFrame frame = new JFrame("Drone Movement");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Drone drone = new Drone();
frame.getContentPane().add(drone);
frame.setSize(1070,300);
frame.setLocation(180,200);
frame.setVisible(true);
drone.start();
drone.factory();
drone.Hospital();
}
我在actionPerformed
JButton
JPanel
致电此课程
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
userAccount.getDrone();
}
为什么这里没有采取任何行动?
答案 0 :(得分:0)
我认为你缺少添加动作监听器。
在Drone类中,创建的JButton应该具有类似
的内容JButton button = new JButton("button");
button.addActionListener(this);
Drone实现ActionListener。
但根据你所说的,JButton有actionPerformed我假设你正在扩展JButton来实现ActionListener并实现了actionPerformed方法,那么代码应该是
public class MyButton extends JButton implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
//TODO implement your action here
}
然后在您的无人机中,您应该有类似
的内容MyButton button = new MyButton();
button.addActionListener(button); // the button itself instead of the this