繁体   English   中英

Java | 两个JButton中的ActionListeners,无响应

[英]Java | ActionListeners in two JButtons, no response

我已经坚持了几天(第一次使用多个ActionListener ,所以请ActionListener包涵)。

我有两个按钮,每个按钮都有一个动作侦听器,用于将图形向左或向右移动。

然而,要么动作听者似乎工作不正常,要么执行的动作不起作用。

我们非常感谢您的建议,我已经尝试过将其切换为Action如本论坛其他地方所建议的那样,但这也没有解决。

package h03verplaatsbarebal;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Paneel extends JPanel implements ActionListener{

//declare objects
private JButton knopLinks; // moves ball to left
private JButton knopRechts; // moves ball to right

//constants
private int horizontalePlaats; // variabele voor horizontale plaats
private int VERPLAATSING; // constante voor verplaatsing

/*create panel with 2 buttons (to left, to right) and a ball*/
public Paneel() {
    //create objects
    knopLinks = new JButton ("Naar links");
    knopLinks.addActionListener(this);
    knopRechts = new JButton ("Naar rechts");
    knopRechts.addActionListener(this);

    //Tooltips
    knopLinks.setToolTipText("Klik hier om de bal naar links te bewegen");
    knopRechts.setToolTipText("Klik hier om de bal naar rechts te bewegen");

    //add to window
    add(knopLinks);
    add(knopRechts);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    int midden = getWidth() / 2; // halfway screen
    int balDiameter = 50;
    int ovaalDiameter = 25;
    horizontalePlaats = midden;

    //draw line
    g.setColor(Color.GREEN);
    g.drawLine(30, getHeight() - 30, getWidth() -30, getHeight() - 30); //lijn
    //draw ball
    g.setColor(Color.ORANGE);
    g.fillOval(horizontalePlaats - balDiameter, getHeight() - 130, 100, 100); // oranje bal
    g.setColor(Color.BLACK);
    g.drawOval(horizontalePlaats - balDiameter, getHeight() - 130, 100, 100); //lijn van bal
    g.setColor(Color.BLACK);
    g.drawOval(horizontalePlaats - ovaalDiameter, getHeight() - 130, 50, 100); // binnen lijnen
}

/*clicking buttons*/
public void actionPerformed(ActionEvent e) {
    VERPLAATSING = 15;
      if (e.getSource() == knopLinks){ //move to left
          horizontalePlaats = horizontalePlaats - VERPLAATSING;
      } 
      else { //move to right
          horizontalePlaats = horizontalePlaats + VERPLAATSING;
      }

    repaint(); // paint again
}
}

您的动作侦听器应该可以工作,但是它只修改了horizontalePlaats的值。

问题在于horizontalePlaatspaintComponentmidden值覆盖,因此您永远看不到所执行操作的结果。

horizontalePlaats = midden;

您将覆盖涂料中的horizo​​ntalePlaats。

int midden = getWidth() / 2; // halfway screen
int balDiameter = 50;
int ovaalDiameter = 25;
horizontalePlaats = midden;

我认为您的动作侦听器很好,但是您只需要在中间初始化horizo​​ntalePlaats即可。

你可以移动这个

int midden = getWidth() / 2; // halfway screen
horizontalePlaats = midden;

到您的Paneel构造函数。

暂无
暂无

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

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