[英]Changing colour of first JButton until second one has been clicked
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 的顏色變回原始顏色。
無論如何,我當前的實現是否可以做到這一點?
要保留您當前的實現,請嘗試這樣的操作
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.