fixed
用户将苏打水洒在眼镜之间。用户点击三个可用的第一个JButton确定"来自"初始玻璃和用户点击三个可用的第二个JButton决定了"到"目的地玻璃。
如何确定用户点击的特定两个JButton? 每当用户点击三个JButtons中的两个时,我想将与这两个JButton相关联的字符串存储在"来自"和"到"变量。
有没有办法做到这一点?
答案 0 :(得分:1)
制作ActionListener
并使用JButton#addActionListener
将其添加到所有三个按钮。该事件有一个您可以使用的源字段。
ActionListener listener = new ActionListener() {
JButton first;
JButton second;
@Override
public void actionPerformed(ActionEvent e) {
if(first == null)
{
first = (JButton) e.getSource();
}
else
{
second = (JButton) e.getSource();
// do something
// clean up
first = null;
second = null;
}
}
};
glass1.addActionListener(listener);
glass2.addActionListener(listener);
glass3.addActionListener(listener);
处理侦听器内部的逻辑有点脏,但这就是想法。
答案 1 :(得分:0)
firstbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//do something here first button is clicked
}
} );
你可以将监听器添加到这样的按钮中。并使用类变量来跟踪单击按钮的次数。
例如:
public class GUIControl {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
}
});
}
public static void showGUI() {
JFrame frame = new JFrame("MyFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JButton glass1 = new JButton("glass1");
JButton glass2 = new JButton("glass2");
JButton glass3 = new JButton("glass3");
String from = "";
String to = "";
int click_count = 0;
glass1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
glass3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(click_count ==0)
{
from = "glassX";
click_count = 1;
}else if(click_count ==1)
{
from = "glassY";
click_count = 0;
}
}
} );
frame.getContentPane().add(glass1);
frame.getContentPane().add(glass2);
frame.getContentPane().add(glass3);
frame.pack();
frame.setVisible(true);
// I want to store the first two clicks in these variables
}