我有一個名爲Screen的類,其中包含actionPerformed方法。 我想爲不同的菜單項目提供不同的結果:隨機,積極和人性化。如何使用我的actionPerformed方法的結果來實現主要方法 - java
這一成果影響的主要方法,但我不能確定如何把兩者聯繫起來...
public class Screen extends JFrame
implements ActionListener {
ActionListener listener;
JMenuItem random = new JMenuItem("Random");
JMenuItem aggressive = new JMenuItem("Aggressive");
JMenuItem human = new JMenuItem("Human");
public Screen(Board board){
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
....
//sets up board of buttons and adds actionListener to each.
....
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
//code for the board buttons - nothing to do with the menu.
//But thought it might help
if (numClicks == 0){
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
FromXInt = Integer.parseInt(x);
FromYInt = Integer.parseInt(y);
System.out.println("From" + " " +FromXInt + "," + FromYInt);
}
else{
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
ToXInt = Integer.parseInt(x);
ToYInt = Integer.parseInt(y);
System.out.println("To" + " " + ToXInt + "," + ToYInt);
}
numClicks++;
if (numClicks >= 2){
numClicks = 0;
}
return;
}
}
我的類,它包含的主要方法:
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// my attempt but doesn't work
if (s.actionPerformed(e) == random){
.....
注:我是新到Java仍然試圖讓我的頭多個類的鏈接。 --------------------如果點擊按鈕,ActionPerformed方法還包含事件,但我沒有添加該代碼,因爲它使事情變得複雜.--
你不返回任何東西來自actionPerformed,所以你不能將它與主方法中的任何東西進行比較。如果你想在你的actionPerformed方法中添加return e.getSource(),你可以這樣做。雖然我不完全瞭解你的程序的功能。 – Juru
您是否將ActionListener添加到任何onject? – Suspended
你檢查了e.getSource()返回的內容嗎? – Suspended