String
aを anに渡すことは可能ActionListener
ですか? 数当てゲームを作成していますが、選択した難易度を に渡す必要がありActionListener
ます。これは、最初に開いた GUI から渡されるためです。コンストラクターに直接渡されるので、これをどのように行うのGame()
ですか?
4 に答える
Have your ActionListener access a variable that contains the result of the guess.
I would do something like:
final JTextArea textArea = new JTextArea();
JButton button =new JButton("press");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String text = textArea.getText();
if (text.equals("something")) {
doSomething();
} else {
doSomethingElse();
}
}
});
文字列はどこから来たのですか?そのコンポーネントをActionListener
構築時に渡すことができます。たとえば、文字列はJLabel
オブジェクトから取得されます。それで
class GuessNumberActionListener implements ActionListener {
private JLabel difficulty;
public GuessNumberActionListener(JLabel difficulty) {
this.difficulty = difficulty;
}
// implement other methods
}
次に、アクションリスナー内で、必要なものにアクセス/更新できます。
ActionListener はインターフェースです。継承を使用してインターフェイスの機能を拡張してみてください。これはトリックを行います
Sure you can. There are lots of ways but one of them is to pass it in to the the ActionListener
's constructor:
public class MyClass implements ActionListener {
private int difficultyLevel;
public MyClass(int difficultyLevel) {
this.difficultyLevel = difficultyLevel;
}
public void actionPerformed(ActionEvent e) {
...//code that reacts to action and does something based on difficultyLevel
}
}
UPDATE:
Looks like the design patterns police are out in full force today. You may want to quickly rewrite your app in MVC before you get shot in the foot :)