简体   繁体   English

如何使用JAVA处理多个窗口(不同的jframe)中的事件?

[英]how to handle events across multiple windows (different jframes) using JAVA?

I am creating an ide which will contain a workarea (a jframe) and a toolbox (another jframe). 我正在创建一个ide,其中将包含一个工作区(一个jframe)和一个工具箱(另一个jframe)。 how do I accomplish the task of handling events across these two jframes? 如何完成在这两个jframe中处理事件的任务? For example, if I click on a tool in the toolbox, an action has to take place in the workarea. 例如,如果我单击工具箱中的工具,则必须在工作区中执行一个操作。

Please help me out 请帮帮我

CODE FOR TOOLBOX: 工具箱代码:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class ToolboxForPDP extends JFrame {

/**
 *
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ToolboxForPDP frame = new ToolboxForPDP();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public ToolboxForPDP() {
    setResizable(false);
    try {
        UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

    setTitle("Toolbox");
    setType(Type.UTILITY);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 157, 445);
    contentPane = new JPanel();
    contentPane.setBackground(new Color(245, 245, 220));
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnNewButton = new JButton("");
    btnNewButton.setToolTipText("Select an element in the work area");
    btnNewButton.setBackground(new Color(255, 255, 255));
    btnNewButton.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\select.jpg"));
    btnNewButton.setBounds(10, 11, 55, 45);
    contentPane.add(btnNewButton);

    JButton btnNewButton_1 = new JButton("");
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnNewButton_1.setToolTipText("Insert Image");
    btnNewButton_1.setBackground(new Color(255, 255, 255));
    btnNewButton_1.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\image.png"));
    btnNewButton_1.setBounds(75, 11, 55, 45);
    contentPane.add(btnNewButton_1);

    JButton btnNewButton_2 = new JButton("");
    btnNewButton_2.setToolTipText("Insert Text");
    btnNewButton_2.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\text.jpg"));
    btnNewButton_2.setBackground(new Color(255, 255, 255));
    btnNewButton_2.setBounds(10, 67, 55, 45);
    contentPane.add(btnNewButton_2);

    JButton btnNewButton_3 = new JButton("");
    btnNewButton_3.setToolTipText("Insert Hyperlink");
    btnNewButton_3.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\hyperlink.png"));
    btnNewButton_3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnNewButton_3.setBackground(new Color(255, 255, 255));
    btnNewButton_3.setBounds(75, 67, 55, 45);
    contentPane.add(btnNewButton_3);

    JButton btnNewButton_4 = new JButton("");
    btnNewButton_4.setToolTipText("Change Page Background Properties");
    btnNewButton_4.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\fill color.png"));
    btnNewButton_4.setBackground(new Color(255, 255, 255));
    btnNewButton_4.setBounds(10, 123, 55, 45);
    contentPane.add(btnNewButton_4);

    JButton btnNewButton_5 = new JButton("");
    btnNewButton_5.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\textbox.jpg"));
    btnNewButton_5.setToolTipText("Insert Textbox");
    btnNewButton_5.setBackground(new Color(255, 255, 255));
    btnNewButton_5.setBounds(10, 179, 55, 45);
    contentPane.add(btnNewButton_5);

    JButton btnNewButton_6 = new JButton("");
    btnNewButton_6.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\radio Button.gif"));
    btnNewButton_6.setToolTipText("Insert Radio Button");
    btnNewButton_6.setBackground(new Color(255, 255, 255));
    btnNewButton_6.setBounds(10, 235, 55, 45);
    contentPane.add(btnNewButton_6);

    JButton btnNewButton_7 = new JButton("");
    btnNewButton_7.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\checkbox.gif"));
    btnNewButton_7.setToolTipText("Insert Checkbox");
    btnNewButton_7.setBackground(new Color(255, 255, 255));
    btnNewButton_7.setBounds(10, 291, 55, 45);
    contentPane.add(btnNewButton_7);

    JButton btnNewButton_8 = new JButton("");
    btnNewButton_8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        }
    });
    btnNewButton_8.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\hr.jpg"));
    btnNewButton_8.setToolTipText("Insert Horizontal Rule");
    btnNewButton_8.setBackground(new Color(255, 255, 255));
    btnNewButton_8.setBounds(75, 123, 55, 45);
    contentPane.add(btnNewButton_8);

    JButton btnNewButton_9 = new JButton("");
    btnNewButton_9.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\button.jpg"));
    btnNewButton_9.setToolTipText("Insert Button");
    btnNewButton_9.setBackground(new Color(255, 255, 255));
    btnNewButton_9.setBounds(75, 179, 55, 45);
    contentPane.add(btnNewButton_9);

    JButton btnNewButton_10 = new JButton("");
    btnNewButton_10.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\drop-down list.png"));
    btnNewButton_10.setToolTipText("Insert Drop-Down List");
    btnNewButton_10.setBackground(new Color(255, 255, 255));
    btnNewButton_10.setBounds(75, 235, 55, 45);
    contentPane.add(btnNewButton_10);

    JButton btnNewButton_11 = new JButton("");
    btnNewButton_11.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\list.jpg"));
    btnNewButton_11.setToolTipText("Insert List");
    btnNewButton_11.setBackground(new Color(255, 255, 255));
    btnNewButton_11.setBounds(75, 291, 55, 45);
    contentPane.add(btnNewButton_11);

    JButton btnNewButton_12 = new JButton("");
    btnNewButton_12.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        }
    });
    btnNewButton_12.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\toolbox icons\\icoScript.png"));
    btnNewButton_12.setToolTipText("Add Script");
    btnNewButton_12.setBackground(new Color(255, 255, 255));
    btnNewButton_12.setBounds(42, 347, 55, 45);
    contentPane.add(btnNewButton_12);
}
}

CODE FOR WORKAREA: 工作区代码:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.ImageIcon;
import java.awt.Toolkit;


public class StartScreen extends JFrame {

/**
 *
 */
private static final long serialVersionUID = 1L;
private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                StartScreen frame = new StartScreen();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public StartScreen() {
    try {
        UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

    setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\logos\\swami_vivekananda2.png"));
    setTitle("PageDesigner PRO(TM)");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(10, 10, 1350, 700);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);

    JMenu mnNew = new JMenu("New");
    mnNew.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\Folder-New-icon.png"));
    mnFile.add(mnNew);

    JMenuItem mntmNewProject = new JMenuItem("New Project");
    mnNew.add(mntmNewProject);

    JMenuItem mntmNewPage = new JMenuItem("New Page");
    mnNew.add(mntmNewPage);
    mnFile.addSeparator();

    JMenuItem mntmSave = new JMenuItem("Save");
    mntmSave.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\save.png"));
    mnFile.add(mntmSave);

    JMenuItem mntmSaveAs = new JMenuItem("Save As...");
    mnFile.add(mntmSaveAs);
    mnFile.addSeparator();

    JMenuItem mntmAddToProject = new JMenuItem("Add to project");
    mnFile.add(mntmAddToProject);

    JMenuItem mntmTestThisPage = new JMenuItem("Test this page");
    mnFile.add(mntmTestThisPage);
    mnFile.addSeparator();

    JCheckBoxMenuItem chckbxmntmShowWelcomeScreen = new JCheckBoxMenuItem("Show Welcome screen at startup");
    mnFile.add(chckbxmntmShowWelcomeScreen);
    mnFile.addSeparator();

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\exit.png"));
    mnFile.add(mntmExit);

    JMenu mnEdit = new JMenu("Edit");
    menuBar.add(mnEdit);

    JMenuItem mntmModifyElementProperties = new JMenuItem("Modify Element Properties");
    mnEdit.add(mntmModifyElementProperties);

    JMenu mnMode = new JMenu("Mode");
    menuBar.add(mnMode);

    JRadioButtonMenuItem rdbtnmntmBeginnerMode = new JRadioButtonMenuItem("Beginner Mode");
    mnMode.add(rdbtnmntmBeginnerMode);

    JRadioButtonMenuItem rdbtnmntmAdvancedMode = new JRadioButtonMenuItem("Advanced Mode");
    mnMode.add(rdbtnmntmAdvancedMode);

    ButtonGroup modeMenuGroup = new ButtonGroup();
    modeMenuGroup.add(rdbtnmntmBeginnerMode);
    modeMenuGroup.add(rdbtnmntmAdvancedMode);

    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    JMenuItem mntmUserGuide = new JMenuItem("User Guide");
    mntmUserGuide.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\manual icon.gif"));
    mnHelp.add(mntmUserGuide);

    JMenuItem mntmAbout = new JMenuItem("About...");
    mntmAbout.setIcon(new ImageIcon("D:\\KS\\4-1\\Mini-Project\\PageDesigner PRO(TM)\\PageDesigner PRO(TM)\\resources\\pics\\icons\\menu icons\\info_black.png"));
    mnHelp.add(mntmAbout);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
}
}

Your question is how to pass information from one JFrame to another, and this can be done as simply as having one class call a method of the other class. 您的问题是如何将信息从一个JFrame传递到另一个JFrame,这可以像让一个类调用另一个类的方法那样简单地完成。 That you haven't done this, and that you've only posted a skeleton program, one with components but with no logic suggests to me that you are still very much a beginner Java programmer, and so my main suggestion is that first and foremost you strive to learn to code, and in particular learn about object oriented principles and how they relate to Java. 您尚未执行此操作,并且您只发布了一个框架程序,该程序具有组件,但是没有逻辑,这向我暗示您仍然是一名初学者Java程序员,所以我的主要建议是您将努力学习编码,尤其是学习面向对象的原理以及它们与Java的关系。 Without these rudiments under your belt, we can give you code and pointers, but it won't help you much. 如果没有这些基础知识,我们可以为您提供代码和指针,但是对您没有太大帮助。 I suggest that you go to the Java Tutorials and start there, but also that you get a decent book or two on the subject such as Bruce Eckel's Thinking in Java , and/or Head First Java . 我建议您去Java教程并从那里开始,而且您会获得一本关于该主题的不错的书,例如Bruce Eckel的《 Java思维》和/或Head First Java

As for your actual code I suggest that you not create classes that extend JFrame since that locks you into a JFrame, and again as per my comment above, your tool window should be a non-modal JDialog not a JFrame. 至于您的实际代码,我建议您不要创建扩展JFrame的类,因为这会将您锁定在JFrame中,并且根据我上面的评论,您的工具窗口应该是非模式JDialog,而不是JFrame。 If you gear your code towards creating JPanels, then you can place them into JFrames, JDialogs, other JPanels, etc... wherever needed, and so this gives you a lot more flexibility. 如果您将代码用于创建JPanels,则可以在需要的地方将它们放置在JFrames,JDialogs,其他JPanels等中,这样可以为您提供更大的灵活性。

The main difficulty in the situation of your program is not passing information from one window to another, one object to another, really, but rather when to do so, since the program is event driven. 程序情况的主要困难在于,实际上不是将信息从一个窗口传递到另一个窗口,而是将一个对象传递给另一个对象,而是在何时进行传递,因为该程序是事件驱动的。 Myself, I like to use PropertyChangeListeners for this, basically using an observer interface that is already part of the Swing GUI structure. 我自己,我喜欢为此使用PropertyChangeListeners,基本上是使用已经是Swing GUI结构一部分的观察者接口。 For example in the code below I create two main JPanels, one is displayed within a JFrame, the other within a non-modal JDialog, and I pass button press information (the actionCommand String of the button) to the JTextArea in the main GUI via a PropertyChangeListener: 例如,在下面的代码中,我创建了两个主JPanel,一个显示在JFrame中,另一个显示在非模态JDialog中,然后通过以下方式将按钮按下信息(按钮的actionCommand字符串)传递给主GUI中的JTextArea PropertyChangeListener:

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;

public class Foo3 {
    private static void createAndShowGui() {
        final MainPanel1 mainPanel1 = new MainPanel1();
        final ToolPanel1 toolPanel1 = new ToolPanel1();

        JFrame frame = new JFrame("Foo3");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel1);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        JDialog dialog = new JDialog(frame, "Toolbar", ModalityType.MODELESS);
        dialog.add(toolPanel1);
        dialog.pack();
        dialog.setLocationByPlatform(true);
        dialog.setVisible(true);

        toolPanel1.addPropertyChangeListener(ToolPanel1.ACTION_COMMAND, new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                mainPanel1.appendActionCommand((String) evt.getNewValue());
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

class MainPanel1 extends JPanel {
    private JTextArea actionCommandArea = new JTextArea(30, 50);
    private JScrollPane scrollPane = new JScrollPane(actionCommandArea);

    public MainPanel1() {
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
    }

    public void appendActionCommand(String text) {
        actionCommandArea.append(text + "\n");
    }
}

class ToolPanel1 extends JPanel {
    public static final String ACTION_COMMAND = "action command";
    public static final String[] BTN_TEXTS  = {
        "Select Element",
        "Insert Image",
        "Insert Text",
        "Insert Hyperlink",
        "Change Page Background",
        "Insert Textbox",
        "Insert Radio Button", 
        "Insert Checkbox",
        "Insert Horizontal Rule",
        "Insert Button",
        "Insert Drop-Down List",
        "Insert List",
        "Add Script"
    };
    private String actionCommand = "";

    public ToolPanel1() {
        int rows = 0; // variable number of rows
        int cols = 2; // 2 columns
        int hgap = 5;
        int vgap = hgap;
        setLayout(new GridLayout(rows, cols, hgap, vgap));
        setBorder(BorderFactory.createEmptyBorder(hgap, hgap, hgap, hgap));

        for (String btnText : BTN_TEXTS) {
            add(new JButton(new ButtonAction(btnText)));
        }
    }

    public String getActionCommand() {
        return actionCommand;
    }

    private class ButtonAction extends AbstractAction {
        public ButtonAction(String name) {
            super(name);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String oldValue = "";
            String newValue = e.getActionCommand();
            actionCommand = newValue;
            ToolPanel1.this.firePropertyChange(ACTION_COMMAND, oldValue, newValue);
        }
    }
}

A more robust design would be to use a Model-View-Controller type design, but this is a bit more advanced, and you'll need to get some more code experience under your belt before using this, I think. 更健壮的设计是使用Model-View-Controller类型的设计,但这要高级一些,我认为您需要掌握更多代码经验。 also check out these links to similar questions/answers . 还可以查看这些指向类似问题/答案的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM