字符串变量不会显示在JFrame中不会显示

时间:2014-09-05 05:11:31

标签: java swing arraylist jframe

当我运行此程序时,变量String 结果不会显示在JPanel outpanel 中。有人可以告诉我为什么吗?我已经尝试谷歌搜索和试验static等几个小时,但我相信static即使它确实解决它也不是OO友好的答案。

import java.util.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.*;

public class AProgram extends JFrame 
            implements WindowListener, ActionListener  {

    public JButton gbt = new JButton("GO");
    public JPanel outpanel = new JPanel();
    public ArrayList<String> responses;
    public String result;

    public AProgram() {
        super ("Program");
    }

    public void init() {
        //output
        outpanel.setOpaque(true);
        outpanel.setPreferredSize(new Dimension(600, 75)); 
        outpanel.setBorder(new LineBorder(Color.black, 2));       
        JLabel jl = new JLabel();    
        jl.setText(result);
        outpanel.add(jl);
        this.add("South", outpanel);

        //press-button - does NOT sit in a panel.
        gbt.setBackground(Color.GREEN);
        gbt.setPreferredSize(new Dimension(75, 75));
        gbt.setBorder(new LineBorder(Color.black, 2)); 
        this.add("East", gbt);

        //all
        gbt.addActionListener(this);
        this.addWindowListener(this);
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);
    }

    public void actionPerformed (ActionEvent evt) {
        String input = "A Lion is ";
        finishSentence(input);
    }

    public void windowClosing (WindowEvent e) {
        this.setVisible(false);
        this.dispose();
    }

    public void windowOpened(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}

    public String finishSentence(String inwds) {
        responses = new ArrayList<String>();
        responses.add(0, "a bookish creature");
        responses.add(1, "quiet and unassuming");
        responses.add(2, "King of the Jungle");

        String result = inwds + responses.get(2);

        return result;
    }

    public static void main (String[] args) {
        AProgram me = new AProgram();
        me.init();
    }
}

1 个答案:

答案 0 :(得分:3)

init()方法中,您将jl的文字设置为null的结果。

然后在actionPerformed()中调用方法finishSentence(),该方法返回String,但您没有将其分配给任何变量或元素。

再次在jl.setText()

中致电actionPerformed()
public void actionPerformed (ActionEvent evt)  {

        String input = "A Lion is ";

        jl.setText(finishSentence(input));                                        

        }