将单独的JPanel / JInternalFrame加载到单独的JDesktopPane(在JFrame中)

时间:2013-04-16 12:03:52

标签: java swing jframe netbeans-7

假设我有一个包含NewMDIApplication extends javax.swing.JFrameJDesktopPane的课程JButton。另外假设我有另一个班级NewJInternalFrame extends javax.swing.JInternalFrameNewJPanel extends javax.swing.JPanel,它还包含一些“按钮”和“文本框”,用于执行某些操作。

我的目的是在点击NewJInternalFrame时将NewJPanel的对象或JDesktopPane的对象加载到NewMDIApplication的{​​{1}}中。 有可能吗?如果是的话,怎么做?

1 个答案:

答案 0 :(得分:1)

以下是将JInternalFrame个实例添加到JDesktopPane的工作示例。请注意,您需要设置尺寸,否则它们不会出现。

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

public class FrameWithInternalFrames {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

        @Override
        public void run() {
            // the GUI as seen by the user (without frame)
            JPanel gui = new JPanel(new BorderLayout());
            gui.setBorder(new EmptyBorder(2, 3, 2, 3));

            gui.setPreferredSize(new Dimension(400, 100));
            gui.setBackground(Color.WHITE);

            final JDesktopPane dtp = new JDesktopPane();
            gui.add(dtp, BorderLayout.CENTER);

            JButton newFrame = new JButton("Add Frame");

            ActionListener listener = new ActionListener() {
            private int disp = 10;
            @Override
            public void actionPerformed(ActionEvent e) {
                JInternalFrame jif = new JInternalFrame();
                dtp.add(jif);
                jif.setLocation(disp, disp);
                jif.setSize(100,100); // VERY important!
                disp += 10;
                jif.setVisible(true);
            }
            };
            newFrame.addActionListener(listener);

            gui.add(newFrame, BorderLayout.PAGE_START);

            JFrame f = new JFrame("Demo");
            f.add(gui);
            // Ensures JVM closes after frame(s) closed and
            // all non-daemon threads are finished
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            // See http://stackoverflow.com/a/7143398/418556 for demo.
            f.setLocationByPlatform(true);

            // ensures the frame is the minimum size it needs to be
            // in order display the components within it
            f.pack();
            // should be done last, to avoid flickering, moving,
            // resizing artifacts.
            f.setVisible(true);
        }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
相关问题