textPanel.setText( “”);不起作用或显示

时间:2014-03-06 21:02:55

标签: java swing jbutton jtextarea settext

每当我在Java GUI中按“清除”时,它永远不会有效,请帮我完成此操作。如果我将“textPanel”替换为另一个按钮,则可以使用,否则使用“textpanel”则不会。

以下是我的代码的轻量级版本,用于演示此问题:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MainFrame extends JFrame {
    private TextPanel textPanel;
    private FormPanel formpanel;

    public MainFrame(){
        super("My Frame");
        createLayout();
        createFrame();
    }

    public void createFrame(){
        setSize(600, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);       
    }

    public void createLayout(){
        BorderLayout myLayout = new BorderLayout();     
        setLayout(myLayout);

        textPanel = new TextPanel();
        formpanel = new FormPanel();

        // adding components
        add(textPanel, BorderLayout.CENTER);
        add(formpanel, BorderLayout.WEST);  
    }

    public static void main(String[] args){
        new MainFrame();
    }

    public static class FormPanel extends JPanel {

        private JButton clear;
        private TextPanel textPanel;

        public FormPanel(){
            clear = new JButton("Clear Cart!");
            textPanel=new TextPanel();
            add(clear);

            clear.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent aev){
                    System.out.println("Test");
                    textPanel.setText("");
                }       
            });
            createGrid();               
        }

        /* this methods simply creates the layout  */ 
        void createGrid(){
            //creating layout
            setLayout(new GridBagLayout());     
            GridBagConstraints gc = new GridBagConstraints();

            gc.gridy++;
            gc.weightx = .1;
            gc.weighty = .1;
            gc.gridx = 2;
            gc.gridy=5;
            gc.anchor = GridBagConstraints.LINE_START; 
            gc.insets = new Insets(0,0,0,0);

            add(clear, gc);

        }
    }

    public static class TextPanel extends JPanel {
        private JTextArea textArea;

        TextPanel (){
            textArea = new JTextArea();
            setLayout(new BorderLayout());

            JScrollPane p = new JScrollPane(textArea);
            add(p, BorderLayout.CENTER);
        }

        public void appendSomeText(String t){
            textArea.append(t);     
        }

        public void setText(String s){
            textArea.setText(s);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您有两个TextPanel个实例,一个位于MainFrame,另一个位于FormPanelTextPanel中定义的FormPanel实际上未添加到面板中,因此textPanel.setText("");对其没有影响,因为它不可见。

当文字附加Add To Cart!按钮时,它实际上会执行MainFrame - formEventOccurred()中执行textPanel.appendSomeText()的方法。这是TextPanel的另一个实例,它是MainFrame的一部分,实际上是可见的。

看起来您需要将复制的逻辑从主框架移动到面板。通常您不应该扩展JFrame,因为您没有添加任何新功能。