改变第一个JButton的颜色直到第二个被点击
问题描述:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonsActionListener implements ActionListener {
private JButton firstButton;
private JButton secondButton;
@Override
public void actionPerformed(ActionEvent e) {
if (firstClick == null) {
firstClick = (JButton) e.getSource();
} else {
secondClick = (JButton) e.getSource();
// Do something
firstClick = null;
secondClick = null;
}
}
}
这个类记录用户点击过的前两个JButton。 firstButton代表用户点击的第一个按钮,secondButton代表用户点击的第二个按钮。改变第一个JButton的颜色直到第二个被点击
我希望当用户点击第一个JButton时,它的颜色应该变成红色,直到第二个JButton被点击。一旦点击了第二个JButton,我想让第一个JButton的颜色变回原来的颜色。
有没有办法与我目前的实施做到这一点?
答
保留当前的实现,尝试这样
class ButtonsActionListener implements ActionListener {
private JButton firstButton;
private JButton secondButton;
@Override
public void actionPerformed(ActionEvent e) {
if (firstButton == null) {
firstButton = (JButton) e.getSource();
firstButton.setBackground(Color.RED);
} else {
if (firstButton == (JButton) e.getSource()) {
firstButton.setBackground(Color.RED);
} else {
secondButton = (JButton) e.getSource();
firstButton.setBackground(null);// reset to original color
}
}
}
}
答
单击第二个按钮后,您可以将背景颜色设置为默认值。最初当单击第一个按钮时,如果单击第二个按钮,则颜色将变为红色,第一个按钮颜色将变回默认颜色。
public static void main(String[] args) {
final JButton button = new JButton("Click me");
final JButton button2 = new JButton("Add");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
button.setBackground(Color.RED);
}
});
button2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
button.setBackground(null);
}
});
}
答
要确定哪个按钮被点击,并作出相应的反应,你可以这样做:
class ButtonsActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (((JButton) e.getSource()) == firstButton) {
firstButtonClicked();
} else if (((JButton) e.getSource()) == secondButton) {
secondButtonClicked();
}
}
private void firstButtonClicked(){
System.out.println("1st button clicked ");
//handle second button color
}
private void secondButtonClicked(){
System.out.println("2nd button clicked ");
//handle second button color
}
}
东西应该设定firstButton和secondButton后null? –
@JackKong这取决于你的要求,你需要在改变颜色后清除按钮引用? – aKilleR
当我得到第一个和第二个按钮后,我需要调用一个移动函数,该函数根据哪个按钮被点击了一些东西。 –