diff --git a/resources/images/EvASplashScreen.png b/resources/images/EvASplashScreen.png new file mode 100644 index 00000000..8a894444 Binary files /dev/null and b/resources/images/EvASplashScreen.png differ diff --git a/resources/images/Help24.gif b/resources/images/Help24.gif new file mode 100644 index 00000000..a2848d88 Binary files /dev/null and b/resources/images/Help24.gif differ diff --git a/resources/images/Open16.gif b/resources/images/Open16.gif new file mode 100644 index 00000000..fabd5676 Binary files /dev/null and b/resources/images/Open16.gif differ diff --git a/resources/images/Save16.gif b/resources/images/Save16.gif new file mode 100644 index 00000000..954f1acc Binary files /dev/null and b/resources/images/Save16.gif differ diff --git a/src/eva2/EvAInfo.java b/src/eva2/EvAInfo.java index e361adff..6932786a 100644 --- a/src/eva2/EvAInfo.java +++ b/src/eva2/EvAInfo.java @@ -95,7 +95,7 @@ public class EvAInfo { public static final String GPLFile= "gpl-3.0.txt"; public static final String iconLocation = "resources/images/icon4.gif"; - public static final String splashLocation = "resources/images/splashScreen2.png"; + public static final String splashLocation = "resources/images/EvASplashScreen.png"; public static final String infoTitle = productName+" Information"; public static final String copyrightYear = "2010-2012"; diff --git a/src/eva2/client/EvAClient.java b/src/eva2/client/EvAClient.java index 45b5762b..6281310a 100644 --- a/src/eva2/client/EvAClient.java +++ b/src/eva2/client/EvAClient.java @@ -15,6 +15,7 @@ import eva2.EvAInfo; import eva2.gui.*; import eva2.server.EvAServer; import eva2.server.go.InterfaceGOParameters; +import eva2.server.go.strategies.GradientDescentAlgorithm; import eva2.server.modules.AbstractModuleAdapter; import eva2.server.modules.GOParameters; import eva2.server.modules.GenericModuleAdapter; @@ -28,8 +29,9 @@ import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.URL; +import java.util.ArrayList; +import java.util.List; import java.util.Set; -import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; @@ -50,7 +52,10 @@ public class EvAClient implements RemoteStateListener, Serializable { private final int splashScreenTime = 1500; private final int maxWindowMenuLength = 30; private boolean clientInited = false; - private JEFrame evaFrame; + private JDesktopPane desktopPane; + private JFrame mainFrame; + private JPanel configurationPane; + private JSplitPane horizontalSplit; private Runnable initRnbl = null; private EvAComAdapter comAdapter; @@ -95,7 +100,7 @@ public class EvAClient implements RemoteStateListener, Serializable { private long startTime = 0; // remember the module in use private transient String currentModule = null; - Vector superListenerList = null; + private List superListenerList = null; private boolean withGUI = true; private boolean withTreeView = false; private EvATabbedFrameMaker frameMaker = null; @@ -103,7 +108,7 @@ public class EvAClient implements RemoteStateListener, Serializable { public void addRemoteStateListener(RemoteStateListener l) { if (superListenerList == null) { - superListenerList = new Vector(); + superListenerList = new ArrayList(); } superListenerList.add(l); } @@ -332,8 +337,8 @@ public class EvAClient implements RemoteStateListener, Serializable { * @param l */ public void addWindowListener(WindowListener l) { - if (evaFrame != null) { - evaFrame.addWindowListener(l); + if (mainFrame != null) { + mainFrame.addWindowListener(l); } else { System.err.println("Error, no JFrame existent in " + this.getClass().getSimpleName()); @@ -346,8 +351,8 @@ public class EvAClient implements RemoteStateListener, Serializable { * @param l */ public void removeWindowListener(WindowListener l) { - if (evaFrame != null) { - evaFrame.removeWindowListener(l); + if (mainFrame != null) { + mainFrame.removeWindowListener(l); } else { System.err.println("Error, no JFrame existent in " + this.getClass().getSimpleName()); @@ -370,13 +375,25 @@ public class EvAClient implements RemoteStateListener, Serializable { } if (withGUI) { - evaFrame = new JEFrame(EvAInfo.productName + " workbench"); - evaFrame.setCloseAllOnClosed(true); - evaFrame.setName(this.getClass().getSimpleName()); // the name is set to recognize the client window - + GridBagConstraints gbConstraints = new GridBagConstraints(); + + /* Set Look and Feel */ + try { + //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (Exception ex) { + LOGGER.log(Level.INFO, "Could not set Look&Feel", ex); + } + mainFrame = new JFrame(EvAInfo.productName + " Workbench"); + mainFrame.setLayout(new GridBagLayout()); + mainFrame.setMinimumSize(new Dimension(800, 600)); + desktopPane = new JExtDesktopPane(); + + JEFrameRegister.getInstance().setDesktopPane(desktopPane); + horizontalSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); + BasicResourceLoader loader = BasicResourceLoader.instance(); byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); - evaFrame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); + mainFrame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); try { Thread.sleep(200); @@ -384,16 +401,9 @@ public class EvAClient implements RemoteStateListener, Serializable { System.out.println("Error" + e.getMessage()); } - progressBar = new JProgressBar(); - progressBar.setBorder(new TitledBorder("Progress")); - progressBar.setValue(0); - progressBar.setStringPainted(true); - evaFrame.getContentPane().add(progressBar, BorderLayout.NORTH); - - evaFrame.getContentPane().setLayout(new BorderLayout()); logPanel = new LoggingPanel(LOGGER); - evaFrame.getContentPane().add(logPanel, BorderLayout.SOUTH); - + logPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); + if (EvAInfo.propShowModules() != null) { showLoadModules = true; @@ -401,10 +411,59 @@ public class EvAClient implements RemoteStateListener, Serializable { showLoadModules = false; // may be set to true again if default module couldnt be loaded } createActions(); + + mainFrame.setSize(800, 600); + + /* Create a new ConfigurationPanel (left side) */ + configurationPane = new JPanel(new GridBagLayout()); + gbConstraints.ipadx = 5; + gbConstraints.weightx = 0.0; + gbConstraints.weighty = 1.0; + /* Set configurationPane at 0,1 */ + gbConstraints.gridx = 0; + gbConstraints.gridy = 1; + gbConstraints.fill = GridBagConstraints.VERTICAL; + gbConstraints.gridwidth = GridBagConstraints.RELATIVE; + gbConstraints.gridheight = GridBagConstraints.RELATIVE; + mainFrame.add(configurationPane, gbConstraints); + + /* SplitPane for desktopPane and loggingPanel */ + horizontalSplit.setTopComponent(desktopPane); + horizontalSplit.setBottomComponent(logPanel); + horizontalSplit.setDividerLocation(0.25); + horizontalSplit.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); + horizontalSplit.setContinuousLayout(true); + /* Add horizontal split pane at 1,1 */ + gbConstraints.gridx = 1; + gbConstraints.gridy = 1; + gbConstraints.fill = GridBagConstraints.BOTH; + gbConstraints.gridwidth = GridBagConstraints.REMAINDER; + gbConstraints.gridheight = GridBagConstraints.RELATIVE; + mainFrame.add(horizontalSplit, gbConstraints); + + + /* Create ProgressBar and add it to the bottom */ + progressBar = new JProgressBar(); + progressBar.setBorder(new TitledBorder("Progress")); + progressBar.setValue(0); + progressBar.setStringPainted(true); + + gbConstraints.gridx = 0; + gbConstraints.gridy = 2; + gbConstraints.gridwidth = 2; + gbConstraints.weighty = 0.0; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.PAGE_END; + mainFrame.add(progressBar, gbConstraints); + + mainFrame.pack(); + mainFrame.setVisible(true); } if (useDefaultModule != null) { - // if goParams are not defined and a params file is defined - // try to load parameters from file + /* + * if goParams are not defined and a params file is defined + * try to load parameters from file + */ if (goParams == null && (paramsFile != null && (paramsFile.length() > 0))) { goParams = GOParameters.getInstance(paramsFile, false); } @@ -413,9 +472,9 @@ public class EvAClient implements RemoteStateListener, Serializable { if (withGUI) { buildMenu(); - evaFrame.addWindowListener(new WindowAdapter() { + mainFrame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { + public void windowClosing(final WindowEvent event) { EvAClient.this.close(); } }); @@ -433,12 +492,22 @@ public class EvAClient implements RemoteStateListener, Serializable { LOGGER.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir")); LOGGER.log(Level.INFO, "Class path is: {0}", System.getProperty("java.class.path", ".")); - if (!(evaFrame.isVisible())) { + if (!(configurationPane.isVisible())) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - evaFrame.setLocation((int) ((screenSize.width - evaFrame.getWidth()) / 2), (int) ((screenSize.height - evaFrame.getHeight()) / 2.5)); - evaFrame.pack(); - evaFrame.setVisible(true); + //evaFrame.setLocation((int) ((screenSize.width - evaFrame.getWidth()) / 2), (int) ((screenSize.height - evaFrame.getHeight()) / 2.5)); + configurationPane.setVisible(true); + } + + if (!(mainFrame.isVisible())) { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + mainFrame.setLocation((int) ((screenSize.width - mainFrame.getWidth()) / 2), (int) ((screenSize.height - mainFrame.getHeight()) / 2.5)); + mainFrame.pack(); + mainFrame.setSize(screenSize); + mainFrame.setVisible(true); + mainFrame.setVisible(true); + } + // if this message is omitted, the stupid scroll pane runs to // the end of the last line which is ugly for a long class path LOGGER.info("EvA2 ready"); @@ -451,7 +520,6 @@ public class EvAClient implements RemoteStateListener, Serializable { */ public void close() { LOGGER.info("Closing EvA2 Client. Bye!"); - evaFrame.dispose(); Set keys = System.getenv().keySet(); if (keys.contains("MATLAB")) { LOGGER.info("EvA2 workbench has been started from Matlab: not killing JVM"); @@ -481,7 +549,12 @@ public class EvAClient implements RemoteStateListener, Serializable { * @param args command line parameters */ public static void main(String[] args) { - String[] keys = new String[]{"--help", "--autorun", "--nosplash", "--nogui", "--remotehost", "--params", "--treeView"}; + /* Available command-line parameters */ + String[] keys = new String[]{ + "--help", "--autorun", "--nosplash", "--nogui", + "--remotehost", "--params", "--treeView" + }; + /* Number of arguments per parameter */ int[] arities = new int[]{0, 0, 0, 0, 1, 1, 0}; Object[] values = new Object[keys.length]; @@ -532,9 +605,8 @@ public class EvAClient implements RemoteStateListener, Serializable { evaClient.awaitClientInitialized(); // this returns as soon as the // GUI is ready evaClient.addWindowListener(windowListener); - // modify initial settings: - evaClient.getStatistics().getStatisticsParameter().setOutputAllFieldsAsText(true); // activate output of all data - // fields + // modify initial settings and activate output of all data: + evaClient.getStatistics().getStatisticsParameter().setOutputAllFieldsAsText(true); // add a data listener instance: evaClient.getStatistics().addDataListener(statisticsListener); @@ -582,10 +654,8 @@ public class EvAClient implements RemoteStateListener, Serializable { actModuleLoad = new ExtAction("&Load", "Load Module", KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(final ActionEvent event) { loadModuleFromServer(null, null); } }; @@ -593,141 +663,123 @@ public class EvAClient implements RemoteStateListener, Serializable { actAbout = new ExtAction("&About...", "Product Information", KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); showAboutDialog(); } }; actLicense = new ExtAction("&License...", "View License", KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); showLicense(); } }; actHost = new ExtAction("&List of all servers", "All servers in list", KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); selectAvailableHost(comAdapter.getHostNameList()); } }; actAvailableHost = new ExtAction("Available &Server", "Available server", KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); showPleaseWaitDialog(); - Thread xx = new Thread() { - + new Thread() { @Override public void run() { selectAvailableHost(comAdapter.getAvailableHostNameList()); } - }; - xx.start(); + }.start(); } }; actKillHost = new ExtAction("&Kill server", "Kill server process on selected host", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); - showPleaseWaitDialog(); - Thread xx = new Thread() { - + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); + new Thread() { + @Override public void run() { selectAvailableHostToKill(comAdapter.getAvailableHostNameList()); } - }; - xx.start(); + }.start(); + showPleaseWaitDialog(); } }; actKillAllHosts = new ExtAction("Kill &all servers", "Kill all servers", KeyStroke.getKeyStroke(KeyEvent.VK_K, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { - LOGGER.info(e.getActionCommand()); - showPleaseWaitDialog(); - Thread xx = new Thread() { - + @Override + public void actionPerformed(final ActionEvent event) { + LOGGER.info(event.getActionCommand()); + new Thread() { + @Override public void run() { selectAllAvailableHostToKill(comAdapter.getAvailableHostNameList()); } - }; - xx.start(); + }.start(); + showPleaseWaitDialog(); } }; actQuit = new ExtAction("&Quit", "Quit EvA2 workbench", KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK)) { - /* (non-Javadoc) - * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) - */ - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(final ActionEvent event) { EvAClient.this.close(); } }; - /* - * m_actStartServerManager = new ExtAction("Start &Server Manager", - * "Start &Server Manager", KeyStroke.getKeyStroke(KeyEvent.VK_S, - * Event.CTRL_MASK)){ public void actionPerformed(ActionEvent e){ - * m_LogPanel.logMessage(e.getActionCommand()); ServerStartFrame sm = - * new ServerStartFrame(m_ComAdapter.getHostNameList()); } }; - */ } + /** + * Create the main menu and add actions. + */ private void buildMenu() { menuBar = new JMenuBar(); - evaFrame.setJMenuBar(menuBar); + mainFrame.setJMenuBar(menuBar); menuModule = new JExtMenu("&Module"); menuModule.add(actModuleLoad); - //////////////////////////////////////////////////////////////// menuWindow = new JExtMenu("&Window"); menuWindow.addMenuListener(new MenuListener() { - public void menuSelected(MenuEvent e) { - // System.out.println("Selected"); + @Override + public void menuSelected(final MenuEvent event) { menuWindow.removeAll(); JExtMenu curMenu = menuWindow; -// JScrollPane jsp = new JScrollPane(); - Object[] framelist = JEFrameRegister.getFrameList(); - for (int i = 0; i < framelist.length; i++) { - JMenuItem act = new JMenuItem((i + 1) + ". " + ((JEFrame) framelist[i]).getTitle()); - final JFrame selectedFrame = ((JEFrame) framelist[i]); + List frameList = JEFrameRegister.getInstance().getFrameList(); + int frameIndex = 1; + for (JEFrame frame : frameList) { + + JMenuItem act = new JMenuItem(frameIndex + ". " + frame.getTitle()); + final JInternalFrame selectedFrame = frame; act.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (!selectedFrame.isActive()) { - selectedFrame.setExtendedState(JFrame.NORMAL); + @Override + public void actionPerformed(final ActionEvent event) { + if (!selectedFrame.isFocusOwner()) { + //selectedFrame..setExtendedState(JFrame.NORMAL); selectedFrame.setVisible(false); - selectedFrame.setVisible(true); // it seems to be quite a fuss to bring something to the front and actually mean it... - selectedFrame.toFront(); // this seems useless - selectedFrame.requestFocus(); // this seems useless too + // it seems to be quite a fuss to bring something to the front and actually mean it... + selectedFrame.setVisible(true); + // this seems useless + selectedFrame.toFront(); + // this seems useless too + selectedFrame.requestFocus(); } } }); @@ -739,20 +791,24 @@ public class EvAClient implements RemoteStateListener, Serializable { curMenu = subMenu; } curMenu.add(act); + + /* Next frame index */ + frameIndex++; } - String[] commonPrefixes = JEFrameRegister.getCommonPrefixes(10); + String[] commonPrefixes = JEFrameRegister.getInstance().getCommonPrefixes(10); if (commonPrefixes.length > 0) { menuWindow.add(new JSeparator()); } for (int i = 0; i < commonPrefixes.length; i++) { final String prefix = commonPrefixes[i]; JMenuItem act = new JMenuItem("Close all of " + prefix + "..."); - act.addActionListener((new ActionListener() { + act.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - JEFrameRegister.closeAllByPrefix(prefix); + @Override + public void actionPerformed(final ActionEvent event) { + JEFrameRegister.getInstance().closeAllByPrefix(prefix); } - })); + }); menuWindow.add(act); } @@ -765,7 +821,6 @@ public class EvAClient implements RemoteStateListener, Serializable { } }); - //////////////////////////////////////////////////////////////// menuSelHosts = new JExtMenu("&Select Hosts"); menuSelHosts.setToolTipText("Select a host for the server application"); menuSelHosts.add(actHost); @@ -773,11 +828,10 @@ public class EvAClient implements RemoteStateListener, Serializable { menuSelHosts.addSeparator(); menuSelHosts.add(actKillHost); menuSelHosts.add(actKillAllHosts); - //////////////////////////////////////////////////////////////// + menuAbout = new JExtMenu("&About"); menuAbout.add(actAbout); menuAbout.add(actLicense); - ////////////////////////////////////////////////////////////// menuOptions = new JExtMenu("&Options"); menuOptions.add(menuSelHosts); @@ -790,18 +844,11 @@ public class EvAClient implements RemoteStateListener, Serializable { menuBar.add(menuOptions); menuBar.add(menuWindow); menuBar.add(menuAbout); + + menuBar.add(((JExtDesktopPane) desktopPane).getWindowMenu()); } - public static String getProductName() { - return EvAInfo.productName; - } - - protected void logMessage(String msg) { - if (logPanel != null) { - logPanel.logMessage(msg); - } - } /** * @@ -830,7 +877,7 @@ public class EvAClient implements RemoteStateListener, Serializable { if (selectedModule == null) { // show a dialog and ask for a module String[] ModuleNameList = comAdapter.getModuleNameList(); if (ModuleNameList == null) { - JOptionPane.showMessageDialog(evaFrame.getContentPane(), "No modules available on " + comAdapter.getHostName(), EvAInfo.infoTitle, 1); + JOptionPane.showMessageDialog(configurationPane, "No modules available on " + comAdapter.getHostName(), EvAInfo.infoTitle, 1); } else { String lastModule = null; @@ -846,7 +893,7 @@ public class EvAClient implements RemoteStateListener, Serializable { LOGGER.log(Level.INFO, "Defaulting to module: {0}", lastModule); } - selectedModule = (String) JOptionPane.showInputDialog(evaFrame.getContentPane(), + selectedModule = (String) JOptionPane.showInputDialog(configurationPane, "Which module do you want \n to load on host: " + comAdapter.getHostName() + " ?", "Load optimization module on host", JOptionPane.QUESTION_MESSAGE, @@ -858,7 +905,7 @@ public class EvAClient implements RemoteStateListener, Serializable { if (selectedModule == null) { System.err.println("not loading any module"); - } else { + } else { try { java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userRoot(); prefs.put("lastModule", selectedModule); @@ -872,7 +919,7 @@ public class EvAClient implements RemoteStateListener, Serializable { actHost.setEnabled(true); actAvailableHost.setEnabled(true); } - LOGGER.info("Selected Module: " + selectedModule); + LOGGER.log(Level.INFO, "Selected Module: {0}", selectedModule); } } @@ -951,36 +998,41 @@ public class EvAClient implements RemoteStateListener, Serializable { if (withGUI) { // this (or rather: EvAModuleButtonPanelMaker) is where the start button etc come from! frameMaker = newModuleAdapter.getModuleFrame(); -// newModuleAdapter.setLogPanel(m_LogPanel); - JPanel moduleContainer = frameMaker.makePanel(); // MK the main frame is actually painted in here - boolean wasVisible = evaFrame.isVisible(); - evaFrame.setVisible(false); - evaFrame.getContentPane().removeAll(); + /* This is the left TabPane on the main frame */ + JPanel moduleContainer = frameMaker.makePanel(); + + boolean wasVisible = configurationPane.isVisible(); + configurationPane.setVisible(false); + configurationPane.removeAll(); - // nested info-panel so that we can stay with simple borderlayouts - JPanel infoPanel = new JPanel(); - infoPanel.setLayout(new BorderLayout()); - infoPanel.add(progressBar, BorderLayout.SOUTH); - infoPanel.add(logPanel, BorderLayout.NORTH); JComponent tree = null; - if (withTreeView && (newModuleAdapter instanceof AbstractModuleAdapter)) { tree = getEvATreeView(frameMaker.getGOPanel(), "GOParameters", ((AbstractModuleAdapter) newModuleAdapter).getGOParameters()); - evaFrame.add(tree, BorderLayout.WEST); + configurationPane.add(tree, BorderLayout.LINE_START); } - evaFrame.add(frameMaker.getToolBar(), BorderLayout.NORTH); - evaFrame.add(moduleContainer, BorderLayout.CENTER); - //m_Frame.add(m_ProgressBar, BorderLayout.CENTER); - //m_Frame.add(m_LogPanel, BorderLayout.SOUTH); - evaFrame.add(infoPanel, BorderLayout.SOUTH); - - evaFrame.pack(); - evaFrame.setVisible(wasVisible); + + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.weightx = 1.0; + gbConstraints.weighty = 0.0; + gbConstraints.gridx = 0; + gbConstraints.gridy = 0; + gbConstraints.gridwidth = 2; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.anchor = GridBagConstraints.PAGE_START; + mainFrame.add(frameMaker.getToolBar(), gbConstraints); + + GridBagConstraints gbConstraints2 = new GridBagConstraints(); + gbConstraints2.gridx = 0; + gbConstraints2.gridy = 0; + gbConstraints2.fill = GridBagConstraints.VERTICAL; + gbConstraints2.gridheight = GridBagConstraints.REMAINDER; + gbConstraints2.weighty = 1.0; + configurationPane.add(moduleContainer, gbConstraints2); + configurationPane.validate(); } currentModule = selectedModule; - // m_ModulGUIContainer.add(Temp); } catch (Exception e) { currentModule = null; LOGGER.log(Level.SEVERE, "Error while newModulAdapter.getModulFrame(): " + e.getMessage(), e); @@ -1029,7 +1081,7 @@ public class EvAClient implements RemoteStateListener, Serializable { if (hostNames == null || hostNames.length == 0) { showNoHostFoundDialog(); } else { - String hostName = (String) JOptionPane.showInputDialog(evaFrame.getContentPane(), + String hostName = (String) JOptionPane.showInputDialog(configurationPane, "Which active host do you want to connect to?", "Host", JOptionPane.QUESTION_MESSAGE, null, hostNames, comAdapter.getHostName()); if (hostName != null) { @@ -1048,7 +1100,7 @@ public class EvAClient implements RemoteStateListener, Serializable { } private void showPleaseWaitDialog() { - JOptionPane.showMessageDialog(evaFrame.getContentPane(), "Please wait one moment.", EvAInfo.infoTitle, 1); + JOptionPane.showMessageDialog(configurationPane, "Please wait one moment.", EvAInfo.infoTitle, 1); } private void showAboutDialog() { @@ -1065,7 +1117,7 @@ public class EvAClient implements RemoteStateListener, Serializable { aboutMessage.append("\nSee: "); aboutMessage.append(EvAInfo.url); - JOptionPane.showMessageDialog(evaFrame, aboutMessage, EvAInfo.infoTitle, 1); + JOptionPane.showMessageDialog(configurationPane, aboutMessage, EvAInfo.infoTitle, 1); } private void showLicense() { @@ -1076,7 +1128,7 @@ public class EvAClient implements RemoteStateListener, Serializable { } private void showNoHostFoundDialog() { - JOptionPane.showMessageDialog(evaFrame.getContentPane(), "No host with running EVASERVER found. Please start one or \nadd the correct address to the properties list.", EvAInfo.infoTitle, 1); + JOptionPane.showMessageDialog(configurationPane, "No host with running EVASERVER found. Please start one or \nadd the correct address to the properties list.", EvAInfo.infoTitle, 1); } private void selectAvailableHostToKill(String[] HostNames) { @@ -1084,7 +1136,7 @@ public class EvAClient implements RemoteStateListener, Serializable { showNoHostFoundDialog(); return; } - String HostName = (String) JOptionPane.showInputDialog(evaFrame.getContentPane(), + String HostName = (String) JOptionPane.showInputDialog(configurationPane, "Which server do you want to be killed ?", "Host", JOptionPane.QUESTION_MESSAGE, null, HostNames, comAdapter.getHostName()); if (HostName == null) { diff --git a/src/eva2/client/EvAComAdapter.java b/src/eva2/client/EvAComAdapter.java index e1dfa64f..c37a2f4a 100644 --- a/src/eva2/client/EvAComAdapter.java +++ b/src/eva2/client/EvAComAdapter.java @@ -23,15 +23,15 @@ import java.rmi.RemoteException; * */ public class EvAComAdapter extends ComAdapter { - private LoggingPanel m_LogPanel; + private LoggingPanel loggingPanel; private EvAMainAdapterImpl localMainAdapter; private boolean runLocally = false; /** * */ - public void setLogPanel(LoggingPanel OutputFrame) { - m_LogPanel = OutputFrame; + public void setLogPanel(LoggingPanel loggingPanel) { + this.loggingPanel = loggingPanel; } /** * @@ -51,12 +51,14 @@ public class EvAComAdapter extends ComAdapter { public ModuleAdapter getModuleAdapter(String selectedModuleName, InterfaceGOParameters goParams, String noGuiStatsFile) { ModuleAdapter newModuleAdapter; if ((m_RMIServer == null) && isRunLocally()) { - //ret = evaAdapter.getModuleAdapter(Modul, hostAdd, this.m_MainAdapterClient); - newModuleAdapter = getLocalMainAdapter().getModuleAdapter(selectedModuleName, true, getHostName(), goParams, noGuiStatsFile, null); - } else { - newModuleAdapter = ((RMIConnectionEvA)getConnection(getHostName())).getModuleAdapter(selectedModuleName); - if (newModuleAdapter == null) System.err.println("RMI Error for getting ModuleAdapterObject : " + selectedModuleName); - } + //ret = evaAdapter.getModuleAdapter(Modul, hostAdd, this.m_MainAdapterClient); + newModuleAdapter = getLocalMainAdapter().getModuleAdapter(selectedModuleName, true, getHostName(), goParams, noGuiStatsFile, null); + } else { + newModuleAdapter = ((RMIConnectionEvA) getConnection(getHostName())).getModuleAdapter(selectedModuleName); + if (newModuleAdapter == null) { + System.err.println("RMI Error for getting ModuleAdapterObject : " + selectedModuleName); + } + } return newModuleAdapter; } @@ -86,12 +88,12 @@ public class EvAComAdapter extends ComAdapter { } list = ((EvAMainAdapter)Connection.getMainAdapter()).getModuleNameList(); } - if (m_LogPanel != null) - m_LogPanel.logMessage("List of modules on server:"); + if (loggingPanel != null) + loggingPanel.logMessage("List of modules on server:"); if (list != null) for (int i = 0; i < list.length; i++) { - if ( (String) list[i] != null && m_LogPanel != null) - m_LogPanel.logMessage( (String) list[i]); + if ( (String) list[i] != null && loggingPanel != null) + loggingPanel.logMessage( (String) list[i]); } return list; } diff --git a/src/eva2/gui/BeanInspector.java b/src/eva2/gui/BeanInspector.java index d0d56b66..c78bd26e 100644 --- a/src/eva2/gui/BeanInspector.java +++ b/src/eva2/gui/BeanInspector.java @@ -889,31 +889,36 @@ public class BeanInspector { * @param target The target object * @return String for the tooltip. */ - public static String getToolTipText(String name, MethodDescriptor[] methods, Object target, boolean stripToolTipToFirstPoint, int toHTMLLen) { - String result = ""; - String tipName = name + "TipText"; - for (int j = 0; j < methods.length; j++) { - String mname = methods[j].getDisplayName(); - Method meth = methods[j].getMethod(); - if (mname.equals(tipName)) { - if (meth.getReturnType().equals(String.class)) { - try { - Object args[] = { }; - String tempTip = (String)(meth.invoke(target, args)); - result = tempTip; - if (stripToolTipToFirstPoint) { - int ci = tempTip.indexOf('.'); - if (ci > 0) result = tempTip.substring(0, ci); - } - } catch (Exception ex) { - } - break; - } - } - } // end for looking for tiptext - if (toHTMLLen > 0) return StringTools.toHTML(result, toHTMLLen); - else return result; - } + public static String getToolTipText(String name, MethodDescriptor[] methods, Object target, boolean stripToolTipToFirstPoint, int toHTMLLen) { + String result = ""; + String tipName = name + "TipText"; + for (int j = 0; j < methods.length; j++) { + String mname = methods[j].getDisplayName(); + Method meth = methods[j].getMethod(); + if (mname.equals(tipName)) { + if (meth.getReturnType().equals(String.class)) { + try { + Object args[] = {}; + String tempTip = (String) (meth.invoke(target, args)); + result = tempTip; + if (stripToolTipToFirstPoint) { + int ci = tempTip.indexOf('.'); + if (ci > 0) { + result = tempTip.substring(0, ci); + } + } + } catch (Exception ex) { + } + break; + } + } + } // end for looking for tiptext + if (toHTMLLen > 0) { + return StringTools.toHTML(result, toHTMLLen); + } else { + return result; + } + } /** * This method simply looks for an appropriate tool tip text diff --git a/src/eva2/gui/BigStringEditor.java b/src/eva2/gui/BigStringEditor.java index 08f05c3c..0dbc77b2 100644 --- a/src/eva2/gui/BigStringEditor.java +++ b/src/eva2/gui/BigStringEditor.java @@ -16,6 +16,8 @@ import java.beans.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; +import javax.swing.event.InternalFrameAdapter; +import javax.swing.event.InternalFrameEvent; /*==========================================================================* * CLASS DECLARATION @@ -40,11 +42,14 @@ public class BigStringEditor implements PropertyEditor { PropertyDialog frame = new PropertyDialog(editor,file, 50, 50); //frame.setSize(200, 200); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing (WindowEvent e) { - m_finished=true; - } - }); + frame.addInternalFrameListener(new InternalFrameAdapter() { + + @Override + public void internalFrameClosing(InternalFrameEvent e) { + super.internalFrameClosing(e); + m_finished = true; + } + }); while (m_finished==false) { try {Thread.sleep(1000);} catch (Exception e) { @@ -187,11 +192,14 @@ public class BigStringEditor implements PropertyEditor { PropertyDialog frame = new PropertyDialog(editor, "test", 50, 50); frame.setSize(200, 200); - frame.addWindowListener(new WindowAdapter() { - public void windowClosing (WindowEvent e) { - System.exit(0); - } - }); + frame.addInternalFrameListener(new InternalFrameAdapter() { + + @Override + public void internalFrameClosing(InternalFrameEvent e) { + super.internalFrameClosing(e); + System.exit(0); + } + }); // editor.setValue(so); } catch (Exception e) { e.printStackTrace(); diff --git a/src/eva2/gui/EvATabbedFrameMaker.java b/src/eva2/gui/EvATabbedFrameMaker.java index 66ab404c..3cfa16fd 100644 --- a/src/eva2/gui/EvATabbedFrameMaker.java +++ b/src/eva2/gui/EvATabbedFrameMaker.java @@ -1,17 +1,13 @@ package eva2.gui; /* - * Title: EvA2 - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 272 $ - * $Date: 2007-11-21 18:06:36 +0100 (Wed, 21 Nov 2007) $ - * $Author: mkron $ + * Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer + * Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher @version: $Revision: 272 + * $ $Date: 2007-11-21 18:06:36 +0100 (Wed, 21 Nov 2007) $ $Author: mkron $ + */ +/* + * ==========================================================================* IMPORTS + *========================================================================== */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -25,124 +21,280 @@ import javax.swing.JTabbedPane; import eva2.server.go.InterfaceNotifyOnInformers; import eva2.server.go.problems.InterfaceAdditionalPopulationInformer; +import java.awt.*; +import java.awt.event.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.*; +import javax.swing.plaf.TabbedPaneUI; +import javax.swing.plaf.basic.BasicButtonUI; /** - * Produces the main EvA2 frame and a tool bar instance. - * TODO This class should be removed alltogether. + * Produces the main EvA2 frame and a tool bar instance. TODO This class should be removed + * alltogether. */ public class EvATabbedFrameMaker implements Serializable, PanelMaker, InterfaceNotifyOnInformers { - private static final long serialVersionUID = 2637376545826821423L; - private ArrayList pmContainer = null; - private JExtToolBar m_BarStandard; - EvAModuleButtonPanelMaker butPanelMkr=null; - - public EvATabbedFrameMaker() { - pmContainer = null; - } - - public void addPanelMaker(PanelMaker pm) { - if (pmContainer==null) pmContainer = new ArrayList(2); - pmContainer.add(pm); - } - public JPanel makePanel() { - JPanel m_SuperPanel = new JPanel(); - m_SuperPanel.setLayout(new GridBagLayout()); - GridBagConstraints gbconst = new GridBagConstraints(); - gbconst.fill = GridBagConstraints.BOTH; - gbconst.weightx = 1; - gbconst.weighty = 1; - gbconst.gridwidth = GridBagConstraints.REMAINDER; + private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); + private static final long serialVersionUID = 2637376545826821423L; + private ArrayList pmContainer = null; + private JExtToolBar extToolBar; + EvAModuleButtonPanelMaker butPanelMkr = null; + private JTabbedPane tabbedPane; - final JTabbedPane m_MainPanel = new JTabbedPane(); -// m_MainPanel.addChangeListener(new ChangeListener() { -// /* -// * This listener was added to catch the switch to the statistics panel. In that event, -// * the stats selection string may have to be updated. -// */ -// public void stateChanged(ChangeEvent e) { -//// System.out.println("AAAA " + e.toString()); -// if (m_MainPanel.getSelectedIndex()==1) { -// // the statistics panel is being activated! -//// System.out.println(guiContainer); -// // the third object should be the statistics panel, refer to GenericModuleAdapter -// JParaPanel statsPan = (JParaPanel) guiContainer.get(2); -//// System.out.println(statsPan.m_LocalParameter); -//// statsPan.m_Editor.setValue(statsPan.m_Editor.getValue()); // really update the contents of the stats panel -- - // this is now done in a cleaner way using this class as a listener from AbstractGOParameters -// } -// }}); - - m_BarStandard = new JExtToolBar(); - m_BarStandard.setFloatable(false); - - for (int i=0;i(2); + } + pmContainer.add(pm); + } - public void refreshPanels() { - for (PanelMaker jpp : pmContainer) { - if (jpp instanceof JParaPanel) ((JParaPanel)jpp).m_Editor.setValue(((JParaPanel)jpp).m_Editor.getValue()); - } - } - - public void setInformers( - List informers) { - // if the informers have changed, update the GUI element which displays them - try { - JParaPanel statsPan = getStatsPanel(); - if (statsPan.m_Editor!=null) { - statsPan.m_Editor.setValue(statsPan.m_Editor.getValue()); // really update the contents of the stats panel -// System.out.println("OOO setting informers to stats panel succeeded!"); - } - } catch(Exception e) { - System.err.println("Failed to update statistics panel from " + this.getClass()); - System.err.println(e.getMessage()); - e.printStackTrace(System.err); - } - } + public JPanel makePanel() { + JPanel tabControlPanel = new JPanel(new GridBagLayout()); - public JParaPanel getGOPanel() { - try { - JParaPanel sP = (JParaPanel) pmContainer.get(1); - return sP; - } catch(Exception e) { - System.err.println("Failed to get GO panel from " + this.getClass()); - } - return null; - } - - public JParaPanel getStatsPanel() { - try { - JParaPanel sP = (JParaPanel) pmContainer.get(2); - return sP; - } catch(Exception e) { - System.err.println("Failed to get statistics panel from " + this.getClass()); - } - return null; - } + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.fill = GridBagConstraints.VERTICAL; + gbConstraints.gridy = 0; + + tabbedPane = new JTabbedPane(); + tabbedPane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); + //tabbedPane.setUI(new eva2.gui.utils.CustomTabbedPaneUI()); + tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + + + /* This toolbar will hold the closed tabs */ + JToolBar tabToolBar = new JToolBar(JToolBar.VERTICAL); + tabToolBar.setFloatable(false); + + /* ToDo: The control buttons shouldn't be added here.. */ + extToolBar = new JExtToolBar(); + extToolBar.setFloatable(false); + + for (PanelMaker element : pmContainer) { + JComponent panel = element.makePanel(); + if (element instanceof EvAModuleButtonPanelMaker) { + extToolBar.add(panel); + butPanelMkr = (EvAModuleButtonPanelMaker) element; + } else if (element instanceof JParaPanel) { + tabbedPane.addTab(((JParaPanel) element).getName(), panel); + } + } + + for (int i = 0; i < tabbedPane.getTabCount(); i++) { + tabbedPane.setTabComponentAt(i, new ClosableTabComponent(tabbedPane, tabToolBar)); + } + + gbConstraints.weighty = 1.0; + gbConstraints.gridx = 0; + tabControlPanel.add(tabToolBar, gbConstraints); + gbConstraints.gridx = 1; + tabControlPanel.add(tabbedPane, gbConstraints); + tabbedPane.validate(); + return tabControlPanel; + } + + /** + * @deprecated + * @return The toolbar with control buttons + */ + public JExtToolBar getToolBar() { + return extToolBar; + } + + /** + * Emulate pressing the start button. + */ + public void onUserStart() { + if (butPanelMkr != null) { + butPanelMkr.onUserStart(); + } else { + System.err.println("Error: button panel was null (EvATabbedFrameMaker)"); + } + } + + public void refreshPanels() { + for (PanelMaker jpp : pmContainer) { + if (jpp instanceof JParaPanel) { + ((JParaPanel) jpp).propertyEditor.setValue(((JParaPanel) jpp).propertyEditor.getValue()); + } + } + } + + public void setInformers(List informers) { + // if the informers have changed, update the GUI element which displays them + try { + JParaPanel statsPan = getStatsPanel(); + if (statsPan.propertyEditor != null) { + // really update the contents of the stats panel + statsPan.propertyEditor.setValue(statsPan.propertyEditor.getValue()); + } + } catch (Exception e) { + System.err.println("Failed to update statistics panel from " + this.getClass()); + System.err.println(e.getMessage()); + e.printStackTrace(System.err); + } + } + + public JParaPanel getGOPanel() { + try { + JParaPanel sP = (JParaPanel) pmContainer.get(1); + return sP; + } catch (Exception e) { + System.err.println("Failed to get GO panel from " + this.getClass()); + } + return null; + } + + public JParaPanel getStatsPanel() { + try { + JParaPanel sP = (JParaPanel) pmContainer.get(2); + return sP; + } catch (Exception e) { + System.err.println("Failed to get statistics panel from " + this.getClass()); + } + return null; + } } + +/** + * Component to be used as tabComponent; + * Contains a JLabel to show the text and + * a JButton to close the tab it belongs to + */ +class ClosableTabComponent extends JPanel { + private final JTabbedPane pane; + private final JToolBar toolBar; + + public ClosableTabComponent(final JTabbedPane pane, final JToolBar toolBar) { + super(new FlowLayout(FlowLayout.LEADING, 0, 0)); + + if (pane == null) { + throw new NullPointerException("TabbedPane is null"); + } + this.pane = pane; + this.toolBar = toolBar; + this.toolBar.setVisible(false); + setOpaque(false); + + //make JLabel read titles from JTabbedPane + JLabel label = new JLabel() { + public String getText() { + int index = pane.indexOfTabComponent(ClosableTabComponent.this); + if (index != -1) { + return pane.getTitleAt(index); + } + return null; + } + }; + + add(label); + //add more space between the label and the button + label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); + //tab button + JButton button = new TabButton(); + add(button); + //add more space to the top of the component + setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); + } + + private class TabButton extends JButton implements ActionListener { + public TabButton() { + int size = 17; + setPreferredSize(new Dimension(size, size)); + setToolTipText("Hide this Tab"); + //Make the button looks the same for all Laf's + setUI(new BasicButtonUI()); + //Make it transparent + setContentAreaFilled(false); + //No need to be focusable + setFocusable(false); + setBorder(BorderFactory.createEtchedBorder()); + setBorderPainted(false); + //Making nice rollover effect + //we use the same listener for all buttons + addMouseListener(buttonMouseListener); + setRolloverEnabled(true); + //Close the proper tab by clicking the button + addActionListener(this); + } + + public void actionPerformed(ActionEvent e) { + int i = pane.indexOfTabComponent(ClosableTabComponent.this); + if (i != -1) { + final String tabTitle = pane.getTitleAt(i); + final Component tabPane = pane.getComponentAt(i); + final int tabPosition = i; + pane.remove(i); + if(pane.getTabCount() == 0) { + pane.setVisible(false); + } + /* Create a button to be shown in the ToolBar */ + JButton tabButton = new JButton(tabTitle); + /* Rotate it by -90° */ + tabButton.setUI(new eva2.gui.utils.VerticalButtonUI(-90)); + tabButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + /* Add the Tab Panel again */ + pane.insertTab(tabTitle, null, tabPane, "", tabPosition); + pane.setVisible(true); + /* Remove the Button */ + toolBar.remove((Component)e.getSource()); + /* If the Button was the last one, hide ToolBar again */ + if(toolBar.getComponentCount() == 0) { + toolBar.setVisible(false); + } + } + }); + /* Add it to the ToolBar */ + if(!toolBar.isVisible()) { + toolBar.setVisible(true); + } + toolBar.add(tabButton); + } + } + + //we don't want to update UI for this button + public void updateUI() { + } + + //paint the cross + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + //shift the image for pressed buttons + if (getModel().isPressed()) { + g2.translate(1, 1); + } + g2.setStroke(new BasicStroke(2)); + g2.setColor(Color.BLACK); + int delta = 6; + g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); + g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); + g2.dispose(); + } + } + + private final static MouseListener buttonMouseListener = new MouseAdapter() { + public void mouseEntered(MouseEvent e) { + Component component = e.getComponent(); + if (component instanceof AbstractButton) { + AbstractButton button = (AbstractButton) component; + button.setBorderPainted(true); + } + } + + public void mouseExited(MouseEvent e) { + Component component = e.getComponent(); + if (component instanceof AbstractButton) { + AbstractButton button = (AbstractButton) component; + button.setBorderPainted(false); + } + } + }; +} \ No newline at end of file diff --git a/src/eva2/gui/ExtDesktopManager.java b/src/eva2/gui/ExtDesktopManager.java index 1c7ea1cb..1084673c 100644 --- a/src/eva2/gui/ExtDesktopManager.java +++ b/src/eva2/gui/ExtDesktopManager.java @@ -9,62 +9,79 @@ package eva2.gui; * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ * $Author: streiche $ */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -import javax.swing.*; -import java.awt.*; +import java.awt.Component; +import java.awt.Event; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.DefaultDesktopManager; +import javax.swing.JInternalFrame; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + /** * */ -public class ExtDesktopManager extends DefaultDesktopManager{ - int WINDOW_LIST_START; - public final static String INDEX = "Index"; - public final static String FRAME = "Frame"; - private JInternalFrame activeFrame = null; - private JExtDesktopPane desktop; - public ExtDesktopManager(JExtDesktopPane desktop){ - this.desktop = desktop; - } - public void activateFrame(JInternalFrame f){ - super.activateFrame(f); - activeFrame = f; - } - public void deactivateFrame(JInternalFrame f){ - super.deactivateFrame(f); - if(activeFrame == f) activeFrame = null; - } - public JInternalFrame getActiveFrame(){ - return activeFrame; - } - public void closeFrame(JInternalFrame f){ - System.out.println("closed internalframe called"); - super.closeFrame(f); - int index = ((Integer)f.getClientProperty(INDEX)).intValue() + WINDOW_LIST_START - 1; - int i; - desktop.m_mnuWindow.remove(index); - for(i = index; i < Math.min(WINDOW_LIST_START + 9, desktop.m_mnuWindow.getItemCount()); i++){ - JMenuItem m = desktop.m_mnuWindow.getItem(i); - JInternalFrame frame = (JInternalFrame)m.getClientProperty(FRAME); - frame.putClientProperty(INDEX, new Integer(((Integer)frame.getClientProperty(INDEX)).intValue() - 1)); - int winIndex = i - WINDOW_LIST_START + 1; - m.setText((winIndex) + " " + frame.getTitle()); - m.setMnemonic((char)(0x30 + winIndex)); - m.setAccelerator(KeyStroke.getKeyStroke(0x30 + winIndex, Event.ALT_MASK)); +public class ExtDesktopManager extends DefaultDesktopManager { + + private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); + + int WINDOW_LIST_START; + public final static String INDEX = "Index"; + public final static String FRAME = "Frame"; + private JInternalFrame activeFrame = null; + private JExtDesktopPane desktop; + + public ExtDesktopManager(JExtDesktopPane desktop) { + this.desktop = desktop; } - if(f.isSelected()){ - Component tmp = null; - boolean found = false; - for(i = 0; i < desktop.getComponentCount() && !found; i++){ - tmp = desktop.getComponent(i); - if(tmp instanceof JInternalFrame) found = true; - } - - if(found) desktop.selectFrame((JInternalFrame)tmp); - else activeFrame = null; + public void activateFrame(JInternalFrame f) { + super.activateFrame(f); + activeFrame = f; + } + + public void deactivateFrame(JInternalFrame f) { + super.deactivateFrame(f); + if (activeFrame == f) { + activeFrame = null; + } + } + + public JInternalFrame getActiveFrame() { + return activeFrame; + } + + public void closeFrame(JInternalFrame internalFrame) { + LOGGER.log(Level.FINE, "Closing Internal Frame: {0}", internalFrame.getTitle()); + super.closeFrame(internalFrame); + int index = ((Integer) internalFrame.getClientProperty(INDEX)).intValue() + WINDOW_LIST_START - 1; + int i; + desktop.m_mnuWindow.remove(index); + for (i = index; i < Math.min(WINDOW_LIST_START + 9, desktop.m_mnuWindow.getItemCount()); i++) { + JMenuItem m = desktop.m_mnuWindow.getItem(i); + JInternalFrame frame = (JInternalFrame) m.getClientProperty(FRAME); + frame.putClientProperty(INDEX, new Integer(((Integer) frame.getClientProperty(INDEX)).intValue() - 1)); + int winIndex = i - WINDOW_LIST_START + 1; + m.setText((winIndex) + " " + frame.getTitle()); + m.setMnemonic((char) (0x30 + winIndex)); + m.setAccelerator(KeyStroke.getKeyStroke(0x30 + winIndex, Event.ALT_MASK)); + } + + if (internalFrame.isSelected()) { + Component tmp = null; + boolean found = false; + for (i = 0; i < desktop.getComponentCount() && !found; i++) { + tmp = desktop.getComponent(i); + if (tmp instanceof JInternalFrame) { + found = true; + } + } + + if (found) { + desktop.selectFrame((JInternalFrame) tmp); + } else { + activeFrame = null; + } + } } - } } - - diff --git a/src/eva2/gui/GOEPanel.java b/src/eva2/gui/GOEPanel.java index 4330fe90..a5a62adf 100644 --- a/src/eva2/gui/GOEPanel.java +++ b/src/eva2/gui/GOEPanel.java @@ -1,10 +1,11 @@ package eva2.gui; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.Window; +import eva2.server.go.tools.FileTools; +import eva2.tools.BasicResourceLoader; +import eva2.tools.EVAHELP; +import eva2.tools.SerializedObject; +import eva2.tools.jproxy.RMIProxyLocal; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -18,370 +19,437 @@ import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import java.util.Vector; - -import javax.swing.BorderFactory; -import javax.swing.DefaultComboBoxModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; +import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxRenderer; -import eva2.server.go.tools.FileTools; -import eva2.tools.EVAHELP; -import eva2.tools.SerializedObject; -import eva2.tools.jproxy.RMIProxyLocal; /** -* -*/ + * + */ public class GOEPanel extends JPanel implements ItemListener { - private Object m_Backup; - private PropertyChangeSupport m_Support; - private static boolean TRACE = false; - - /** The chooser component */ - private JComboBox m_ObjectChooser; - /** The component that performs classifier customization */ - private PropertySheetPanel m_ChildPropertySheet; - /** The model containing the list of names to select from */ - private DefaultComboBoxModel m_ObjectNames; - /** Open object from disk */ - private JButton openButton; - /** Save object to disk */ - private JButton saveButton; - /** ok button */ - private JButton okayButton; - /** cancel button */ - private JButton cancelButton; - /** edit source button */ -// private JButton m_editSourceBut; - /** Creates the GUI editor component */ + + private Object backupObject; + private PropertyChangeSupport propChangeSupport; + private static boolean TRACE = false; + /** + * The chooser component + */ + private JComboBox objectChooser; + /** + * The component that performs classifier customization + */ + private PropertySheetPanel propertySheetPanel; + /** + * The model containing the list of names to select from + */ + private DefaultComboBoxModel comboBoxModel; + /** + * Open object from disk + */ + private JButton openButton; + /** + * Save object to disk + */ + private JButton saveButton; + /** + * ok button + */ + private JButton okayButton; + /** + * cancel button + */ + private JButton cancelButton; + /** + * Creates the GUI editor component + */ // private Vector m_ClassesLongName; - private GenericObjectEditor genericObjectEditor = null; - private boolean withComboBoxToolTips = true; // should tool tips for the combo box be created? - private int tipMaxLen = 100; // maximum length of tool tip + private GenericObjectEditor genericObjectEditor = null; + private boolean withComboBoxToolTips = true; // should tool tips for the combo box be created? + private int tipMaxLen = 100; // maximum length of tool tip - /** - * - */ - public GOEPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe) { - this(target, backup, support, goe, false); - } - - /** - * - */ - public GOEPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe, boolean withCancel) { - Object m_Object = target; - m_Backup = backup; - m_Support = support; - genericObjectEditor = goe; - -// System.out.println("GOEPanel.Constructor !! " + this); - try { - if (!(Proxy.isProxyClass(m_Object.getClass()))) m_Backup = copyObject(m_Object); - } catch(OutOfMemoryError err) { - m_Backup=null; - System.gc(); - System.err.println("Could not create backup object: not enough memory (GOEPanel backup of " + m_Object + ")"); + /** + * + */ + public GOEPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe) { + this(target, backup, support, goe, false); + } + + /** + * + */ + public GOEPanel(Object target, Object backup, PropertyChangeSupport support, GenericObjectEditor goe, boolean withCancel) { + Object m_Object = target; + backupObject = backup; + propChangeSupport = support; + genericObjectEditor = goe; + + try { + if (!(Proxy.isProxyClass(m_Object.getClass()))) { + backupObject = copyObject(m_Object); + } + } catch (OutOfMemoryError err) { + backupObject = null; + System.gc(); + System.err.println("Could not create backup object: not enough memory (GOEPanel backup of " + m_Object + ")"); + } + comboBoxModel = new DefaultComboBoxModel(new String[0]); + objectChooser = new JComboBox(comboBoxModel); + objectChooser.setEditable(false); + propertySheetPanel = new PropertySheetPanel(); + propertySheetPanel.addPropertyChangeListener( + new PropertyChangeListener() { + + public void propertyChange(final PropertyChangeEvent event) { + propChangeSupport.firePropertyChange("", backupObject, genericObjectEditor.getValue()); + } + }); + openButton = makeIconButton("resources/images/Open16.gif", "Open"); + openButton.setToolTipText("Load a configured object"); + openButton.setEnabled(true); + openButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent event) { + Object object = FileTools.openObject(openButton, genericObjectEditor.getClassType()); + if (object != null) { + // setValue takes care of: Making sure obj is of right type, + // and firing property change. + genericObjectEditor.setValue(object); + // Need a second setValue to get property values filled in OK. + // Not sure why. + genericObjectEditor.setValue(object); // <- Hannes ?!?!? + } + } + }); + + saveButton = makeIconButton("resources/images/Save16.gif", "Save"); + saveButton.setToolTipText("Save the current configured object"); + saveButton.setEnabled(true); + saveButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent event) { + FileTools.saveObjectWithFileChooser(saveButton, genericObjectEditor.getValue()); + } + }); + + okayButton = new JButton("OK"); + okayButton.setEnabled(true); + okayButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent event) { + backupObject = copyObject(genericObjectEditor.getValue()); + + updateClassType(); + updateChooser(); + updateChildPropertySheet(); + + /* + * ToDo: This is really ugly. Find a way to make this better. + */ + Container container = GOEPanel.this.getParent(); + while (!(container instanceof JDialog)) { + container = container.getParent(); + } + ((JDialog) container).dispose(); + } + }); + + cancelButton = new JButton("Cancel"); + cancelButton.setEnabled(true); + cancelButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent event) { + if (backupObject != null) { + // TODO m_goe.setObject(m_Object); + genericObjectEditor.setValue(copyObject(backupObject)); + updateClassType(); + updateChooser(); + updateChildPropertySheet(); + } + /* + * ToDo: This is really ugly. Find a way to make this better. + */ + Container container = GOEPanel.this.getParent(); + while (!(container instanceof JDialog)) { + container = container.getParent(); + } + ((JDialog) container).dispose(); + } + }); + + setLayout(new GridBagLayout()); + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.gridx = 0; + gbConstraints.gridy = 0; + add(objectChooser, gbConstraints); + + gbConstraints.weightx = 1.0; + gbConstraints.weighty = 1.0; + gbConstraints.gridy = 1; + gbConstraints.gridheight = GridBagConstraints.RELATIVE; + gbConstraints.fill = GridBagConstraints.BOTH; + add(propertySheetPanel, gbConstraints); + + JToolBar buttonBar = new JToolBar(); + buttonBar.setRollover(true); + buttonBar.setFloatable(false); + buttonBar.add(openButton); + buttonBar.add(saveButton); + + /* Add spacer to the end of the line */ + buttonBar.add(Box.createHorizontalGlue()); + + if (withCancel) { + buttonBar.add(cancelButton); + } + buttonBar.add(okayButton); + + gbConstraints.weightx = 0.0; + gbConstraints.weighty = 0.0; + gbConstraints.gridy = 2; + gbConstraints.anchor = GridBagConstraints.LINE_START; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + add(buttonBar, gbConstraints); + + if (genericObjectEditor.getClassType() != null) { + updateClassType(); + updateChooser(); + updateChildPropertySheet(); + } + objectChooser.addItemListener(this); + } + + /** + * This method is duplicated from EvAModuleButtonPanelMaker. + * ToDo: Refactor this. + * + * @param iconSrc + * @param title + * @return + */ + private JButton makeIconButton(final String iconSrc, final String title) { + JButton newButton; + byte[] bytes; + bytes = BasicResourceLoader.instance().getBytesFromResourceLocation(iconSrc, false); + if (bytes == null) { + newButton = new JButton(title); + } else { + newButton = new JButton(new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes))); } - m_ObjectNames = new DefaultComboBoxModel(new String [0]); - m_ObjectChooser = new JComboBox(m_ObjectNames); - m_ObjectChooser.setEditable(false); - m_ChildPropertySheet = new PropertySheetPanel(); - m_ChildPropertySheet.addPropertyChangeListener( - new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - if (TRACE) System.out.println("GOE Property Change Listener: " + evt); - m_Support.firePropertyChange("", m_Backup, genericObjectEditor.getValue()); - } - }); - openButton = new JButton("Open"); - openButton.setToolTipText("Load a configured object"); - openButton.setEnabled(true); - openButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - Object object = FileTools.openObject(openButton, genericObjectEditor.getClassType()); -// Object object = openObject(); - if (object != null) { - // setValue takes care of: Making sure obj is of right type, - // and firing property change. - genericObjectEditor.setValue(object); - // Need a second setValue to get property values filled in OK. - // Not sure why. - genericObjectEditor.setValue(object); // <- Hannes ?!?!? - } - } - }); - - saveButton = new JButton("Save"); - saveButton.setToolTipText("Save the current configured object"); - saveButton.setEnabled(true); - saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - FileTools.saveObjectWithFileChooser(saveButton, genericObjectEditor.getValue()); -// saveObject(m_goe.getValue()); - } - }); - - okayButton = new JButton("OK"); - okayButton.setEnabled(true); - okayButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - m_Backup = copyObject(genericObjectEditor.getValue()); -// System.out.println("Backup is now " + BeanInspector.toString(m_Backup)); - if ((getTopLevelAncestor() != null) && (getTopLevelAncestor() instanceof Window)) { - Window w = (Window) getTopLevelAncestor(); - w.dispose(); - } - } - }); - - cancelButton = new JButton("Cancel"); - cancelButton.setEnabled(true); - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (m_Backup != null) { -// m_Object = copyObject(m_Backup); - // TODO m_goe.setObject(m_Object); -// System.out.println("Backup was " + BeanInspector.toString(m_Backup)); - genericObjectEditor.setValue(copyObject(m_Backup)); - updateClassType(); - updateChooser(); - updateChildPropertySheet(); - } - if ((getTopLevelAncestor() != null) - && (getTopLevelAncestor() instanceof Window)) { - Window w = (Window) getTopLevelAncestor(); - w.dispose(); - } - } - }); - - setLayout(new BorderLayout()); - add(m_ObjectChooser, BorderLayout.NORTH); // important - //add(m_ChildPropertySheet, BorderLayout.CENTER); - // Since we resize to the size of the property sheet, a scrollpane isn't - // typically needed (O Rly?) - JScrollPane myScrollPane =new JScrollPane(m_ChildPropertySheet,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - - myScrollPane.setBorder(null); - add(myScrollPane, BorderLayout.CENTER); - - - JPanel okcButs = new JPanel(); - okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - okcButs.setLayout(new GridLayout(1, 4, 5, 5)); - okcButs.add(openButton); - okcButs.add(saveButton); -// okcButs.add(m_editSourceBut); - if (withCancel) okcButs.add(cancelButton); - okcButs.add(okayButton); - - add(okcButs, BorderLayout.SOUTH); - - if (genericObjectEditor.getClassType() != null) { - updateClassType(); - updateChooser(); - updateChildPropertySheet(); - } - m_ObjectChooser.addItemListener(this); + return newButton; } - public void setEnabledOkCancelButtons(boolean enabled) { - okayButton.setEnabled(enabled); - cancelButton.setEnabled(enabled); - } - - /** - * Makes a copy of an object using serialization - * @param source the object to copy - * @return a copy of the source object - */ - protected Object copyObject(Object source) { - Object result = null; - try { + public void setEnabledOkCancelButtons(boolean enabled) { + okayButton.setEnabled(enabled); + cancelButton.setEnabled(enabled); + } + + /** + * Makes a copy of an object using serialization. + * + * @param source the object to copy + * @return a copy of the source object + */ + protected Object copyObject(Object source) { + Object result = null; + try { // System.out.println("Copying " + BeanInspector.toString(source)); - SerializedObject so = new SerializedObject(source); - result = so.getObject(); - so=null; - } catch (Exception ex) { - System.err.println("GenericObjectEditor: Problem making backup object"); - System.err.println(source.getClass().getName()); - ex.printStackTrace(); - } - return result; - } + SerializedObject so = new SerializedObject(source); + result = so.getObject(); + so = null; + } catch (Exception ex) { + System.err.println("GenericObjectEditor: Problem making backup object"); + System.err.println(source.getClass().getName()); + ex.printStackTrace(); + } + return result; + } - /** - * This is used to hook an action listener to the ok button - * @param a The action listener. - */ - public void addOkListener(ActionListener a) { - okayButton.addActionListener(a); - } + /** + * This is used to hook an action listener to the ok button. + * + * @param a The action listener. + */ + public void addOkListener(ActionListener a) { + okayButton.addActionListener(a); + } - /** - * This is used to hook an action listener to the cancel button - * @param a The action listener. - */ - public void addCancelListener(ActionListener a) { - cancelButton.addActionListener(a); - } + /** + * This is used to hook an action listener to the cancel button + * + * @param a The action listener. + */ + public void addCancelListener(ActionListener a) { + cancelButton.addActionListener(a); + } - /** - * This is used to remove an action listener from the ok button - * @param a The action listener - */ - public void removeOkListener(ActionListener a) { - okayButton.removeActionListener(a); - } + /** + * This is used to remove an action listener from the ok button + * + * @param a The action listener + */ + public void removeOkListener(ActionListener a) { + okayButton.removeActionListener(a); + } - /** - * This is used to remove an action listener from the cancel button - * @param a The action listener - */ - public void removeCancelListener(ActionListener a) { - cancelButton.removeActionListener(a); - } - - public void setTarget(Object o) { - m_ChildPropertySheet.setTarget(o); - } - - /** - * - */ - protected void updateClassType() { - if (TRACE) System.out.println("# updating class "+genericObjectEditor.getClassType().getName()); - Vector classesLongNames; - ArrayList> instances = new ArrayList>(5); - if (Proxy.isProxyClass(genericObjectEditor.getClassType())) { - if (TRACE) System.out.println("PROXY! original was " + ((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)genericObjectEditor.getValue()))).getOriginalClass().getName()); - classesLongNames = new Vector(GenericObjectEditor.getClassesFromProperties(((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)genericObjectEditor.getValue()))).getOriginalClass().getName(), null)); - } else { - classesLongNames = new Vector(GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances)); - } - if (classesLongNames.size() > 1) { - m_ObjectChooser.setModel(new DefaultComboBoxModel(classesLongNames)); - if (withComboBoxToolTips) m_ObjectChooser.setRenderer(new ToolTipComboBoxRenderer(collectComboToolTips(instances, tipMaxLen) )); - add(m_ObjectChooser, BorderLayout.NORTH); - } else remove(m_ObjectChooser); - if (TRACE) System.out.println("# done updating class "+genericObjectEditor.getClassType().getName()); - } + /** + * This is used to remove an action listener from the cancel button + * + * @param a The action listener + */ + public void removeCancelListener(ActionListener a) { + cancelButton.removeActionListener(a); + } - private String[] collectComboToolTips(List> instances, int maxLen) { - String[] tips = new String[instances.size()]; - for (int i=0; i classesLongNames; + ArrayList> instances = new ArrayList>(5); + if (Proxy.isProxyClass(genericObjectEditor.getClassType())) { + classesLongNames = new Vector(GenericObjectEditor.getClassesFromProperties(((RMIProxyLocal) Proxy.getInvocationHandler(((Proxy) genericObjectEditor.getValue()))).getOriginalClass().getName(), null)); + } else { + classesLongNames = new Vector(GenericObjectEditor.getClassesFromProperties(genericObjectEditor.getClassType().getName(), instances)); + } + if (classesLongNames.size() > 1) { + objectChooser.setModel(new DefaultComboBoxModel(classesLongNames)); + if (withComboBoxToolTips) { + objectChooser.setRenderer(new ToolTipComboBoxRenderer(collectComboToolTips(instances, tipMaxLen))); + } + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.gridx = 0; + gbConstraints.gridy = 0; + add(objectChooser, gbConstraints); + } else { + remove(objectChooser); + } + } + private String[] collectComboToolTips(List> instances, int maxLen) { + String[] tips = new String[instances.size()]; + for (int i = 0; i < tips.length; i++) { + tips[i] = null; + Class[] classParams = new Class[]{}; + try { + String tip = null; + Method giMeth = instances.get(i).getDeclaredMethod("globalInfo", classParams); + if (Modifier.isStatic(giMeth.getModifiers())) { + tip = (String) giMeth.invoke(null, (Object[]) null); + } + if (tip != null) { + if (tip.length() <= maxLen) { + tips[i] = tip; + } else { + tips[i] = tip.substring(0, maxLen - 2) + ".."; + } + } + } catch (Exception e) { + } + } + return tips; + } - /** Updates the child property sheet, and creates if needed */ - public void updateChildPropertySheet() { - //System.err.println("GOE::updateChildPropertySheet()"); - // Set the object as the target of the propertysheet - m_ChildPropertySheet.setTarget(genericObjectEditor.getValue()); - // Adjust size of containing window if possible - if ((getTopLevelAncestor() != null) - && (getTopLevelAncestor() instanceof Window)) { - ((Window) getTopLevelAncestor()).pack(); - } - } + protected void updateChooser() { + String objectName = /* + * EVAHELP.cutClassName + */ (genericObjectEditor.getValue().getClass().getName()); + boolean found = false; + for (int i = 0; i < comboBoxModel.getSize(); i++) { + if (TRACE) { + System.out.println("in updateChooser: looking at " + (String) comboBoxModel.getElementAt(i)); + } + if (objectName.equals((String) comboBoxModel.getElementAt(i))) { + found = true; + break; + } + } + if (!found) { + comboBoxModel.addElement(objectName); + } + objectChooser.getModel().setSelectedItem(objectName); + } - /** - * When the chooser selection is changed, ensures that the Object - * is changed appropriately. - * - * @param e a value of type 'ItemEvent' - */ + /** + * Updates the child property sheet, and creates if needed + */ + public void updateChildPropertySheet() { + // Set the object as the target of the propertysheet + propertySheetPanel.setTarget(genericObjectEditor.getValue()); + // Adjust size of containing window if possible + if ((getTopLevelAncestor() != null) + && (getTopLevelAncestor() instanceof Window)) { + ((Window) getTopLevelAncestor()).pack(); + } + } - public void itemStateChanged(ItemEvent e) { - String className = (String)m_ObjectChooser.getSelectedItem(); + /** + * When the chooser selection is changed, ensures that the Object is changed appropriately. + * + * @param e a value of type 'ItemEvent' + */ + public void itemStateChanged(ItemEvent e) { + String className; - if (TRACE) System.out.println("Event-Quelle: " + e.getSource().toString()); - if ((e.getSource() == m_ObjectChooser) && (e.getStateChange() == ItemEvent.SELECTED)){ - className = (String)m_ObjectChooser.getSelectedItem(); - try { - if (TRACE) System.out.println(className); -// Object n = (Object)Class.forName(className, true, this.getClass().getClassLoader()).newInstance(); - Object n = (Object)Class.forName(className).newInstance(); - genericObjectEditor.setValue(n); - // TODO ? setObject(n); - } catch (Exception ex) { - System.err.println("Exeption in itemStateChanged "+ex.getMessage()); - System.err.println("Classpath is " + System.getProperty("java.class.path")); - ex.printStackTrace(); - m_ObjectChooser.hidePopup(); - m_ObjectChooser.setSelectedIndex(0); - JOptionPane.showMessageDialog(this, - "Could not create an example of\n" - + className + "\n" - + "from the current classpath. Is the resource folder at the right place?\nIs the class abstract or the default constructor missing?", - "GenericObjectEditor", - JOptionPane.ERROR_MESSAGE); - EVAHELP.getSystemPropertyString(); - } - } - } + if ((e.getSource() == objectChooser) && (e.getStateChange() == ItemEvent.SELECTED)) { + className = (String) objectChooser.getSelectedItem(); + try { + Object n = (Object) Class.forName(className).newInstance(); + genericObjectEditor.setValue(n); + // TODO ? setObject(n); + } catch (Exception ex) { + System.err.println("Exeption in itemStateChanged " + ex.getMessage()); + System.err.println("Classpath is " + System.getProperty("java.class.path")); + ex.printStackTrace(); + objectChooser.hidePopup(); + objectChooser.setSelectedIndex(0); + JOptionPane.showMessageDialog(this, + "Could not create an example of\n" + + className + "\n" + + "from the current classpath. Is the resource folder at the right place?\nIs the class abstract or the default constructor missing?", + "GenericObjectEditor", + JOptionPane.ERROR_MESSAGE); + EVAHELP.getSystemPropertyString(); + } + } + } } class ToolTipComboBoxRenderer extends BasicComboBoxRenderer { - private static final long serialVersionUID = -5781643352198561208L; - String[] toolTips = null; - public ToolTipComboBoxRenderer(String[] tips) { - super(); - toolTips=tips; - } + private static final long serialVersionUID = -5781643352198561208L; + String[] toolTips = null; - @Override - public Component getListCellRendererComponent(JList list, Object value, - int index, boolean isSelected, boolean cellHasFocus) { - if (isSelected) { - setBackground(list.getSelectionBackground()); - setForeground(list.getSelectionForeground()); - if ((toolTips!=null) && (index >= 0)) { - if (toolTips[index]!=null) list.setToolTipText(toolTips[index]); - } - } else { - setBackground(list.getBackground()); - setForeground(list.getForeground()); - } - setFont(list.getFont()); - setText((value == null) ? "" : value.toString()); - return this; - } + public ToolTipComboBoxRenderer(String[] tips) { + super(); + toolTips = tips; + } + + @Override + public Component getListCellRendererComponent(JList list, Object value, + int index, boolean isSelected, boolean cellHasFocus) { + if (isSelected) { + setBackground(list.getSelectionBackground()); + setForeground(list.getSelectionForeground()); + if ((toolTips != null) && (index >= 0)) { + if (toolTips[index] != null) { + list.setToolTipText(toolTips[index]); + } + } + } else { + setBackground(list.getBackground()); + setForeground(list.getForeground()); + } + setFont(list.getFont()); + setText((value == null) ? "" : value.toString()); + return this; + } } diff --git a/src/eva2/gui/GenericArrayEditor.java b/src/eva2/gui/GenericArrayEditor.java index 7644611d..b5eebc9b 100644 --- a/src/eva2/gui/GenericArrayEditor.java +++ b/src/eva2/gui/GenericArrayEditor.java @@ -1,34 +1,14 @@ package eva2.gui; /* - * Title: EvA2 - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 235 $ - * $Date: 2007-11-08 13:53:51 +0100 (Thu, 08 Nov 2007) $ - * $Author: mkron $ + * Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer + * Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher @version: $Revision: 235 + * $ $Date: 2007-11-08 13:53:51 +0100 (Thu, 08 Nov 2007) $ $Author: mkron $ */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.LayoutManager; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.InputEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; +import eva2.tools.EVAHELP; +import eva2.tools.SerializedObject; +import java.awt.*; +import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; @@ -36,729 +16,743 @@ import java.beans.PropertyEditor; import java.lang.reflect.Array; import java.util.LinkedList; import java.util.List; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.ListCellRenderer; -import javax.swing.ListModel; -import javax.swing.SwingConstants; +import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; -import eva2.tools.EVAHELP; -import eva2.tools.SerializedObject; -/*==========================================================================* - * CLASS DECLARATION - *==========================================================================*/ -public class GenericArrayEditor extends JPanel -implements PropertyEditor { - /** Handles property change notification */ - private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); - /** The label for when we can't edit that type */ - private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); - /** The list component displaying current values */ - private JList m_ElementList = new JList(); - /** The class of objects allowed in the array */ - private Class m_ElementClass = String.class; - /** The defaultlistmodel holding our data */ - private DefaultListModel m_ListModel; - /** The property editor for the class we are editing */ - private PropertyEditor m_ElementEditor; - /** Cheat to handle selectable lists as well */ - private PropertySelectableList selectableList = null; - /** Click this to delete the selected array values */ - private JButton m_DeleteBut = new JButton("Delete"); - /** list of additional buttons above the list */ - private List m_AdditionalUpperButtonList = new LinkedList(); - /** list of additional buttons below the list */ - private List m_AdditionalLowerButtonList = new LinkedList(); - - private JPanel additionalCenterPane = null; - - private List m_popupItemList = new LinkedList(); - private JButton m_AddBut = new JButton("Add"); - private JButton m_SetBut = new JButton("Set"); - private JButton m_SetAllBut = new JButton("Set all"); +public class GenericArrayEditor extends JPanel implements PropertyEditor { - private boolean withAddButton = true; - private boolean withSetButton = true; - private boolean withDeleteButton = true; - - private Component m_View = null; - /** Listens to buttons being pressed and taking the appropriate action */ - private ActionListener m_InnerActionListener = - new ActionListener() { - // - public void actionPerformed(ActionEvent e) { - boolean consistentView = true; // be optimistic... - if (m_View instanceof PropertyText) { // check consistency! - consistentView = ((PropertyText)m_View).checkConsistency(); - if (!consistentView) { -// System.err.println("Warning, inconsistent view!"); - ((PropertyText)m_View).updateFromEditor(); - } - } - if (e.getSource() == m_DeleteBut) { - int [] selected = m_ElementList.getSelectedIndices(); - if (selected != null) { - for (int i = selected.length-1; i>=0; i--) { - int current = selected[i]; - m_ListModel.removeElementAt(current); - if (m_ListModel.size() > current) { - m_ElementList.setSelectedIndex(current); - } - m_ElementList.setModel(m_ListModel); - } + /** + * Handles property change notification + */ + private PropertyChangeSupport m_Support = new PropertyChangeSupport(this); + /** + * The label for when we can't edit that type + */ + private JLabel m_Label = new JLabel("Can't edit", SwingConstants.CENTER); + /** + * The list component displaying current values + */ + private JList m_ElementList = new JList(); + /** + * The class of objects allowed in the array + */ + private Class m_ElementClass = String.class; + /** + * The defaultlistmodel holding our data + */ + private DefaultListModel m_ListModel; + /** + * The property editor for the class we are editing + */ + private PropertyEditor m_ElementEditor; + /** + * Cheat to handle selectable lists as well + */ + private PropertySelectableList selectableList = null; + /** + * Click this to delete the selected array values + */ + private JButton m_DeleteBut = new JButton("Delete"); + /** + * list of additional buttons above the list + */ + private List m_AdditionalUpperButtonList = new LinkedList(); + /** + * list of additional buttons below the list + */ + private List m_AdditionalLowerButtonList = new LinkedList(); + private JComponent additionalCenterComp = null; + private List m_popupItemList = new LinkedList(); + private JButton m_AddBut = new JButton("Add"); + private JButton m_SetBut = new JButton("Set"); + private JButton m_SetAllBut = new JButton("Set all"); + private boolean withAddButton = true; + private boolean withSetButton = true; + private boolean withDeleteButton = true; + private Component m_View = null; + /** + * Listens to buttons being pressed and taking the appropriate action + */ + private ActionListener m_InnerActionListener = + new ActionListener() { + // - if (selectableList!=null) selectableList.setObjects(modelToArray(selectableList.getObjects(), m_ListModel)); - m_Support.firePropertyChange("", null, null); - } - if (m_ElementList.getSelectedIndex() == -1) { - m_DeleteBut.setEnabled(false); - } - } else if (e.getSource() == m_AddBut) { - int selected = m_ElementList.getSelectedIndex(); - Object addObj = m_ElementEditor.getValue(); + public void actionPerformed(ActionEvent e) { + boolean consistentView = true; // be optimistic... + if (m_View instanceof PropertyText) { // check consistency! + consistentView = ((PropertyText) m_View).checkConsistency(); + if (!consistentView) { + ((PropertyText) m_View).updateFromEditor(); + } + } + if (e.getSource() == m_DeleteBut) { + int[] selected = m_ElementList.getSelectedIndices(); + if (selected != null) { + for (int i = selected.length - 1; i >= 0; i--) { + int current = selected[i]; + m_ListModel.removeElementAt(current); + if (m_ListModel.size() > current) { + m_ElementList.setSelectedIndex(current); + } + m_ElementList.setModel(m_ListModel); + } - // Make a full copy of the object using serialization - try { - SerializedObject so = new SerializedObject(addObj); - addObj = so.getObject(); - so=null; - if (selected != -1) { - m_ListModel.insertElementAt(addObj, selected); - } else { - m_ListModel.addElement(addObj); - } - m_ElementList.setModel(m_ListModel); - if (selectableList!=null) selectableList.setObjects(modelToArray(selectableList.getObjects(), m_ListModel)); - m_Support.firePropertyChange("", null, null); - } catch (Exception ex) { - JOptionPane.showMessageDialog(GenericArrayEditor.this,"Could not create an object copy",null,JOptionPane.ERROR_MESSAGE); - } - } else if (e.getSource() == m_SetAllBut) { - Object addObj = m_ElementEditor.getValue(); - for (int i=0; i=0 && (selected = 0 && (selected < m_ListModel.size())) { + try { + m_ListModel.setElementAt(new SerializedObject(addObj).getObject(), selected); + } catch (Exception e1) { + JOptionPane.showMessageDialog(GenericArrayEditor.this, "Could not create an object copy", null, JOptionPane.ERROR_MESSAGE); + } + m_Support.firePropertyChange("", null, null); + } + } + } + }; + + public void setAdditionalCenterPane(JComponent component) { + this.additionalCenterComp = component; + } + + private Object[] modelToArray(Object[] origArray, DefaultListModel listModel) { + Class objClass = origArray.getClass().getComponentType(); + Object[] os = (Object[]) java.lang.reflect.Array.newInstance(objClass, listModel.size()); // Object[] os= new Object[listModel.size()]; - for (int i=0; i=0 && (list.getCellBounds(index, index).contains(e.getPoint()))) { - PropertyPanel propPanel=null; - Component comp = gae.m_View; - if (comp instanceof PropertyPanel ) propPanel = (PropertyPanel) comp; - else System.err.println("Error, invalid property panel in " + this.getClass()); - ListModel dlm = list.getModel(); - Object item = dlm.getElementAt(index); - list.ensureIndexIsVisible(index); -// System.out.println(e); -// System.out.println("Double clicked on " + item); - propPanel.getEditor().setValue(item); - propPanel.showDialog(e.getXOnScreen(), e.getYOnScreen()); - propPanel=null; -// int x = getLocationOnScreen().x; -// int y = getLocationOnScreen().y; - -// if (m_PropertyDialog == null) -// m_PropertyDialog = new PropertyDialog(gae.m_ElementEditor, EVAHELP.cutClassName(gae.m_ElementEditor.getClass().getName()) , x, y); -// else { -// m_PropertyDialog.updateFrameTitle(gae.m_ElementEditor); -// m_PropertyDialog.set -// m_PropertyDialog.setVisible(false); -// m_PropertyDialog.setExtendedState(JFrame.NORMAL); -// m_PropertyDialog.setVisible(true); -// m_PropertyDialog.requestFocus(); -// } + public ActionJList(JList l, GenericArrayEditor genAE) { + list = l; + gae = genAE; + } - } - } - } - } - /* This class handles the creation of list cell renderers from the - * property editors. - */ - private class EditorListCellRenderer implements ListCellRenderer { - /** The class of the property editor for array objects */ - private Class m_EditorClass; - /** The class of the array values */ - private Class m_ValueClass; - /** - * Creates the list cell renderer. - * - * @param editorClass The class of the property editor for array objects - * @param valueClass The class of the array values - */ - public EditorListCellRenderer(Class editorClass, Class valueClass) { - m_EditorClass = editorClass; - m_ValueClass = valueClass; - } - /** - * Creates a cell rendering component. - * - * @param JList the list that will be rendered in - * @param Object the cell value - * @param int which element of the list to render - * @param boolean true if the cell is selected - * @param boolean true if the cell has the focus - * @return the rendering component - */ - public Component getListCellRendererComponent(final JList list, - final Object value, - final int index, - final boolean isSelected, - final boolean cellHasFocus) { - try { - final PropertyEditor e = (PropertyEditor)m_EditorClass.newInstance(); - if (e instanceof GenericObjectEditor) { - // ((GenericObjectEditor) e).setDisplayOnly(true); - ((GenericObjectEditor) e).setClassType(m_ValueClass); - } - e.setValue(value); - JPanel cellPanel = new JPanel() { -// return new JCheckBox("", isSelected) { -// public void paintComponent(Graphics g) { -// String name = (String)BeanInspector.callIfAvailable(value, "getName", new Object[]{}); -// if (name==null) setText(value.getClass().getSimpleName()); -// else setText(name); -// super.paintComponent(g); - public void paintComponent(Graphics g) { - Insets i = this.getInsets(); - Rectangle box = new Rectangle(i.left,i.top, - this.getWidth(), //- i.right, - this.getHeight() );//- i.bottom +20); - g.setColor(isSelected ? list.getSelectionBackground() : list.getBackground()); - g.fillRect(0, 0, this.getWidth(), this.getHeight()); - g.setColor(isSelected ? list.getSelectionForeground(): list.getForeground()); - e.paintValue(g, box); - } - public Dimension getPreferredSize() { - Font f = this.getFont(); - FontMetrics fm = this.getFontMetrics(f); - Dimension newPref = new Dimension(0, fm.getHeight()); - newPref.height = getFontMetrics(getFont()).getHeight() * 6 / 4; //6 / 4; - newPref.width = newPref.height * 6; //5 - return newPref; - } - }; - return cellPanel; - } catch (Exception ex) { - return null; - } - } - } + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + int index = list.locationToIndex(e.getPoint()); + // Check if the index is valid and if the indexed cell really contains the clicked point + if (index >= 0 && (list.getCellBounds(index, index).contains(e.getPoint()))) { + PropertyPanel propPanel = null; + Component comp = gae.m_View; + if (comp instanceof PropertyPanel) { + propPanel = (PropertyPanel) comp; + } else { + System.err.println("Error, invalid property panel in " + this.getClass()); + } + ListModel dlm = list.getModel(); + Object item = dlm.getElementAt(index); + list.ensureIndexIsVisible(index); + propPanel.getEditor().setValue(item); + propPanel.showDialog(e.getXOnScreen(), e.getYOnScreen()); + propPanel = null; + } + } + } + } + /* + * This class handles the creation of list cell renderers from the property editors. + */ - /** - * Updates the type of object being edited, so attempts to find an - * appropriate propertyeditor. - * - * @param o a value of type 'Object' - */ - private void updateEditorType(Object obj) { + private class EditorListCellRenderer implements ListCellRenderer { - // Determine if the current object is an array - m_ElementEditor = null; - m_ListModel = null; - m_View = null; - removeAll(); + /** + * The class of the property editor for array objects + */ + private Class m_EditorClass; + /** + * The class of the array values + */ + private Class m_ValueClass; - if ((obj != null) && (obj.getClass().isArray() || (obj instanceof PropertySelectableList))) { - Object arrayInstance = obj; - if (!(obj.getClass().isArray())) { - arrayInstance=((PropertySelectableList)obj).getObjects(); - selectableList = (PropertySelectableList)obj; - } else selectableList = null; - Class elementClass = arrayInstance.getClass().getComponentType(); - PropertyEditor editor = PropertyEditorProvider.findEditor(elementClass); - if (editor instanceof EnumEditor) editor.setValue(obj); - m_View = null; - ListCellRenderer lcr = new DefaultListCellRenderer(); - if (editor != null) { - if (editor instanceof GenericObjectEditor) { + /** + * Creates the list cell renderer. + * + * @param editorClass The class of the property editor for array objects + * @param valueClass The class of the array values + */ + public EditorListCellRenderer(Class editorClass, Class valueClass) { + m_EditorClass = editorClass; + m_ValueClass = valueClass; + } + + /** + * Creates a cell rendering component. + * + * @param JList the list that will be rendered in + * @param Object the cell value + * @param int which element of the list to render + * @param boolean true if the cell is selected + * @param boolean true if the cell has the focus + * @return the rendering component + */ + public Component getListCellRendererComponent(final JList list, + final Object value, + final int index, + final boolean isSelected, + final boolean cellHasFocus) { + try { + final PropertyEditor e = (PropertyEditor) m_EditorClass.newInstance(); + if (e instanceof GenericObjectEditor) { + // ((GenericObjectEditor) e).setDisplayOnly(true); + ((GenericObjectEditor) e).setClassType(m_ValueClass); + } + e.setValue(value); + JPanel cellPanel = new JPanel() { + + public void paintComponent(Graphics g) { + Insets i = this.getInsets(); + Rectangle box = new Rectangle(i.left, i.top, + this.getWidth(), //- i.right, + this.getHeight());//- i.bottom +20); + g.setColor(isSelected ? list.getSelectionBackground() : list.getBackground()); + g.fillRect(0, 0, this.getWidth(), this.getHeight()); + g.setColor(isSelected ? list.getSelectionForeground() : list.getForeground()); + e.paintValue(g, box); + } + + public Dimension getPreferredSize() { + Font f = this.getFont(); + FontMetrics fm = this.getFontMetrics(f); + Dimension newPref = new Dimension(0, fm.getHeight()); + newPref.height = getFontMetrics(getFont()).getHeight() * 6 / 4; //6 / 4; + newPref.width = newPref.height * 6; //5 + return newPref; + } + }; + return cellPanel; + } catch (Exception ex) { + return null; + } + } + } + + /** + * Updates the type of object being edited, so attempts to find an appropriate propertyeditor. + * + * @param o a value of type 'Object' + */ + private void updateEditorType(Object obj) { + + // Determine if the current object is an array + m_ElementEditor = null; + m_ListModel = null; + m_View = null; + removeAll(); + + if ((obj != null) && (obj.getClass().isArray() || (obj instanceof PropertySelectableList))) { + Object arrayInstance = obj; + if (!(obj.getClass().isArray())) { + arrayInstance = ((PropertySelectableList) obj).getObjects(); + selectableList = (PropertySelectableList) obj; + } else { + selectableList = null; + } + Class elementClass = arrayInstance.getClass().getComponentType(); + PropertyEditor editor = PropertyEditorProvider.findEditor(elementClass); + if (editor instanceof EnumEditor) { + editor.setValue(obj); + } + m_View = null; + ListCellRenderer lcr = new DefaultListCellRenderer(); + if (editor != null) { + if (editor instanceof GenericObjectEditor) { // ((GenericObjectEditor) editor).getCustomEditor(); - ((GenericObjectEditor) editor).setClassType(elementClass); - } - if (editor.isPaintable() && editor.supportsCustomEditor()) { - m_View = new PropertyPanel(editor); - lcr = new EditorListCellRenderer(editor.getClass(), elementClass); - } else if (editor.getTags() != null) { - m_View = new PropertyValueSelector(editor); - } else if (editor.getAsText() != null) { - m_View = new PropertyText(editor); - } - } - if (m_View == null) { - System.err.println("No property editor for class: " - + elementClass.getName()); - } else { - m_ElementEditor = editor; + ((GenericObjectEditor) editor).setClassType(elementClass); + } + if (editor.isPaintable() && editor.supportsCustomEditor()) { + m_View = new PropertyPanel(editor); + lcr = new EditorListCellRenderer(editor.getClass(), elementClass); + } else if (editor.getTags() != null) { + m_View = new PropertyValueSelector(editor); + } else if (editor.getAsText() != null) { + m_View = new PropertyText(editor); + } + } + if (m_View == null) { + System.err.println("No property editor for class: " + + elementClass.getName()); + } else { + m_ElementEditor = editor; - // Create the ListModel and populate it - m_ListModel = new DefaultListModel(); - m_ElementClass = elementClass; - for (int i = 0; i < Array.getLength(arrayInstance); i++) { - m_ListModel.addElement(Array.get(arrayInstance,i)); - } - m_ElementList.setCellRenderer(lcr); - m_ElementList.setModel(m_ListModel); - if (m_ListModel.getSize() > 0) { - m_ElementList.setSelectedIndex(0); - m_DeleteBut.setEnabled(true); - } else { - m_DeleteBut.setEnabled(false); - } + // Create the ListModel and populate it + m_ListModel = new DefaultListModel(); + m_ElementClass = elementClass; + for (int i = 0; i < Array.getLength(arrayInstance); i++) { + m_ListModel.addElement(Array.get(arrayInstance, i)); + } + m_ElementList.setCellRenderer(lcr); + m_ElementList.setModel(m_ListModel); + if (m_ListModel.getSize() > 0) { + m_ElementList.setSelectedIndex(0); + m_DeleteBut.setEnabled(true); + } else { + m_DeleteBut.setEnabled(false); + } - try { - if (m_ListModel.getSize() > 0) { - m_ElementEditor.setValue(m_ListModel.getElementAt(0)); - } else { - if (m_ElementEditor instanceof GenericObjectEditor) { - ((GenericObjectEditor)m_ElementEditor).setDefaultValue(); - } else { - if (m_ElementEditor.getValue()!=null) { - m_ElementEditor.setValue(m_ElementClass.newInstance()); - } - } - } + try { + if (m_ListModel.getSize() > 0) { + m_ElementEditor.setValue(m_ListModel.getElementAt(0)); + } else { + if (m_ElementEditor instanceof GenericObjectEditor) { + ((GenericObjectEditor) m_ElementEditor).setDefaultValue(); + } else { + if (m_ElementEditor.getValue() != null) { + m_ElementEditor.setValue(m_ElementClass.newInstance()); + } + } + } - setPreferredSize(new Dimension(300,400)); -// JPanel panel = new JPanel(); -// panel.setLayout(new BorderLayout()); -// panel.add(view, BorderLayout.CENTER); -// panel.add(m_AddBut, BorderLayout.EAST); -// JPanel buttonPanel=new JPanel(new FlowLayout()); - - if (withAddButton && !(m_AdditionalUpperButtonList.contains(m_AddBut))) m_AdditionalUpperButtonList.add(m_AddBut); - if (withSetButton && !(m_AdditionalUpperButtonList.contains(m_SetBut))) m_AdditionalUpperButtonList.add(m_SetBut); - if (withSetButton && !(m_AdditionalUpperButtonList.contains(m_SetAllBut))) m_AdditionalUpperButtonList.add(m_SetAllBut); - - JPanel combiUpperPanel = new JPanel(getButtonLayout(1, m_AdditionalUpperButtonList)); - combiUpperPanel.add(m_View ); + //setPreferredSize(new Dimension(400,500)); - for (JButton but : m_AdditionalUpperButtonList) { - combiUpperPanel.add(but); - } - add(combiUpperPanel, BorderLayout.NORTH); - if (additionalCenterPane==null) add(new JScrollPane(m_ElementList), BorderLayout.CENTER); - else { - JPanel centerPane=new JPanel(); - centerPane.setLayout(new GridLayout(2, 1)); - centerPane.add(new JScrollPane(m_ElementList)); - centerPane.add(additionalCenterPane); - add(centerPane, BorderLayout.CENTER); - } - - if (withDeleteButton && !m_AdditionalLowerButtonList.contains(m_DeleteBut)) m_AdditionalLowerButtonList.add(m_DeleteBut); - JPanel combiLowerPanel = new JPanel(getButtonLayout(0, m_AdditionalLowerButtonList)); - for (JButton but : m_AdditionalLowerButtonList) { - combiLowerPanel.add(but); - } - add(combiLowerPanel, BorderLayout.SOUTH); - m_ElementEditor.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent e) { - repaint(); - } - }); - - addPopupMenu(); - } catch (Exception ex) { - System.err.println(ex.getMessage()); - ex.printStackTrace(); - m_ElementEditor = null; - } - } - } - if (m_ElementEditor == null) { - add(m_Label, BorderLayout.CENTER); - } - m_Support.firePropertyChange("", null, null); - validate(); - } - - /** - * Make a fitting grid layout for a list of buttons. An additional offset may be given - * if further components should be added besides the buttons. - * - * @param additionalOffset - * @param bList - * @return - */ - private LayoutManager getButtonLayout(int additionalOffset, List bList) { - int lines = 1+((bList.size()+additionalOffset-1)/3); - int cols = 3; - return new GridLayout(lines, cols); - } + if (withAddButton && !(m_AdditionalUpperButtonList.contains(m_AddBut))) { + m_AdditionalUpperButtonList.add(m_AddBut); + } + if (withSetButton && !(m_AdditionalUpperButtonList.contains(m_SetBut))) { + m_AdditionalUpperButtonList.add(m_SetBut); + } + if (withSetButton && !(m_AdditionalUpperButtonList.contains(m_SetAllBut))) { + m_AdditionalUpperButtonList.add(m_SetAllBut); + } - public void removeUpperActionButton(String text) { - removeActionButton(m_AdditionalUpperButtonList, text); - } - - public void removeLowerActionButton(String text) { - removeActionButton(m_AdditionalLowerButtonList, text); - } - - protected void removeActionButton(List bList, String text) { - JButton but = null; - for (JButton jb : bList) { - if (text.equals(jb.getText())) { - but = jb; - break; - } - } - if (but!=null) bList.remove(but); - } - - public void addUpperActionButton(String text, ActionListener al) { - addActionButton(m_AdditionalUpperButtonList, text, al); - } - - /** - * Wrap an action listener such that the selection state will always be up to date - * in the selectableList (if it exists). - * @param al - * @return - */ - private ActionListener makeSelectionKnownAL(final ActionListener al) { - return new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (selectableList!=null) { - selectableList.setSelectionByIndices(m_ElementList.getSelectedIndices()); - } - al.actionPerformed(e); - } - }; - } + // Upper Button Panel + JPanel combiUpperPanel = new JPanel(getButtonLayout(1, m_AdditionalUpperButtonList)); + combiUpperPanel.add(m_View); - public void addLowerActionButton(String text, ActionListener al) { - addActionButton(m_AdditionalLowerButtonList, text, al); - } - - public void addActionButton(List bList, String text, ActionListener al) { - JButton but = new JButton(text); - but.addActionListener(makeSelectionKnownAL(al)); - bList.add(but); - } - - /** - * Sets the current object array. - * - * @param o an object that must be an array. - */ - public void setValue(Object o) { - // Create a new list model, put it in the list and resize? - updateEditorType(o); - } + for (JButton but : m_AdditionalUpperButtonList) { + combiUpperPanel.add(but); + } + + setLayout(new GridBagLayout()); + + GridBagConstraints gbConstraints = new GridBagConstraints(); + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + gbConstraints.gridx = 0; + gbConstraints.gridy = 0; + add(combiUpperPanel, gbConstraints); + + // Job List + gbConstraints.gridy++; + gbConstraints.fill = GridBagConstraints.HORIZONTAL; + add(new JScrollPane(m_ElementList), gbConstraints); + + // Lower Button Panel + if (withDeleteButton && !m_AdditionalLowerButtonList.contains(m_DeleteBut)) { + m_AdditionalLowerButtonList.add(m_DeleteBut); + } + JPanel combiLowerPanel = new JPanel(getButtonLayout(0, m_AdditionalLowerButtonList)); + for (JButton but : m_AdditionalLowerButtonList) { + combiLowerPanel.add(but); + } + gbConstraints.gridy++; + add(combiLowerPanel, gbConstraints); + + // Additional Center Panel (e.g. PropertySheetPanel) + if (additionalCenterComp != null) { + gbConstraints.weightx = 1.0; + gbConstraints.weighty = 1.0; + gbConstraints.fill = GridBagConstraints.BOTH; + gbConstraints.gridy++; + add(additionalCenterComp, gbConstraints); + } + + m_ElementEditor.addPropertyChangeListener(new PropertyChangeListener() { - /** - * Select all items. If all are selected, then deselect all items. - */ - public void selectDeselectAll() { - if (areAllSelected()) m_ElementList.getSelectionModel().clearSelection(); - else m_ElementList.setSelectionInterval(0, m_ElementList.getModel().getSize()-1); - } - - public boolean areAllSelected() { - for (int i=0; i0) { - m_ElementList.addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - if (selectableList!=null) { - selectableList.setSelectionByIndices(m_ElementList.getSelectedIndices()); - } - if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { - // do nothing - } else { // right click released, so show popup - JPopupMenu popupMenu = new JPopupMenu(); - for (JMenuItem item : m_popupItemList) popupMenu.add(item); - popupMenu.show(GenericArrayEditor.this, e.getX(), e.getY()); - } - } - }); - } - } + addPopupMenu(); + } catch (Exception ex) { + System.err.println(ex.getMessage()); + ex.printStackTrace(); + m_ElementEditor = null; + } + } + } + if (m_ElementEditor == null) { + add(m_Label, BorderLayout.CENTER); + } + m_Support.firePropertyChange("", null, null); + validate(); + } - /** - * Create a menu item with given title and listener, add it to the menu and - * return it. It may be enabled or disabled. - * - * @param menu - * @param title - * @param aListener - * @param enabled - * @return - */ - private JMenuItem createMenuItem(String title, boolean enabled, - ActionListener aListener) { - JMenuItem item = new JMenuItem(title); - // if (bgColor!=null) item.setForeground(bgColor); - item.addActionListener(aListener); - item.setEnabled(enabled); - return item; - } - - /** - * Supposedly returns an initialization string to create a classifier - * identical to the current one, including it's state, but this doesn't - * appear possible given that the initialization string isn't supposed to - * contain multiple statements. - * - * @return the java source code initialisation string - */ - public String getJavaInitializationString() { - return "null"; - } + /** + * Make a fitting grid layout for a list of buttons. An additional offset may be given if + * further components should be added besides the buttons. + * + * @param additionalOffset + * @param bList + * @return + */ + private LayoutManager getButtonLayout(int additionalOffset, List bList) { + int lines = 1 + ((bList.size() + additionalOffset - 1) / 3); + int cols = 3; + return new GridLayout(lines, cols); + } - /** - * Returns true to indicate that we can paint a representation of the - * string array - * - * @return true - */ - public boolean isPaintable() { - return true; - } + public void removeUpperActionButton(String text) { + removeActionButton(m_AdditionalUpperButtonList, text); + } - /** - * Paints a representation of the current classifier. - * - * @param gfx the graphics context to use - * @param box the area we are allowed to paint into - */ - public void paintValue(Graphics gfx, Rectangle box) { - FontMetrics fm = gfx.getFontMetrics(); - int vpad = (box.height - fm.getAscent()) / 2; + public void removeLowerActionButton(String text) { + removeActionButton(m_AdditionalLowerButtonList, text); + } + + protected void removeActionButton(List bList, String text) { + JButton but = null; + for (JButton jb : bList) { + if (text.equals(jb.getText())) { + but = jb; + break; + } + } + if (but != null) { + bList.remove(but); + } + } + + public void addUpperActionButton(String text, ActionListener al) { + addActionButton(m_AdditionalUpperButtonList, text, al); + } + + /** + * Wrap an action listener such that the selection state will always be up to date in the + * selectableList (if it exists). + * + * @param al + * @return + */ + private ActionListener makeSelectionKnownAL(final ActionListener al) { + return new ActionListener() { + + public void actionPerformed(ActionEvent e) { + if (selectableList != null) { + selectableList.setSelectionByIndices(m_ElementList.getSelectedIndices()); + } + al.actionPerformed(e); + } + }; + } + + public void addLowerActionButton(String text, ActionListener al) { + addActionButton(m_AdditionalLowerButtonList, text, al); + } + + public void addActionButton(List bList, String text, ActionListener al) { + JButton but = new JButton(text); + but.addActionListener(makeSelectionKnownAL(al)); + bList.add(but); + } + + /** + * Sets the current object array. + * + * @param o an object that must be an array. + */ + public void setValue(Object o) { + // Create a new list model, put it in the list and resize? + updateEditorType(o); + } + + /** + * Select all items. If all are selected, then deselect all items. + */ + public void selectDeselectAll() { + if (areAllSelected()) { + m_ElementList.getSelectionModel().clearSelection(); + } else { + m_ElementList.setSelectionInterval(0, m_ElementList.getModel().getSize() - 1); + } + } + + public boolean areAllSelected() { + for (int i = 0; i < m_ElementList.getModel().getSize(); i++) { + if (!m_ElementList.isSelectedIndex(i)) { + return false; + } + } + return true; + } + + /** + * Gets the current object array. + * + * @return the current object array + */ + public Object getValue() { + if (m_ListModel == null) { + return null; + } + if (selectableList != null) { + return selectableList; + } else { + // Convert the listmodel to an array of strings and return it. + int length = m_ListModel.getSize(); + Object result = Array.newInstance(m_ElementClass, length); + for (int i = 0; i < length; i++) { + Array.set(result, i, m_ListModel.elementAt(i)); + } + return result; + } + } + + public void addPopupItem(String text, ActionListener al) { + JMenuItem item = createMenuItem(text, true, makeSelectionKnownAL(al)); + m_popupItemList.add(item); + } + + public void addPopupMenu() { + if (m_popupItemList.size() > 0) { + m_ElementList.addMouseListener(new MouseAdapter() { + + public void mouseClicked(MouseEvent e) { + if (selectableList != null) { + selectableList.setSelectionByIndices(m_ElementList.getSelectedIndices()); + } + if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { + // do nothing + } else { // right click released, so show popup + JPopupMenu popupMenu = new JPopupMenu(); + for (JMenuItem item : m_popupItemList) { + popupMenu.add(item); + } + popupMenu.show(GenericArrayEditor.this, e.getX(), e.getY()); + } + } + }); + } + } + + /** + * Create a menu item with given title and listener, add it to the menu and return it. It may be + * enabled or disabled. + * + * @param menu + * @param title + * @param aListener + * @param enabled + * @return + */ + private JMenuItem createMenuItem(String title, boolean enabled, + ActionListener aListener) { + JMenuItem item = new JMenuItem(title); + // if (bgColor!=null) item.setForeground(bgColor); + item.addActionListener(aListener); + item.setEnabled(enabled); + return item; + } + + /** + * Supposedly returns an initialization string to create a classifier identical to the current + * one, including it's state, but this doesn't appear possible given that the initialization + * string isn't supposed to contain multiple statements. + * + * @return the java source code initialisation string + */ + public String getJavaInitializationString() { + return "null"; + } + + /** + * Returns true to indicate that we can paint a representation of the string array + * + * @return true + */ + public boolean isPaintable() { + return true; + } + + /** + * Paints a representation of the current classifier. + * + * @param gfx the graphics context to use + * @param box the area we are allowed to paint into + */ + public void paintValue(Graphics gfx, Rectangle box) { + FontMetrics fm = gfx.getFontMetrics(); + int vpad = (box.height - fm.getAscent()) / 2; // System.out.println(m_ListModel + " --- " + m_ElementClass); - String rep; - if (m_ListModel.getSize() == 0) rep="Empty"; - else { - rep = m_ListModel.getSize() + " of " + EVAHELP.cutClassName(m_ElementClass.getName()); - Object maybeName = BeanInspector.callIfAvailable(m_ListModel.get(0), "getName", new Object[]{}); - if (maybeName!=null) { - rep = rep + " ("+(String)maybeName + "...)"; - } - } - gfx.drawString(rep, 2, fm.getHeight() + vpad - 3 ); - } - /** - * - */ - public String getAsText() { - return null; - } - /** - * - */ - public void setAsText(String text) throws IllegalArgumentException { - throw new IllegalArgumentException(text); - } - /** - * - */ - public String[] getTags() { - return null; - } - /** - * - */ - public boolean supportsCustomEditor() { - return true; - } - /** - * - */ - public Component getCustomEditor() { - return this; - } - - public void addPropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); - m_Support.addPropertyChangeListener(l); - } + String rep; + if (m_ListModel.getSize() == 0) { + rep = "Empty"; + } else { + rep = m_ListModel.getSize() + " of " + EVAHELP.cutClassName(m_ElementClass.getName()); + Object maybeName = BeanInspector.callIfAvailable(m_ListModel.get(0), "getName", new Object[]{}); + if (maybeName != null) { + rep = rep + " (" + (String) maybeName + "...)"; + } + } + gfx.drawString(rep, 2, fm.getHeight() + vpad - 3); + } - public void removePropertyChangeListener(PropertyChangeListener l) { - if (m_Support == null) m_Support = new PropertyChangeSupport(this); - m_Support.removePropertyChangeListener(l); - } + /** + * + */ + public String getAsText() { + return null; + } - /** - * - */ -// public static void main(String [] args) { -// try { -// java.beans.PropertyEditorManager.registerEditor(SelectedTag.class,TagEditor.class); -// java.beans.PropertyEditorManager.registerEditor(int [].class,GenericArrayEditor.class); -// java.beans.PropertyEditorManager.registerEditor(double [].class,GenericArrayEditor.class); -// GenericArrayEditor editor = new GenericArrayEditor(); -// -// -// int[] initial = { 3,45, 7}; -// editor.setValue(initial); -// PropertyDialog pd = new PropertyDialog(editor,EVAHELP.cutClassName(editor.getClass().getName()) -// , 100, 100); -//// pd.setSize(200,200); -// pd.addWindowListener(new WindowAdapter() { -// public void windowClosing(WindowEvent e) { -// System.exit(0); -// } -// }); -// editor.setValue(initial); -// //ce.validate(); -// } catch (Exception ex) { -// ex.printStackTrace(); -// System.err.println(ex.getMessage()); -// } -// } - public boolean isWithAddButton() { - return withAddButton; - } - public void setWithAddButton(boolean withAddButton) { - this.withAddButton = withAddButton; - } - public boolean isWithSetButton() { - return withSetButton; - } - public void setWithSetButton(boolean withSetButton) { - this.withSetButton = withSetButton; - } - - public boolean isWithDeleteButton() { - return withDeleteButton; - } - public void setWithDeleteButton(boolean wB) { - this.withDeleteButton = wB; - } - - public void removeNotify() { - super.removeNotify(); - } + /** + * + */ + public void setAsText(String text) throws IllegalArgumentException { + throw new IllegalArgumentException(text); + } + + /** + * + */ + public String[] getTags() { + return null; + } + + /** + * + */ + public boolean supportsCustomEditor() { + return true; + } + + /** + * + */ + public Component getCustomEditor() { + return this; + } + + public void addPropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.addPropertyChangeListener(l); + } + + public void removePropertyChangeListener(PropertyChangeListener l) { + if (m_Support == null) { + m_Support = new PropertyChangeSupport(this); + } + m_Support.removePropertyChangeListener(l); + } + + public boolean isWithAddButton() { + return withAddButton; + } + + public void setWithAddButton(boolean withAddButton) { + this.withAddButton = withAddButton; + } + + public boolean isWithSetButton() { + return withSetButton; + } + + public void setWithSetButton(boolean withSetButton) { + this.withSetButton = withSetButton; + } + + public boolean isWithDeleteButton() { + return withDeleteButton; + } + + public void setWithDeleteButton(boolean wB) { + this.withDeleteButton = wB; + } + + public void removeNotify() { + super.removeNotify(); + } } - diff --git a/src/eva2/gui/GenericObjectEditor.java b/src/eva2/gui/GenericObjectEditor.java index 992f98b1..c741b982 100644 --- a/src/eva2/gui/GenericObjectEditor.java +++ b/src/eva2/gui/GenericObjectEditor.java @@ -1,16 +1,10 @@ package eva2.gui; /* - * Title: EvA2 - * Description: - * Copyright: Copyright (c) 2012 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher, Fabian Becker - * @version: $Revision: 266 $ - * $Date: 2007-11-20 14:33:48 +0100 (Tue, 20 Nov 2007) $ - * $Author: mkron $ + * Title: EvA2 Description: Copyright: Copyright (c) 2012 Company: University of Tuebingen, Computer + * Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher, Fabian Becker @version: + * $Revision: 266 $ $Date: 2007-11-20 14:33:48 +0100 (Tue, 20 Nov 2007) $ $Author: mkron $ */ - import java.awt.Component; import java.awt.FontMetrics; import java.awt.Graphics; @@ -36,474 +30,477 @@ import eva2.EvAInfo; import eva2.tools.ReflectPackage; import eva2.tools.jproxy.RMIProxyLocal; - - public class GenericObjectEditor implements PropertyEditor { - private static final Logger logger = Logger.getLogger(EvAInfo.defaultLogger); - private Object m_Object; - private Object m_Backup; - private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); - private Class classType; - private GOEPanel editorComponent; - private boolean isEnabled = true; - - /** - * Read the classes available for user selection from the properties or the classpath respectively - */ - public static ArrayList getClassesFromProperties(String className, ArrayList> instances) { - logger.log(Level.FINEST, "Requesting className: {0}", className); - - // Try to read the predefined classes from the props file. - String typeOptions = EvAInfo.getProperty(className); - if (typeOptions == null) { - // If none are defined, all assignable classes are searched the hard way, using the ReflectPackage - return getClassesFromClassPath(className, instances); - } else { - StringTokenizer st = new StringTokenizer(typeOptions, ", "); - ArrayList classes = new ArrayList(); - while (st.hasMoreTokens()) { - String current = st.nextToken().trim(); - try { - Class clz = Class.forName(current); // test for instantiability - if (instances != null) { - instances.add(clz); - } - classes.add(current); - } catch (ClassNotFoundException ex) { - logger.log(Level.WARNING, - String.format("Requesting className: %1$s, Couldn't load: %2%s", className, current), ex); - } - } - return classes; - } - } - - /** - * Return the names of all classes in the same package that are assignable - * from the named class, and that can be loaded through the classpath. - * If a class has a declared field called "hideFromGOE" this method will skip it. - * Abstract classes and interfaces will be skipped as well. - * - * @see ReflectPackage.getAssignableClassesInPackage - * @param className - * @return - */ - public static ArrayList getClassesFromClassPath(String className, ArrayList> instances) { - ArrayList classes = new ArrayList(); - Class[] classArray; - classArray=ReflectPackage.getAssignableClasses(className, true, true); - if (classArray == null) { - logger.log(Level.WARNING, String.format("No assignable classes found in property file or on classpath: %1$s for %2$s", EvAInfo.propertyFile, className)); - classes.add(className); - } else { - for (Class clazz : classArray) { - int m = clazz.getModifiers(); - try { - // a field allowing a class to indicate it doesnt want to be displayed - Field f = clazz.getDeclaredField("hideFromGOE"); - if (f.getBoolean(clazz) == true) { - logger.log(Level.FINEST, "Class {0} wants to be hidden from GOE.", clazz); - continue; - } - } catch (NoSuchFieldException e) { - /* - * We are just logging this exception here. It is expected that - * most classes do not have this field. - */ - logger.log(Level.FINER, String.format("%1$s does not have a hideFromGOE field", clazz.toString()), e); - } catch (IllegalArgumentException e) { - logger.log(Level.FINER, e.getMessage(), e); - } catch (IllegalAccessException e) { - logger.log(Level.FINER, e.getMessage(), e); - } - - - if (!Modifier.isAbstract(m) && !clazz.isInterface()) { // dont take abstract classes or interfaces - try { - Class[] params = new Class[0]; - clazz.getConstructor(params); - if (instances!=null) instances.add(clazz); - classes.add(clazz.getName()); - } catch (NoSuchMethodException e) { - logger.log(Level.WARNING, String.format("GOE warning: Class %1$s has no default constructor", clazz.getName()), e); - } - } - } - } - return classes; - } - - /** - * Hide or show the editable property of a class, this makes sense for classes - * which are represented visually using the GenericObjectEditor. - * Returns false, if an error occurs, else true. - * An instance may call this statically on itself by means of this.getClass(). - * Actually this only sets the hidden property of the java bean which is checked in the - * wasModified method of PropertySheetPanel. - * - * @param cls class the property belongs to - * @param property string name of the property - * @param hide desired value to set, true for hidden, false for visible - * @return false, if an error occurs, else true - */ - public static boolean setExpertProperty(Class cls, String property, boolean expertValue) { - try { - BeanInfo bi = Introspector.getBeanInfo(cls); - PropertyDescriptor[] props = bi.getPropertyDescriptors(); - for (int i=0; i