3

私は見なければなりません:

  1. MainWindowView (JFrame を拡張)
  2. ScanOptimisationView (JPanel を拡張)

だから、私は MainWindowView クラスにコンボボックスを持っています。そして、ActionListener を作成し、このコンボボックスにバインドします。この ActionListener の actionPerfomed() メソッドは、ScanOptimisationView パネルをメイン ウィンドウ フレームに追加しようとします。コードは次のとおりです。

package ru.belaventcev.view;

import java.awt.Container;

public class MainWindowView extends JFrame{
    private int frmHeight = 525;
    private int frmWidth  = 650;

    public Container frmContainer;

    public static JButton btnCalc;

    public static JComboBox cbMethods;

    public MainWindowView(){
        setPreferredSize(new Dimension(frmWidth, frmHeight));
        setSize(frmWidth, frmHeight);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        frmContainer = getContentPane();
        frmContainer.setLayout(new MigLayout("", "[grow,center]", "[::30px,grow,center][grow,center][::500px,grow,center][::25px,grow,center]"));
        cbMethods = new JComboBox();
        cbMethods.setModel(new DefaultComboBoxModel(new JPanel[] {new ScanOptimisationView()}));
        cbMethods.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JPanel temp = (JPanel) cbMethods.getSelectedItem();
                frmContainer.add(temp, "cell 0 1,span");
            }
        });

        /*
         * If I uncomment this, panel is shown!
        JPanel temp = (JPanel) cbMethods.getSelectedItem();
        frmContainer.add(temp, "cell 0 1");
        */

        frmContainer.add(cbMethods, "cell 0 0,growx");



        btnCalc = new JButton("Расчитать");
        frmContainer.add(btnCalc, "cell 0 3,alignx right");

    }
}

以下のコードを使用すると、actionPerformed() のコードでパネルが表示されないのに、表示されるのはなぜですか?

4

1 に答える 1

5

動作しない場合、actionListener が を呼び出した後、frmContainer.add()を呼び出す必要がありますfrmContainer.validate()。Container.add() の Javadoc から:

「表示されているコンテナにコンポーネントが追加されている場合、新しいコンポーネントを表示するには、そのコンテナで検証を呼び出す必要があります。」

クリックに応答しているとき、コンテナは明らかにすでに表示されています。コンストラクターに JPanel を追加しても、JFrame はまだ表示されていません。

于 2011-12-24T07:33:00.433 に答える