0

我是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);

       }





}
4

1 回答 1

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);
    }
});

例如...

于 2013-09-15T11:11:09.387 回答