我是Java的初学者,所以请不要苛刻答案。我试图通过尝试编写相对较难为我编程的程序来提高我的java技能,但是这个让我陷入困境。
public class Szymon {
public static void reply(String name) {
switch(name){
case "michal":name="Niedzwiedz!";
break;
default:System.out.println("wot ?");
}
}
public static void greet(String name){
System.out.printf("Elo %s co tam u ciebie ? \n",name);
}
}
我花了好几个小时写这篇文章,尽管不是很多,但我从中获得了很多经验。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Window<label> extends JFrame{
private static final long serialVersionUID=1L;
public Window(){
super("Display of Input & Output");
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p= new JPanel();
JButton b= new JButton("reply()");
final JTextField tf=new JTextField();
tf.setColumns(10);
JButton b2= new JButton("greet()");
final JTextField tf2=new JTextField();
tf2.setColumns(10);
final JLabel label=new JLabel();
p.add(b);
p.add(tf);
p.add(b2);
p.add(tf2);
p.add(label);
new Szymon();
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String tfVal = tf.getText();
Szymon.reply(tfVal);
}
});
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String tf2Val=tf2.getText();
Szymon.greet(tf2Val);
}
});
add(p);
}
}
答案 0 :(得分:1)
而不是尝试从您调用的方法中修改调用者,这是一个过度扩展责任的问题,而是返回调用者应该应用的值...
public class Szymon {
public static String reply(String name) {
switch(name){
case "michal":name="Niedzwiedz!";
break;
default:name = "wot ?";
}
// Return the value to be applied...
return name;
}
public static void greet(String name){
System.out.printf("Elo %s co tam u ciebie ? \n",name);
}
}
然后,当您调用该方法时,请在返回时应用更改...
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String tfVal = tf.getText();
String reVal = Szymon.reply(tfVal);
label.setText(reValue);
}
});
例如......