[英]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
的值。
問題在於horizontalePlaats
被paintComponent
的midden
值覆蓋,因此您永遠看不到所執行操作的結果。
horizontalePlaats = midden;
您將覆蓋塗料中的horizontalePlaats。
int midden = getWidth() / 2; // halfway screen
int balDiameter = 50;
int ovaalDiameter = 25;
horizontalePlaats = midden;
我認為您的動作偵聽器很好,但是您只需要在中間初始化horizontalePlaats即可。
你可以移動這個
int midden = getWidth() / 2; // halfway screen
horizontalePlaats = midden;
到您的Paneel構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.