本文介绍了ActionListener中的Java Swing问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

//GUI.java
public class GUI extends JFrame implements ActionListener {

    private static final long serialVersionUID = 870343916997182570L;
    private JPanel btmPanel;

    public GUI(String arg0) throws HeadlessException {
        super(arg0);
        createGUI();
    }

    private void createGUI() {
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        //ResultPanel rslt = new ResultPanel();
        //this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);

        btmPanel = new JPanel();
        btmPanel.setBackground(Color.LIGHT_GRAY);
        btmPanel.setLayout(new FlowLayout());

        JButton blueSearch = new JButton("Search");
        blueSearch.setBackground(Color.WHITE);
        blueSearch.addActionListener(this);
        btmPanel.add(blueSearch);

        JButton blackChart = new JButton("Chart");
        blackChart.setBackground(Color.WHITE);
        blackChart.addActionListener(this);
        btmPanel.add(blackChart);

        this.getContentPane().add(btmPanel, BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String buttonString = e.getActionCommand();

        if (buttonString.equals("Search")) {
            ResultPanel rslt = new ResultPanel();
            this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);
        }
    }

}

//ResultPanel.java
public class ResultPanel extends JPanel implements ActionListener {

    private static final long serialVersionUID = -7851502165390304971L;
    private JPanel textPanel;
    private JTextArea textDisplay;

    public ResultPanel() {
        textPanel = new JPanel();
        textDisplay = new JTextArea("Text Area:");
    }

    public JPanel createPanel() {

        textDisplay.setEditable(true);
        textPanel.setBackground(Color.LIGHT_GRAY);
        textPanel.setLayout(new BorderLayout());
        textPanel.add(textDisplay,BorderLayout.CENTER);

        return textPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {


    }

}

我在主机上有两个按钮,我希望在按下按钮时可以更改面板。

I have two buttons on the main frame, and I hope to change the panel when I press the button.

问题是 actionPerformed中的代码不起作用,

The question is that the code in "actionPerformed" doesn't work,

,但如果我将它们放在creatGUI()中。...(请参见标记部分)。

but it works well if I put them in the creatGUI()....(see the marked section).

有什么问题吗?

推荐答案

添加面板后,只需调用 pack();

Just call pack(); after you add the panel. This will get the JFrame to show the update.

    if (buttonString.equals("Search")) {
        ResultPanel rslt = new ResultPanel();
        this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);
        pack();
    }

这篇关于ActionListener中的Java Swing问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:15