我有一个自定义组件(其中extends JPanel
)。
它看起来像这样:
我的问题是:当我在另一个中使用它时JFrame
,我如何添加一个ActionListener
,以便当我单击任何按钮时它会执行代码actionPerformed
?
我尝试添加一个MouseListener
,但它没有工作。
编辑:对不起,我对组件不是很清楚:它由两个JButtons
(“-”和“+”)和一个JTextField
. 当用户点击其中任何一个时,中间的数字会增加或减少。所有这 3 个组件都放在一个JPanel
.
编辑2:这是源代码:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
@SuppressWarnings("serial")
public class ZoomSelector extends JPanel {
protected JButton btnDecrement;
protected JTextField txtNumber;
protected JButton btnIncrement;
private String currentValue, previousValue;
public ZoomSelector() {
setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
initGUI();
txtNumber.setText("12");
currentValue = "12";
setSize(new Dimension(125, 26));
validate();
}
public boolean hasChanged() {
if(currentValue.equals(previousValue)) {
return true;
}
else {
return false;
}
}
public String getText() {
return txtNumber.getText();
}
public void reset() {
previousValue = txtNumber.getText();
txtNumber.setText("12");
currentValue = "12";
}
@Override
public void setEnabled(boolean e) {
btnDecrement.setEnabled(e);
txtNumber.setEnabled(e);
btnIncrement.setEnabled(e);
}
public void increment() {
previousValue = txtNumber.getText();
int number = Integer.parseInt(txtNumber.getText());
if(number < 20) {
number++;
txtNumber.setText("" + number);
currentValue = "" + number;
}
}
public void decrement() {
previousValue = txtNumber.getText();
int number = Integer.parseInt(txtNumber.getText());
if(number > 0) {
number--;
txtNumber.setText("" + number);
currentValue = "" + number;
}
}
private void initGUI() {
btnDecrement = new JButton("-");
btnDecrement.setFont(new Font("Tahoma", Font.BOLD, 14));
btnDecrement.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
decrement();
}
});
setLayout(new BorderLayout(0, 0));
add(btnDecrement, BorderLayout.WEST);
txtNumber = new JTextField();
txtNumber.setHorizontalAlignment(SwingConstants.CENTER);
txtNumber.setText("0");
txtNumber.setEditable(false);
add(txtNumber, BorderLayout.CENTER);
txtNumber.setColumns(2);
btnIncrement = new JButton("+");
btnIncrement.setFont(new Font("Tahoma", Font.BOLD, 14));
btnIncrement.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
increment();
}
});
add(btnIncrement, BorderLayout.EAST);
}
}