でActionListener
を使用して値を格納するのに問題があります。私はかなりJavaに慣れていないし、クラスとサブクラスのプログラミング方法に100%自信がない。JTextFieldから値を格納するときにJavaのフィールドを解決できません
import java.ActionEvent;
import javaActionListener;
import javax.swing JButton;
import javax.swing JPanel;
import javax.swing.JTextField;
public class Trial extends JPanel implements Action Listener {
private static final long serialVersionUID = 1L;
public Trial() {
setFrame();
}
public void setFrame(){
JFrame frame = new JFrame("Trial");
JPanel panel = new JPanel();
JTextField field = new JTextField(10);
JButton button = new JButton("Enter");
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new Trial();
}
@Override
public void actionPerformed(ActionEvent e) {
String s = field.getText();
System.out.prinln("Button is pressed");
}
}
これがそうである理由フィールドは、actionPerformed
内部で定義されていませんか? ActionEventを使って遊んだところ、actionPerformed
関数の外の変数には渡せません。だから私はこれをどうやってやるの? setFrame()
を自分のクラスに移動する必要がありますか?
「試行」はなぜ「JPanel」を拡張しますか?それがそれをするのは完全に不必要なようです。 –
コードは元のコードのスニペットに過ぎません。私はちょうど質問のために必要なコード行を取った。 –