Major update! Some related projects might be broken from now on - if so, let me know via email.

This is the first of a series of commits to manifest the new graphical user interface of EvA2.

This commit includes (incomplete list)

- New Icons that are used in the GUI
- A completely refactored GUI with a one-window layout.
- Plots/Text Output will now appear on a JDesktopPane
- Configuration can be done via the sidebar (not yet completely functional)
- New layouts for TabbedPane (currently not active) and JButton (vertical text)
- Code cleanup / removal of TRACE variable
- More classes are now using the Logging facility.

refs #8, #10, #14
fixes #12
This commit is contained in:
Fabian Becker 2012-05-14 13:57:39 +00:00
parent d4c8b802bd
commit d2059a5852
72 changed files with 5330 additions and 4519 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 463 KiB

BIN
resources/images/Help24.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
resources/images/Open16.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 B

BIN
resources/images/Save16.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 B

View File

@ -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";

View File

@ -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<RemoteStateListener> superListenerList = null;
private List<RemoteStateListener> 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<RemoteStateListener>();
superListenerList = new ArrayList<RemoteStateListener>();
}
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<String> 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<JEFrame> 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) {

View File

@ -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;
}

View File

@ -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

View File

@ -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();

View File

@ -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<PanelMaker> pmContainer = null;
private JExtToolBar m_BarStandard;
EvAModuleButtonPanelMaker butPanelMkr=null;
public EvATabbedFrameMaker() {
pmContainer = null;
}
public void addPanelMaker(PanelMaker pm) {
if (pmContainer==null) pmContainer = new ArrayList<PanelMaker>(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<PanelMaker> 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<pmContainer.size();i++) {
PanelMaker element = pmContainer.get(i);
JComponent panel = element.makePanel();
if (element instanceof EvAModuleButtonPanelMaker) {
m_BarStandard.add(panel);
butPanelMkr=(EvAModuleButtonPanelMaker)element;
} else if (element instanceof JParaPanel) {
m_MainPanel.addTab (((JParaPanel)element).getName(), panel);
}
}
m_SuperPanel.add(m_MainPanel, gbconst);
public EvATabbedFrameMaker() {
pmContainer = null;
}
return m_SuperPanel;
}
public JExtToolBar getToolBar() {
return m_BarStandard;
}
/**
* 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 addPanelMaker(PanelMaker pm) {
if (pmContainer == null) {
pmContainer = new ArrayList<PanelMaker>(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<InterfaceAdditionalPopulationInformer> 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<InterfaceAdditionalPopulationInformer> 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);
}
}
};
}

View File

@ -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;
}
}
}
}
}

View File

@ -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<String> 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<String> classesLongNames;
ArrayList<Class<?>> instances = new ArrayList<Class<?>>(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<String>(GenericObjectEditor.getClassesFromProperties(((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)genericObjectEditor.getValue()))).getOriginalClass().getName(), null));
} else {
classesLongNames = new Vector<String>(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<Class<?>> 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;
}
public void setTarget(Object o) {
propertySheetPanel.setTarget(o);
}
protected void updateChooser() {
String objectName = /*EVAHELP.cutClassName*/ (genericObjectEditor.getValue().getClass().getName());
boolean found = false;
for (int i = 0; i < m_ObjectNames.getSize(); i++) {
if (TRACE) System.out.println("in updateChooser: looking at "+(String)m_ObjectNames.getElementAt(i));
if (objectName.equals((String)m_ObjectNames.getElementAt(i))) {
found = true;
break;
}
}
if (!found)
m_ObjectNames.addElement(objectName);
m_ObjectChooser.getModel().setSelectedItem(objectName);
}
/**
*
*/
protected void updateClassType() {
Vector<String> classesLongNames;
ArrayList<Class<?>> instances = new ArrayList<Class<?>>(5);
if (Proxy.isProxyClass(genericObjectEditor.getClassType())) {
classesLongNames = new Vector<String>(GenericObjectEditor.getClassesFromProperties(((RMIProxyLocal) Proxy.getInvocationHandler(((Proxy) genericObjectEditor.getValue()))).getOriginalClass().getName(), null));
} else {
classesLongNames = new Vector<String>(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<Class<?>> 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;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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<String> getClassesFromProperties(String className, ArrayList<Class<?>> 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<String> classes = new ArrayList<String>();
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<String> getClassesFromClassPath(String className, ArrayList<Class<?>> instances) {
ArrayList<String> classes = new ArrayList<String>();
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<props.length; i++) {
if ((props[i].getName().equals(property))) {
if (expertValue != props[i].isExpert()) props[i].setExpert(expertValue);
}
}
return true;
} catch (Exception e) {
logger.log(Level.WARNING, String.format("Couldn't set expert property for %1$s/%2$s", cls.getName(), property), e);
return false;
}
}
/**
* 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 setHideProperty(Class<?> cls, String property, boolean hide) {
try {
BeanInfo bi = Introspector.getBeanInfo(cls);
PropertyDescriptor[] props = bi.getPropertyDescriptors();
for (int i=0; i<props.length; i++) {
if ((props[i].getName().equals(property))) {
if (hide != props[i].isHidden()) {
props[i].setHidden(hide);
}
return true;
}
}
logger.log(Level.WARNING, "Property {0} not found", property);
return false;
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Couldn't set hide property for %1$s/%2$s", cls.getName(), property), e);
return false;
}
}
/**
* Hide or unhide all properties of a given class. Added to avoid the problem with hidden
* properties of inherited classes hide the property for all classes within the same inheritance tree.
*
* @param cls
* @param hide
* @return the original hidden states or null if an error occurred.
*/
public static boolean[] setHideAllProperties(Class<?> cls, boolean hide) {
try {
BeanInfo bi = Introspector.getBeanInfo(cls);
PropertyDescriptor[] props = bi.getPropertyDescriptors();
boolean[] orig = new boolean[props.length];
for (int i=0; i<props.length; i++) {
orig[i]=props[i].isHidden();
props[i].setHidden(hide);
}
return orig;
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Couldn't hide all properties for %1$s/all", cls.getName()), e);
return null;
}
}
public static void setHideProperties(Class<?> cls, boolean[] hideStates) {
if (hideStates!=null) {
BeanInfo bi;
try {
bi = Introspector.getBeanInfo(cls);
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Error on introspection of %1$s", cls.getName()), e);
return;
}
PropertyDescriptor[] props = bi.getPropertyDescriptors();
if (hideStates.length == props.length) {
for (int i=0; i<props.length; i++) {
props[i].setHidden(hideStates[i]);
}
} else {
System.err.println("Error, mismatching length of hide state array in GenericObjectEditor.setHideProperites");
}
}
}
/**
* Convenience-method. See setHideProperty.
*
* @param cls
* @param property
* @param show
* @return
*/
public static boolean setShowProperty(Class<?> cls, String property, boolean show) {
return GenericObjectEditor.setHideProperty(cls, property, !show);
}
/**
* Sets whether the editor is "enabled", meaning that the current
* values will be painted.
*
* @param newVal a value of type 'boolean'
*/
public void setEnabled(boolean newVal) {
if (newVal != isEnabled) {
isEnabled = newVal;
}
}
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;
/**
* Sets the class of values that can be edited.
*
* @param type a value of type 'Class'
*/
public void setClassType(Class<?> type) {
//if (TRACE) System.out.println("GOE setClassType("+ (type == null? "<null>" : type.getName()) + ")");
classType = type;
if (editorComponent != null)
editorComponent.updateClassType();
/**
* Read the classes available for user selection from the properties or the classpath
* respectively
*/
public static ArrayList<String> getClassesFromProperties(String className, ArrayList<Class<?>> 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<String> classes = new ArrayList<String>();
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<String> getClassesFromClassPath(String className, ArrayList<Class<?>> instances) {
ArrayList<String> classes = new ArrayList<String>();
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 < props.length; i++) {
if ((props[i].getName().equals(property))) {
if (expertValue != props[i].isExpert()) {
props[i].setExpert(expertValue);
}
}
}
return true;
} catch (Exception e) {
logger.log(Level.WARNING, String.format("Couldn't set expert property for %1$s/%2$s", cls.getName(), property), e);
return false;
}
}
/**
* 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 setHideProperty(Class<?> cls, String property, boolean hide) {
try {
BeanInfo bi = Introspector.getBeanInfo(cls);
PropertyDescriptor[] props = bi.getPropertyDescriptors();
for (int i = 0; i < props.length; i++) {
if ((props[i].getName().equals(property))) {
if (hide != props[i].isHidden()) {
props[i].setHidden(hide);
}
return true;
}
}
logger.log(Level.WARNING, "Property {0} not found", property);
return false;
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Couldn't set hide property for %1$s/%2$s", cls.getName(), property), e);
return false;
}
}
/**
* Hide or unhide all properties of a given class. Added to avoid the problem with hidden
* properties of inherited classes hide the property for all classes within the same inheritance
* tree.
*
* @param cls
* @param hide
* @return the original hidden states or null if an error occurred.
*/
public static boolean[] setHideAllProperties(Class<?> cls, boolean hide) {
try {
BeanInfo bi = Introspector.getBeanInfo(cls);
PropertyDescriptor[] props = bi.getPropertyDescriptors();
boolean[] orig = new boolean[props.length];
for (int i = 0; i < props.length; i++) {
orig[i] = props[i].isHidden();
props[i].setHidden(hide);
}
return orig;
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Couldn't hide all properties for %1$s/all", cls.getName()), e);
return null;
}
}
public static void setHideProperties(Class<?> cls, boolean[] hideStates) {
if (hideStates != null) {
BeanInfo bi;
try {
bi = Introspector.getBeanInfo(cls);
} catch (IntrospectionException e) {
logger.log(Level.WARNING, String.format("Error on introspection of %1$s", cls.getName()), e);
return;
}
PropertyDescriptor[] props = bi.getPropertyDescriptors();
if (hideStates.length == props.length) {
for (int i = 0; i < props.length; i++) {
props[i].setHidden(hideStates[i]);
}
} else {
System.err.println("Error, mismatching length of hide state array in GenericObjectEditor.setHideProperites");
}
}
}
/**
* Convenience-method. See setHideProperty.
*
* @param cls
* @param property
* @param show
* @return
*/
public static boolean setShowProperty(Class<?> cls, String property, boolean show) {
return GenericObjectEditor.setHideProperty(cls, property, !show);
}
/**
* Sets whether the editor is "enabled", meaning that the current values will be painted.
*
* @param newVal a value of type 'boolean'
*/
public void setEnabled(boolean newVal) {
if (newVal != isEnabled) {
isEnabled = newVal;
}
}
/**
* Sets the class of values that can be edited.
*
* @param type a value of type 'Class'
*/
public void setClassType(Class<?> type) {
//if (TRACE) System.out.println("GOE setClassType("+ (type == null? "<null>" : type.getName()) + ")");
classType = type;
if (editorComponent != null) {
editorComponent.updateClassType();
}
}
public Class<?> getClassType() {
return classType;
}
/**
* Sets the current object to be the default, taken as the first item in the chooser
*/
public void setDefaultValue() {
if (classType == null) {
logger.log(Level.WARNING, "No ClassType set up for GenericObjectEditor!");
return;
}
Vector<String> v = null;
if (Proxy.isProxyClass(classType)) {
//if (TRACE) System.out.println("PROXY! original was " + ((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)m_Object))).getOriginalClass().getName());
v = new Vector<String>(getClassesFromProperties(((RMIProxyLocal) Proxy.getInvocationHandler(((Proxy) m_Object))).getOriginalClass().getName(), null));
} else {
v = new Vector<String>(getClassesFromProperties(classType.getName(), null));
}
public Class<?> getClassType() {
return classType;
}
/**
* Sets the current object to be the default, taken as the first item in
* the chooser
*/
public void setDefaultValue() {
if (classType == null) {
logger.log(Level.WARNING, "No ClassType set up for GenericObjectEditor!");
return;
}
Vector<String> v=null;
if (Proxy.isProxyClass(classType)) {
//if (TRACE) System.out.println("PROXY! original was " + ((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)m_Object))).getOriginalClass().getName());
v = new Vector<String>(getClassesFromProperties(((RMIProxyLocal)Proxy.getInvocationHandler(((Proxy)m_Object))).getOriginalClass().getName(), null));
} else {
v = new Vector<String>(getClassesFromProperties(classType.getName(), null));
}
// v = new Vector<String>(getClassesFromProperties(m_ClassType.getName()));
try {
if (v.size() > 0)
setObject((Object)Class.forName((String)v.get(0)).newInstance());
} catch (Exception ex) {
System.err.println("Exception in setDefaultValue !!!"+ex.getMessage());
}
}
try {
if (v.size() > 0) {
setObject((Object) Class.forName((String) v.get(0)).newInstance());
}
} catch (Exception ex) {
System.err.println("Exception in setDefaultValue !!!" + ex.getMessage());
}
}
/**
* Sets the current Object. If the Object is in the
* Object chooser, this becomes the selected item (and added
* to the chooser if necessary).
*
* @param o an object that must be a Object.
*/
public void setValue(Object o) {
//System.err.println("setValue()" + m_ClassType.toString());
/**
* Sets the current Object. If the Object is in the Object chooser, this becomes the selected
* item (and added to the chooser if necessary).
*
* @param o an object that must be a Object.
*/
public void setValue(Object o) {
//System.err.println("setValue()" + m_ClassType.toString());
if (o==null || classType == null) {
logger.log(Level.WARNING, "No ClassType set up for GenericObjectEditor!");
return;
}
if (!classType.isAssignableFrom(o.getClass())) {
if (classType.isPrimitive()) {
System.err.println("setValue object not of correct type! Expected "+classType.getName()+", got " + o.getClass().getName());
System.err.println("setting primitive type");
setObject((Object)o);
//throw new NullPointerException("ASDF");
} else {
System.err.println("setValue object not of correct type! Expected "+classType.getName()+", got " + o.getClass().getName());
}
return;
}
if (o == null || classType == null) {
logger.log(Level.WARNING, "No ClassType set up for GenericObjectEditor!");
return;
}
if (!classType.isAssignableFrom(o.getClass())) {
if (classType.isPrimitive()) {
System.err.println("setValue object not of correct type! Expected " + classType.getName() + ", got " + o.getClass().getName());
System.err.println("setting primitive type");
setObject((Object) o);
//throw new NullPointerException("ASDF");
} else {
System.err.println("setValue object not of correct type! Expected " + classType.getName() + ", got " + o.getClass().getName());
}
return;
}
setObject((Object)o);
if (editorComponent != null)
editorComponent.updateChooser();
setObject((Object) o);
if (editorComponent != null) {
editorComponent.updateChooser();
}
}
}
/**
* Sets the current Object, but doesn't worry about updating
* the state of the Object chooser.
*
* @param c a value of type 'Object'
*/
private void setObject(Object c) {
// This should really call equals() for comparison.
//if (TRACE) System.out.println("setObject "+ c.getClass().getName() + " " + c);
boolean trueChange = (c != getValue());
/**
* Sets the current Object, but doesn't worry about updating the state of the Object chooser.
*
* @param c a value of type 'Object'
*/
private void setObject(Object c) {
// This should really call equals() for comparison.
//if (TRACE) System.out.println("setObject "+ c.getClass().getName() + " " + c);
boolean trueChange = (c != getValue());
m_Backup = m_Object;
m_Object = c;
m_Backup = m_Object;
m_Object = c;
if (editorComponent != null) {
editorComponent.updateChildPropertySheet();
if (trueChange)
propertyChangeSupport.firePropertyChange("", m_Backup, m_Object);
}
}
if (editorComponent != null) {
editorComponent.updateChildPropertySheet();
if (trueChange) {
propertyChangeSupport.firePropertyChange("", m_Backup, m_Object);
}
}
}
/**
* Gets the current Object.
*
* @return the current Object
*/
public Object getValue() {
return m_Object;
}
/**
* Gets the current Object.
*
* @return the current Object
*/
public Object getValue() {
return m_Object;
}
/**
* Supposedly returns an initialization string to create a Object 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 initialization string
*/
public String getJavaInitializationString() {
return "new " + m_Object.getClass().getName() + "()";
}
/**
* Supposedly returns an initialization string to create a Object
* 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 initialization string
*/
public String getJavaInitializationString() {
return "new " + m_Object.getClass().getName() + "()";
}
/**
* Returns true to indicate that we can paint a representation of the Object.
*
* @return true
*/
public boolean isPaintable() {
return true;
}
/**
* Returns true to indicate that we can paint a representation of the
* Object.
*
* @return true
*/
public boolean isPaintable() {
return true;
}
/**
* Paints a representation of the current Object.
*
* @param gfx the graphics context to use
* @param box the area we are allowed to paint into
*/
public void paintValue(Graphics gfx, Rectangle box) {
if (isEnabled && m_Object != null) {
int getNameMethod = -1;
MethodDescriptor[] methods;
String rep = "";
try {
BeanInfo beanInfo = Introspector.getBeanInfo(m_Object.getClass());
methods = beanInfo.getMethodDescriptors();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equalsIgnoreCase("getName")) {
getNameMethod = i;
}
}
} catch (IntrospectionException ex) {
System.err.println("PropertySheetPanel.setTarget(): Couldn't introspect");
return;
}
if (getNameMethod >= 0) {
try {
rep = (String) methods[getNameMethod].getMethod().invoke(m_Object, (Object[]) null);
} catch (java.lang.IllegalAccessException e1) {
} catch (java.lang.reflect.InvocationTargetException e2) {
}
}
if (rep.length() <= 0) {
rep = m_Object.getClass().getName();
int dotPos = rep.lastIndexOf('.');
if (dotPos != -1) {
rep = rep.substring(dotPos + 1);
}
}
FontMetrics fm = gfx.getFontMetrics();
int vpad = (box.height - fm.getHeight()) / 2;
gfx.drawString(rep, 2, fm.getHeight() + vpad - 2);
}
}
/** Paints a representation of the current Object.
*
* @param gfx the graphics context to use
* @param box the area we are allowed to paint into
*/
public void paintValue(Graphics gfx,Rectangle box) {
if (isEnabled && m_Object != null) {
int getNameMethod = -1;
MethodDescriptor[] methods;
String rep = "";
try {
BeanInfo beanInfo = Introspector.getBeanInfo(m_Object.getClass());
methods = beanInfo.getMethodDescriptors();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equalsIgnoreCase("getName")) getNameMethod = i;
}
} catch (IntrospectionException ex) {
System.err.println("PropertySheetPanel.setTarget(): Couldn't introspect");
return;
}
if (getNameMethod >= 0) {
try {
rep = (String)methods[getNameMethod].getMethod().invoke(m_Object, (Object[])null);
} catch (java.lang.IllegalAccessException e1) {
/**
* Returns null as we don't support getting/setting values as text.
*
* @return null
*/
public String getAsText() {
return null;
}
} catch (java.lang.reflect.InvocationTargetException e2) {
/**
* Returns null as we don't support getting/setting values as text.
*
* @param text the text value
* @exception IllegalArgumentException as we don't support getting/setting values as text.
*/
public void setAsText(String text) throws IllegalArgumentException {
throw new IllegalArgumentException(text);
}
}
}
if (rep.length() <= 0) {
rep = m_Object.getClass().getName();
int dotPos = rep.lastIndexOf('.');
if (dotPos != -1)
rep = rep.substring(dotPos + 1);
}
FontMetrics fm = gfx.getFontMetrics();
int vpad = (box.height - fm.getHeight()) / 2;
gfx.drawString(rep, 2, fm.getHeight() + vpad -2 );
} else {
}
}
/**
* Returns null as we don't support getting values as tags.
*
* @return null
*/
public String[] getTags() {
return null;
}
/**
* Returns true because we do support a custom editor.
*
* @return true
*/
public boolean supportsCustomEditor() {
return true;
}
/**
* Returns null as we don't support getting/setting values as text.
*
* @return null
*/
public String getAsText() {
return null;
}
/**
* Returns the array editing component.
*
* @return a value of type 'java.awt.Component'
*/
public Component getCustomEditor() {
if (editorComponent == null) {
editorComponent = new GOEPanel(m_Object, m_Backup, propertyChangeSupport, this);
}
return editorComponent;
}
/**
* Returns null as we don't support getting/setting values as text.
*
* @param text the text value
* @exception IllegalArgumentException as we don't support
* getting/setting values as text.
*/
public void setAsText(String text) throws IllegalArgumentException {
throw new IllegalArgumentException(text);
}
/**
*
*/
public void disableOKCancel() {
if (editorComponent == null) {
editorComponent = new GOEPanel(m_Object, m_Backup,
propertyChangeSupport, this);
}
editorComponent.setEnabledOkCancelButtons(false);
}
/**
* Returns null as we don't support getting values as tags.
*
* @return null
*/
public String[] getTags() {
return null;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
if (propertyChangeSupport == null) {
propertyChangeSupport = new PropertyChangeSupport(this);
}
propertyChangeSupport.addPropertyChangeListener(l);
}
/**
* Returns true because we do support a custom editor.
*
* @return true
*/
public boolean supportsCustomEditor() {
return true;
}
/**
* Returns the array editing component.
*
* @return a value of type 'java.awt.Component'
*/
public Component getCustomEditor() {
if (editorComponent == null)
editorComponent = new GOEPanel(m_Object, m_Backup, propertyChangeSupport, this);
return editorComponent;
}
/**
*
*/
public void disableOKCancel() {
if (editorComponent == null)
editorComponent = new GOEPanel(m_Object, m_Backup,
propertyChangeSupport, this);
editorComponent.setEnabledOkCancelButtons(false);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
if (propertyChangeSupport == null)
propertyChangeSupport = new PropertyChangeSupport(this);
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
if (propertyChangeSupport == null)
propertyChangeSupport = new PropertyChangeSupport(this);
propertyChangeSupport.removePropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
if (propertyChangeSupport == null) {
propertyChangeSupport = new PropertyChangeSupport(this);
}
propertyChangeSupport.removePropertyChangeListener(l);
}
}

View File

@ -33,6 +33,7 @@ import eva2.server.go.problems.InterfaceOptimizationTarget;
import eva2.server.go.tools.AbstractObjectEditor;
import eva2.server.go.tools.GeneralGOEProperty;
import eva2.tools.BasicResourceLoader;
import java.awt.Color;
/**
@ -127,7 +128,6 @@ public class GenericOptimizationObjectivesEditor extends JPanel implements Prope
p2.add(help, BorderLayout.NORTH);
jp.add(p2, BorderLayout.EAST);
GridBagConstraints gbConstraints = new GridBagConstraints();
this.m_Editor.add(jp, BorderLayout.NORTH);
this.updateEditor();

View File

@ -15,6 +15,8 @@ import eva2.tools.SelectedTag;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JCheckBox;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class GenericSelectableArrayEditor extends GenericArrayEditor {
protected JCheckBox[] m_BlackCheck;
@ -32,10 +34,13 @@ public class GenericSelectableArrayEditor extends GenericArrayEditor {
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);
}
pd.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosing(InternalFrameEvent e) {
super.internalFrameClosing(e);
System.exit(0);
}
});
editor.setValue(initial);
//ce.validate();

View File

@ -12,102 +12,101 @@ import java.io.Serializable;
* $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class Graph implements Serializable {
private PlotInterface m_Plotter;
private int m_GraphLabel;
private String m_Info;
/**
*
*/
public Graph(String Info, PlotInterface Plotter,int x) {
m_Info = Info;
m_Plotter = Plotter;
m_GraphLabel = x;
if (m_Plotter==null)
System.out.println("In constructor m_Plotter == null");
m_Plotter.setInfoString(m_GraphLabel,Info, (float) 1.0 );
}
/**
*
* @param Info
* @param stroke
*/
public String getInfo() {return m_Info;}
/**
*
*/
public void setInfoString(String Info,float stroke) {
m_Plotter.setInfoString(m_GraphLabel, Info,stroke);
}
/**
*
*/
public int getGraphLabel () {
return m_GraphLabel;
}
/**
*
*/
public void setConnectedPoint(double x,double y) {
m_Plotter.setConnectedPoint(x,y,m_GraphLabel);
}
/**
*
*/
public void clear() {
m_Plotter.clearGraph(m_GraphLabel);
}
/**
*
*/
public void setUnconnectedPoint(double x,double y) {
m_Plotter.setUnconnectedPoint(x,y,m_GraphLabel);
}
public int getPointCount() {
return m_Plotter.getPointCount(m_GraphLabel);
}
/**
* Add a graph to this graph object. Uses "force" for mismatching point counts, but returns false
* if force was used and points possibly have been lost.
*
* @return true if the graph could be added directly or false if the graph was added by force losing some data points
* @see PlotInterface.addGraph
*/
public boolean addGraph(Graph x) {
boolean useForce = false;
//System.out.println("adding graph " + x.getGraphLabel() + " to " + getGraphLabel());
if ((getPointCount() != 0) && (getPointCount() != x.getPointCount())) {
//System.err.println("mismatching graphs, point counts were " + getPointCount() + " " + x.getPointCount());
useForce = true;
}
m_Plotter.jump();
m_Plotter.addGraph(m_GraphLabel, x.getGraphLabel(), useForce);
return !useForce;
}
/**
* Causes the PlotInterface to interrupt the connected painting at the
* current position.
*/
public void jump() {
m_Plotter.jump();
}
public void setColorByIndex(int j) {
((Plot)m_Plotter).setColorByIndex(m_GraphLabel, j);
}
// public boolean isValid() { // this was evil in RMI, use GraphWindow instead
// //return true;
// return (m_Plotter != null) && (m_Plotter.getFunctionArea() != null);
// }
private PlotInterface plotter;
private int graphLabel;
private String infoString;
/**
*
*/
public Graph(String info, PlotInterface plotter, int x) {
infoString = info;
this.plotter = plotter;
graphLabel = x;
if (plotter == null) {
System.out.println("In constructor m_Plotter == null");
}
plotter.setInfoString(graphLabel, info, (float) 1.0);
}
/**
*
* @param Info
* @param stroke
*/
public String getInfo() {
return infoString;
}
/**
*
*/
public void setInfoString(String info, float stroke) {
plotter.setInfoString(graphLabel, info, stroke);
}
/**
*
*/
public int getGraphLabel() {
return graphLabel;
}
/**
*
*/
public void setConnectedPoint(double x, double y) {
plotter.setConnectedPoint(x, y, graphLabel);
}
/**
*
*/
public void clear() {
plotter.clearGraph(graphLabel);
}
/**
*
*/
public void setUnconnectedPoint(double x, double y) {
plotter.setUnconnectedPoint(x, y, graphLabel);
}
public int getPointCount() {
return plotter.getPointCount(graphLabel);
}
/**
* Add a graph to this graph object. Uses "force" for mismatching point counts, but returns
* false if force was used and points possibly have been lost.
*
* @return true if the graph could be added directly or false if the graph was added by force
* losing some data points
* @see PlotInterface.addGraph
*/
public boolean addGraph(Graph x) {
boolean useForce = false;
//System.out.println("adding graph " + x.getGraphLabel() + " to " + getGraphLabel());
if ((getPointCount() != 0) && (getPointCount() != x.getPointCount())) {
//System.err.println("mismatching graphs, point counts were " + getPointCount() + " " + x.getPointCount());
useForce = true;
}
plotter.jump();
plotter.addGraph(graphLabel, x.getGraphLabel(), useForce);
return !useForce;
}
/**
* Causes the PlotInterface to interrupt the connected painting at the current position.
*/
public void jump() {
plotter.jump();
}
public void setColorByIndex(int j) {
((Plot) plotter).setColorByIndex(graphLabel, j);
}
}

View File

@ -1,163 +1,164 @@
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: 320 $
* $Date: 2007-12-06 16:05:11 +0100 (Thu, 06 Dec 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: 320
* $ $Date: 2007-12-06 16:05:11 +0100 (Thu, 06 Dec 2007) $ $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.net.InetAddress;
import java.util.ArrayList;
import eva2.tools.jproxy.MainAdapterClient;
import eva2.tools.jproxy.RMIProxyRemote;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
* It represents one plot window in the client GUI.
*/
public class GraphWindow {
public static boolean TRACE = false;
static private int m_GraphCounter = -1;
static private PlotContainer m_PlotContainer;
private MainAdapterClient m_MainAdapterClient;
private PlotInterface m_Plotter;
private String m_Name;
/**
*
*/
public static GraphWindow getInstance (MainAdapterClient client,String GraphWindowName,
String strx,String stry) {
if (m_PlotContainer == null)
m_PlotContainer = new PlotContainer();
GraphWindow ret =null;
try {
// if (!m_PlotContainer.containsName(GraphWindowName)) {
// ret = new GraphWindow(client,GraphWindowName,strx,stry);
// m_PlotContainer.add(ret);
// }
// else {
// ret = m_PlotContainer.getPlot(GraphWindowName);
// }
if (m_PlotContainer.containsName(GraphWindowName)) {
ret = m_PlotContainer.getPlot(GraphWindowName);
public static boolean TRACE = false;
static private int graphCounter = -1;
static private PlotContainer plotContainer;
private MainAdapterClient mainAdapterClient;
private PlotInterface plotter;
private String name;
/**
*
*/
public static GraphWindow getInstance(MainAdapterClient client, String graphWindowName,
String strx, String stry) {
if (plotContainer == null) {
plotContainer = new PlotContainer();
}
if ((ret == null) || !(ret.isValid())) {
if (ret != null) {
m_PlotContainer.remove(ret); // remove if not valid any more
}
ret = new GraphWindow(client,GraphWindowName,strx,stry);
m_PlotContainer.add(ret);
GraphWindow ret = null;
try {
if (plotContainer.containsName(graphWindowName)) {
ret = plotContainer.getPlot(graphWindowName);
}
if ((ret == null) || !(ret.isValid())) {
if (ret != null) {
plotContainer.remove(ret); // remove if not valid any more
}
ret = new GraphWindow(client, graphWindowName, strx, stry);
plotContainer.add(ret);
}
} catch (Exception ee) {
System.out.println("GraphWindow ERROR : " + ee.getMessage());
ee.printStackTrace();
}
} catch (Exception ee) {
System.out.println("GraphWindow ERROR : "+ee.getMessage());
ee.printStackTrace();
return ret;
}
return ret;
}
public boolean isValid() {
return (m_Plotter != null) && (m_Plotter.isValid());
}
public PlotInterface getPlotter() {
return m_Plotter;
}
/**
*
*/
private GraphWindow(MainAdapterClient client,String PlotName,String strx,String stry){
if (TRACE) System.out.println("Constructor GraphWindow");
m_MainAdapterClient = client;
m_Name = PlotName;
try {
if ((client==null) || client.getHostName().equals(InetAddress.getLocalHost().getHostName())) {
if (TRACE) System.out.println("no RMI");
m_Plotter = new Plot(PlotName, strx, stry, true);
}
else {
m_Plotter = (PlotInterface) RMIProxyRemote.newInstance(new Plot(PlotName,strx,stry,false), m_MainAdapterClient);
m_Plotter.init();
if (TRACE) System.out.println("with RMI");
}
} catch (Exception e) {
System.err.println("InetAddress.getLocalHost().getHostAddress() --> ERROR" + e.getMessage());
}
}
public boolean isValid() {
return (plotter != null) && (plotter.isValid());
}
/**
*
*/
public String getName () {
return m_Name;
}
/**
*
*/
public Graph getNewGraph(String InfoString) {
m_GraphCounter++;
if (TRACE) System.out.println("Graph.getNewGraph No:"+m_GraphCounter + " - " + InfoString);
return new Graph (InfoString,m_Plotter,m_GraphCounter);
}
public PlotInterface getPlotter() {
return plotter;
}
/**
*
*/
private GraphWindow(MainAdapterClient client, String plotName, String strx, String stry) {
if (TRACE) {
System.out.println("Constructor GraphWindow");
}
mainAdapterClient = client;
name = plotName;
try {
if ((client == null) || client.getHostName().equals(InetAddress.getLocalHost().getHostName())) {
if (TRACE) {
System.out.println("no RMI");
}
plotter = new Plot(plotName, strx, stry, true);
} else {
plotter = (PlotInterface) RMIProxyRemote.newInstance(new Plot(plotName, strx, stry, false), mainAdapterClient);
plotter.init();
if (TRACE) {
System.out.println("with RMI");
}
}
} catch (Exception e) {
System.err.println("InetAddress.getLocalHost().getHostAddress() --> ERROR" + e.getMessage());
}
}
/**
*
*/
public String getName() {
return name;
}
/**
*
*/
public Graph getNewGraph(String infoString) {
graphCounter++;
if (TRACE) {
System.out.println("Graph.getNewGraph No:" + graphCounter + " - " + infoString);
}
return new Graph(infoString, plotter, graphCounter);
}
}
/**
*
*/
class PlotContainer extends ArrayList<GraphWindow> {
/**
*
*/
private static final long serialVersionUID = 4194675772084989958L;
private GraphWindow m_actualPlot;
/**
*
*/
public PlotContainer() {}
/**
*
*/
public boolean containsName (String name) {
GraphWindow temp = null;
for (int i=0;i<size();i++) {
temp = (GraphWindow)(get(i));
if (name.equals(temp.getName())) {
return true;
}
/**
*
*/
private static final long serialVersionUID = 4194675772084989958L;
private GraphWindow actualPlot;
/**
*
*/
public PlotContainer() {
}
return false;
}
public void remove(GraphWindow gw) {
super.remove(gw);
if (m_actualPlot == gw) m_actualPlot=null;
}
/**
*
*/
public GraphWindow getPlot (String name) {
if ((m_actualPlot!=null) && m_actualPlot.isValid()) {
if (m_actualPlot.getName().equals(name))
return m_actualPlot;
/**
*
*/
public boolean containsName(String name) {
GraphWindow temp = null;
for (int i = 0; i < size(); i++) {
temp = (GraphWindow) (get(i));
if (name.equals(temp.getName())) {
return true;
}
}
return false;
}
GraphWindow temp = null;
for (int i=0;i<size();i++) {
temp = (GraphWindow)(get(i));
if (name.equals(temp.getName())) {
m_actualPlot = temp;
return m_actualPlot;
}
public void remove(GraphWindow gw) {
super.remove(gw);
if (actualPlot == gw) {
actualPlot = null;
}
}
/**
*
*/
public GraphWindow getPlot(String name) {
if ((actualPlot != null) && actualPlot.isValid()) {
if (actualPlot.getName().equals(name)) {
return actualPlot;
}
}
GraphWindow temp = null;
for (int i = 0; i < size(); i++) {
temp = (GraphWindow) (get(i));
if (name.equals(temp.getName())) {
actualPlot = temp;
return actualPlot;
}
}
return null;
}
return null;
}
}

View File

@ -10,16 +10,18 @@ package eva2.gui;
* $Author: streiche $
*/
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.WindowListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.KeyStroke;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class JEFrame extends JFrame {
public class JEFrame extends JInternalFrame {
private boolean closeAllOnClose = false;
public JEFrame() {
@ -42,36 +44,35 @@ public class JEFrame extends JFrame {
}
@Override
public void addWindowListener(WindowListener l) {
super.addWindowListener(l);
public void addInternalFrameListener(InternalFrameListener l) {
super.addInternalFrameListener(l);
}
private void init() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
JEFrameRegister.unregister((JEFrame) e.getWindow());
this.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosed(InternalFrameEvent e) {
super.internalFrameClosed(e);
JEFrameRegister.getInstance().unregister((JEFrame) e.getInternalFrame());
if (closeAllOnClose) {
JEFrameRegister.closeAll();
JEFrameRegister.getInstance().closeAll();
}
// ((JFrame) e.getWindow()).dispose();
}
@Override
public void windowOpened(WindowEvent e) {
super.windowOpened(e);
JEFrameRegister.register((JEFrame) e.getWindow());
}
@Override
public void windowActivated(WindowEvent e) {
JEFrameRegister.register((JEFrame) e.getWindow());
super.windowActivated(e);
}
}
@Override
public void internalFrameOpened(InternalFrameEvent e) {
super.internalFrameOpened(e);
JEFrameRegister.getInstance().register((JEFrame) e.getInternalFrame());
}
@Override
public void internalFrameActivated(InternalFrameEvent e) {
JEFrameRegister.getInstance().register((JEFrame) e.getInternalFrame());
super.internalFrameActivated(e);
}
});
this.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK),
@ -81,8 +82,7 @@ public class JEFrame extends JFrame {
"ctrlFpressed",
new AbstractAction("ctrlFpressed") {
public void actionPerformed(ActionEvent actionEvent) {
((JEFrame) JEFrameRegister.getFrameList()[0]).setExtendedState(JEFrame.NORMAL);
((JEFrame) JEFrameRegister.getFrameList()[0]).toFront();
JEFrameRegister.getInstance().getFrameList().get(0).toFront();
}
}
);
@ -94,12 +94,10 @@ public class JEFrame extends JFrame {
"ctrlOpressed",
new AbstractAction("ctrlOpressed") {
public void actionPerformed(ActionEvent actionEvent) {
Object[] fl = JEFrameRegister.getFrameList();
for (int i = 0; i < fl.length; i++) {
((JEFrame) JEFrameRegister.getFrameList()[i]).setExtendedState(JEFrame.NORMAL);
((JEFrame) JEFrameRegister.getFrameList()[i]).toFront();
}
java.util.List<JEFrame> frameList = JEFrameRegister.getInstance().getFrameList();
for (JEFrame frame : frameList) {
frame.toFront();
}
}
}
);
@ -112,9 +110,16 @@ public class JEFrame extends JFrame {
"ctrlSmallerpressed",
new AbstractAction("ctrlSmallerpressed") {
public void actionPerformed(ActionEvent actionEvent) {
JEFrameRegister.setFocusToNext(self);
JEFrameRegister.getInstance().setFocusToNext(self);
}
}
);
this.setMaximizable(true);
this.setResizable(true);
this.setIconifiable(true);
this.setClosable(true);
}
}

View File

@ -1,5 +1,7 @@
package eva2.gui;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDesktopPane;
/*
* Title: EvA2
* Description:
@ -12,80 +14,114 @@ import java.util.ArrayList;
*/
public class JEFrameRegister {
private static ArrayList<JEFrame> JEFrameList;
public final class JEFrameRegister {
/**
* Singleton instance.
*/
private static JEFrameRegister instance = null;
static {
JEFrameList = new ArrayList<JEFrame>();
}
/**
* List of all frames maintained.
*/
private List<JEFrame> frameList;
public static void register(JEFrame jf) {
if (!JEFrameList.contains(jf)) JEFrameList.add(jf);
// System.out.println("reg " + jf.getTitle() + "/" + (jf.hashCode()) + ", list size: " + JEFrameList.size());
}
private JDesktopPane desktopPane;
public static void unregister(JEFrame jf) {
JEFrameList.remove(jf); // Plot windows produce double closing events, so ignore it
// if (!JEFrameList.remove(jf)) System.err.println("Warning: tried to unregister frame " + jf.getTitle() + " which was not registered! (JEFrameRegister)");
// System.out.println("unreg " + jf.getTitle() + "/" + jf.hashCode() + ", list size:" + JEFrameList.size());
}
private JEFrameRegister() {
this.frameList = new ArrayList<JEFrame>();
}
public static Object[] getFrameList() {
return JEFrameList.toArray();
}
public static JEFrameRegister getInstance() {
if (instance == null) {
instance = new JEFrameRegister();
}
return instance;
}
public static void setFocusToNext(JEFrame jf) {
int idx = JEFrameList.indexOf(jf);
idx = (idx + 1) % JEFrameList.size();
JEFrame toset = ((JEFrame) JEFrameList.get(idx));
toset.setExtendedState(JEFrame.NORMAL);
toset.toFront();
}
public void setDesktopPane(JDesktopPane desktopPane) {
this.desktopPane = desktopPane;
if (!frameList.isEmpty()) {
for (JEFrame frame : frameList) {
this.desktopPane.add(frame);
}
}
}
/**
* Return all prefixes which occur at least twice in the registered frame list.
* @param prefLen
* @return
*/
public static String[] getCommonPrefixes(int prefLen) {
ArrayList<String> prefixes = new ArrayList<String>();
ArrayList<Integer> count = new ArrayList<Integer>();
for (int i=0; i<JEFrameList.size(); i++) {
String title = JEFrameList.get(i).getTitle();
String titPref = title.substring(0, Math.min(prefLen, title.length()));
int earlierIndex = prefixes.indexOf(titPref);
if (earlierIndex<0) {
prefixes.add(titPref);
count.add(1);
} else count.set(earlierIndex, 1+count.get(earlierIndex));
}
for (int i=prefixes.size()-1; i>=0; i--) {
if (count.get(i)<=1) {
prefixes.remove(i);
count.remove(i);
}
}
return prefixes.toArray(new String[prefixes.size()]);
}
public void register(JEFrame jeFrame) {
if (!frameList.contains(jeFrame)) {
frameList.add(jeFrame);
/**
* Close (dispose) all frames whose title starts with a given prefix.
*
* @param prefix
*/
public static void closeAllByPrefix(String prefix) {
for (int i=0; i<JEFrameList.size(); i++) {
String title = JEFrameList.get(i).getTitle();
if (title.startsWith(prefix)) JEFrameList.get(i).dispose();
}
}
/**
* Close (dispose) all frames registered in this list.
*/
public static void closeAll() {
for (int i=0; i<JEFrameList.size(); i++) {
JEFrameList.get(i).dispose();
}
}
if (desktopPane != null) {
desktopPane.add(jeFrame);
}
}
}
public void unregister(JEFrame jeFrame) {
// Plot windows produce double closing events, so ignore it
frameList.remove(jeFrame);
}
public List<JEFrame> getFrameList() {
return frameList;
}
public void setFocusToNext(JEFrame jeFrame) {
int idx = frameList.indexOf(jeFrame);
idx = (idx + 1) % frameList.size();
JEFrame toset = ((JEFrame) frameList.get(idx));
toset.toFront();
}
/**
* Return all prefixes which occur at least twice in the registered frame list.
*
* @param prefLen Preferred length of prefixes
* @return List of prefixes
*/
public String[] getCommonPrefixes(final int prefLen) {
List<String> prefixes = new ArrayList<String>();
List<Integer> count = new ArrayList<Integer>();
for (int i = 0; i < frameList.size(); i++) {
String title = frameList.get(i).getTitle();
String titPref = title.substring(0, Math.min(prefLen, title.length()));
int earlierIndex = prefixes.indexOf(titPref);
if (earlierIndex < 0) {
prefixes.add(titPref);
count.add(1);
} else {
count.set(earlierIndex, 1 + count.get(earlierIndex));
}
}
for (int i = prefixes.size() - 1; i >= 0; i--) {
if (count.get(i) <= 1) {
prefixes.remove(i);
count.remove(i);
}
}
return prefixes.toArray(new String[prefixes.size()]);
}
/**
* Close (dispose) all frames whose title starts with a given prefix.
*
* @param prefix The prefix
*/
public void closeAllByPrefix(final String prefix) {
for (int i = 0; i < frameList.size(); i++) {
String title = frameList.get(i).getTitle();
if (title.startsWith(prefix)) {
frameList.get(i).dispose();
}
}
}
/**
* Close (dispose) all frames registered in this list.
*/
public void closeAll() {
for (int i = 0; i < frameList.size(); i++) {
frameList.get(i).dispose();
}
}
}

View File

@ -9,236 +9,278 @@ package eva2.gui;
* $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $
* $Author: streiche $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import javax.swing.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyVetoException;
import java.awt.event.*;
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
/**
*
*/
public class JExtDesktopPane extends JDesktopPane{
private ActionListener m_actMenuFrame;
private ExtDesktopManager m_manager;
public JExtMenu m_mnuWindow;
private ExtAction actWindowTileVert;
private ExtAction actWindowTileHorz;
private ExtAction actWindowOverlap;
private ExtAction actWindowArrangeIcons;
private ExtAction actWindowList;
public final static int WINDOW_TILEVERT = 0;
public final static int WINDOW_TILEHORZ = 1;
public final static int WINDOW_OVERLAP = 2;
public final static int WINDOW_ARRANGEICONS = 3;
public final static int WINDOW_LIST = 4;
public final static int TITLEBAR_HEIGHT = 25;
/**
*
*/
public JExtDesktopPane(){
super();
m_mnuWindow = new JExtMenu("&Windows");
m_manager = new ExtDesktopManager(this);
setDesktopManager(m_manager);
public class JExtDesktopPane extends JDesktopPane {
m_actMenuFrame = new ActionListener(){
public void actionPerformed(ActionEvent e){
if(!(e.getSource() instanceof JMenuItem)) return;
JInternalFrame frame = (JInternalFrame)((JMenuItem)e.getSource()).getClientProperty(ExtDesktopManager.FRAME);
selectFrame(frame);
}
private ActionListener m_actMenuFrame;
private ExtDesktopManager m_manager;
public JExtMenu m_mnuWindow;
private ExtAction actWindowTileVert;
private ExtAction actWindowTileHorz;
private ExtAction actWindowOverlap;
private ExtAction actWindowArrangeIcons;
private ExtAction actWindowList;
public final static int WINDOW_TILEVERT = 0;
public final static int WINDOW_TILEHORZ = 1;
public final static int WINDOW_OVERLAP = 2;
public final static int WINDOW_ARRANGEICONS = 3;
public final static int WINDOW_LIST = 4;
public final static int TITLEBAR_HEIGHT = 25;
};
/**
*
*/
public JExtDesktopPane() {
super();
m_mnuWindow = new JExtMenu("&Windows");
m_manager = new ExtDesktopManager(this);
setDesktopManager(m_manager);
m_mnuWindow.add(actWindowTileVert = new ExtAction("&Nebeneinander", "Ordnet die Fenster nebeneinander an"){
public void actionPerformed(ActionEvent e){
tileWindows(SwingConstants.HORIZONTAL);
}
});
m_actMenuFrame = new ActionListener() {
m_mnuWindow.add(actWindowTileHorz = new ExtAction("&Untereinander", "Ordnet die Fenster untereinander an"){
public void actionPerformed(ActionEvent e){
tileWindows(SwingConstants.VERTICAL);
}
});
public void actionPerformed(ActionEvent e) {
if (!(e.getSource() instanceof JMenuItem)) {
return;
}
JInternalFrame frame = (JInternalFrame) ((JMenuItem) e.getSource()).getClientProperty(ExtDesktopManager.FRAME);
selectFrame(frame);
}
};
m_mnuWindow.add(actWindowOverlap = new ExtAction("<EFBFBD>&berlappend", "Ordnet die Fenster <20>berlappend an"){
public void actionPerformed(ActionEvent e){
overlapWindows();
}
});
m_mnuWindow.add(actWindowTileVert = new ExtAction("&Nebeneinander", "Ordnet die Fenster nebeneinander an") {
m_mnuWindow.add(actWindowArrangeIcons = new ExtAction("&Symbole anordnen", "Ordnet die Symbole auf dem Desktop an"){
public void actionPerformed(ActionEvent e){
}
});
public void actionPerformed(ActionEvent e) {
tileWindows(SwingConstants.HORIZONTAL);
}
});
m_mnuWindow.add(actWindowList = new ExtAction("Fenster&liste...", "Zeigt eine Liste aller Fenster an", KeyStroke.getKeyStroke(KeyEvent.VK_0, Event.ALT_MASK)){
public void actionPerformed(ActionEvent e){
Vector l = new Vector();
JInternalFrame frames[] = getAllFrames();
m_mnuWindow.add(actWindowTileHorz = new ExtAction("&Untereinander", "Ordnet die Fenster untereinander an") {
for(int i = 0; i < frames.length; i++)
l.add(frames[i].getTitle());
public void actionPerformed(ActionEvent e) {
tileWindows(SwingConstants.VERTICAL);
}
});
JList list = new JList(l);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane pane = new JScrollPane(list);
pane.setPreferredSize(new Dimension(pane.getPreferredSize().width, 150));
m_mnuWindow.add(actWindowOverlap = new ExtAction("Ü&berlappend", "Ordnet die Fenster Überlappend an") {
if(JOptionPane.showOptionDialog(JExtDesktopPane.this, pane, "Fenster ausw<73>hlen", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION)
if(list.getSelectedIndex() != -1) selectFrame(frames[list.getSelectedIndex()]);
}
});
public void actionPerformed(ActionEvent e) {
overlapWindows();
}
});
m_mnuWindow.addSeparator();
m_manager.WINDOW_LIST_START = 6;
}
m_mnuWindow.add(actWindowArrangeIcons = new ExtAction("&Symbole anordnen", "Ordnet die Symbole auf dem Desktop an") {
public ExtAction getWindowAction(int action){
switch(action){
case WINDOW_TILEVERT: return actWindowTileVert;
case WINDOW_TILEHORZ: return actWindowTileHorz;
case WINDOW_OVERLAP: return actWindowOverlap;
case WINDOW_ARRANGEICONS: return actWindowArrangeIcons;
case WINDOW_LIST: return actWindowList;
public void actionPerformed(ActionEvent e) {
}
});
m_mnuWindow.add(actWindowList = new ExtAction("Fenster&liste...", "Zeigt eine Liste aller Fenster an", KeyStroke.getKeyStroke(KeyEvent.VK_0, Event.ALT_MASK)) {
public void actionPerformed(ActionEvent e) {
Vector l = new Vector();
JInternalFrame frames[] = getAllFrames();
for (int i = 0; i < frames.length; i++) {
l.add(frames[i].getTitle());
}
JList list = new JList(l);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane pane = new JScrollPane(list);
pane.setPreferredSize(new Dimension(pane.getPreferredSize().width, 150));
if (JOptionPane.showOptionDialog(JExtDesktopPane.this, pane, "Fenster auswählen", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) {
if (list.getSelectedIndex() != -1) {
selectFrame(frames[list.getSelectedIndex()]);
}
}
}
});
m_mnuWindow.addSeparator();
m_manager.WINDOW_LIST_START = 6;
}
return null;
}
public void overlapWindows(){
final int minWidth = 150, minHeight = 100;
int fWidth, fHeight,
oCount, i, indent;
JInternalFrame[] frames = getOpenFrames();
if(frames.length == 0) return;
oCount = Math.min(frames.length, Math.min((getWidth() - minWidth) / TITLEBAR_HEIGHT + 1, (getHeight() - minHeight) / TITLEBAR_HEIGHT + 1));
fWidth = getWidth() - (oCount - 1) * TITLEBAR_HEIGHT;
fHeight = getHeight() - (oCount - 1) * TITLEBAR_HEIGHT;
indent = 0;
for(i = 0; i < frames.length; i++){
frames[frames.length - i - 1].setLocation(indent * TITLEBAR_HEIGHT, indent * TITLEBAR_HEIGHT);
frames[frames.length - i - 1].setSize(fWidth, fHeight);
indent = (i + 1) % oCount == 0 ? 0 : indent + 1;
}
}
/**
*
*/
public void tileWindows(int orientation){
int rows, cols,
rHeight, cWidth,
row, col,
i;
JInternalFrame[] frames = getOpenFrames();
if(frames.length == 0) return;
if(orientation == SwingConstants.HORIZONTAL){
rows = (int)(Math.rint(Math.sqrt(frames.length) - 0.49));
cols = frames.length / rows;
rHeight = getHeight() / rows;
cWidth = getWidth() / cols;
row = col = 0;
for(i = 0; i < frames.length; i++){
frames[i].setLocation(col * cWidth, row * rHeight);
frames[i].setSize(cWidth, rHeight);
if(col == cols - 1){
row++;
col = 0;
public ExtAction getWindowAction(int action) {
switch (action) {
case WINDOW_TILEVERT:
return actWindowTileVert;
case WINDOW_TILEHORZ:
return actWindowTileHorz;
case WINDOW_OVERLAP:
return actWindowOverlap;
case WINDOW_ARRANGEICONS:
return actWindowArrangeIcons;
case WINDOW_LIST:
return actWindowList;
}
else col++;
if(row > 0 && frames.length - i - (cols + 1) * (rows - row) > 0){
cols++;
cWidth = getWidth() / cols;
return null;
}
public void overlapWindows() {
final int minWidth = 150, minHeight = 100;
int fWidth, fHeight,
oCount, i, indent;
JInternalFrame[] frames = getOpenFrames();
if (frames.length == 0) {
return;
}
}
}
else if(orientation == SwingConstants.VERTICAL){
cols = (int)(Math.rint(Math.sqrt(frames.length) - 0.49));
rows = frames.length / cols;
cWidth = getWidth() / cols;
rHeight = getHeight() / rows;
col = row = 0;
for(i = 0; i < frames.length; i++){
frames[i].setLocation(col * cWidth, row * rHeight);
frames[i].setSize(cWidth, rHeight);
if(row == rows - 1){
col++;
row = 0;
oCount = Math.min(frames.length, Math.min((getWidth() - minWidth) / TITLEBAR_HEIGHT + 1, (getHeight() - minHeight) / TITLEBAR_HEIGHT + 1));
fWidth = getWidth() - (oCount - 1) * TITLEBAR_HEIGHT;
fHeight = getHeight() - (oCount - 1) * TITLEBAR_HEIGHT;
indent = 0;
for (i = 0; i < frames.length; i++) {
frames[frames.length - i - 1].setLocation(indent * TITLEBAR_HEIGHT, indent * TITLEBAR_HEIGHT);
frames[frames.length - i - 1].setSize(fWidth, fHeight);
indent = (i + 1) % oCount == 0 ? 0 : indent + 1;
}
else row++;
if(col > 0 && frames.length - i - (rows + 1) * (cols - col) > 0){
rows++;
rHeight = getHeight() / rows;
}
/**
*
*/
public void tileWindows(int orientation) {
int rows, cols,
rHeight, cWidth,
row, col,
i;
JInternalFrame[] frames = getOpenFrames();
if (frames.length == 0) {
return;
}
}
}
}
public JInternalFrame[] getOpenFrames(){
JInternalFrame[] result;
Vector vResults = new Vector(10);
Component tmp;
for(int i = 0; i < getComponentCount(); i++){
tmp = getComponent(i);
if(tmp instanceof JInternalFrame) vResults.addElement(tmp);
if (orientation == SwingConstants.HORIZONTAL) {
rows = (int) (Math.rint(Math.sqrt(frames.length) - 0.49));
cols = frames.length / rows;
rHeight = getHeight() / rows;
cWidth = getWidth() / cols;
row = col = 0;
for (i = 0; i < frames.length; i++) {
frames[i].setLocation(col * cWidth, row * rHeight);
frames[i].setSize(cWidth, rHeight);
if (col == cols - 1) {
row++;
col = 0;
} else {
col++;
}
if (row > 0 && frames.length - i - (cols + 1) * (rows - row) > 0) {
cols++;
cWidth = getWidth() / cols;
}
}
} else if (orientation == SwingConstants.VERTICAL) {
cols = (int) (Math.rint(Math.sqrt(frames.length) - 0.49));
rows = frames.length / cols;
cWidth = getWidth() / cols;
rHeight = getHeight() / rows;
col = row = 0;
for (i = 0; i < frames.length; i++) {
frames[i].setLocation(col * cWidth, row * rHeight);
frames[i].setSize(cWidth, rHeight);
if (row == rows - 1) {
col++;
row = 0;
} else {
row++;
}
if (col > 0 && frames.length - i - (rows + 1) * (cols - col) > 0) {
rows++;
rHeight = getHeight() / rows;
}
}
}
}
result = new JInternalFrame[vResults.size()];
vResults.copyInto(result);
public JInternalFrame[] getOpenFrames() {
JInternalFrame[] result;
Vector vResults = new Vector(10);
Component tmp;
return result;
}
public int getFrameCount(){
return getComponentCount(new ComponentFilter(){
public boolean accept(Component c){
return c instanceof JInternalFrame ||
(c instanceof JInternalFrame.JDesktopIcon &&
((JInternalFrame.JDesktopIcon)c).getInternalFrame() != null);
}
});
}
public int getComponentCount(ComponentFilter c){
int result = 0;
for(int i = 0; i < getComponentCount(); i++) if(c.accept(getComponent(i))) result++;
return result;
}
public void selectFrame(JInternalFrame f){
if(f != null){
try{
if(f.isIcon()) f.setIcon(false);
else f.setSelected(true);
}
catch(PropertyVetoException exc){}
for (int i = 0; i < getComponentCount(); i++) {
tmp = getComponent(i);
if (tmp instanceof JInternalFrame) {
vResults.addElement(tmp);
}
}
result = new JInternalFrame[vResults.size()];
vResults.copyInto(result);
return result;
}
}
public void addImpl(Component comp, Object constraints, int index){
super.addImpl(comp, constraints, index);
//System.out.println("JExtDesktopPane.addImpl");
if(comp instanceof JDocFrame){
JDocFrame f = (JDocFrame)comp;
int frameIndex = m_mnuWindow.getItemCount() - m_manager.WINDOW_LIST_START + 1;
if(f.getClientProperty(ExtDesktopManager.INDEX) != null) return;
f.putClientProperty(ExtDesktopManager.INDEX, new Integer(frameIndex));
JMenuItem m = new JMenuItem((frameIndex < 10 ? frameIndex + " " : "") + f.getTitle());
if(frameIndex < 10){
m.setMnemonic((char)(0x30 + frameIndex));
m.setAccelerator(KeyStroke.getKeyStroke(0x30 + frameIndex, Event.ALT_MASK));
}
m.setToolTipText("Shows the window " + f.getTitle() + " an");
m.putClientProperty(ExtDesktopManager.FRAME, f);
m.addActionListener(m_actMenuFrame);
m_mnuWindow.add(m);
public int getFrameCount() {
return getComponentCount(new ComponentFilter() {
public boolean accept(Component c) {
return c instanceof JInternalFrame
|| (c instanceof JInternalFrame.JDesktopIcon
&& ((JInternalFrame.JDesktopIcon) c).getInternalFrame() != null);
}
});
}
public int getComponentCount(ComponentFilter c) {
int result = 0;
for (int i = 0; i < getComponentCount(); i++) {
if (c.accept(getComponent(i))) {
result++;
}
}
return result;
}
public void selectFrame(JInternalFrame f) {
if (f != null) {
try {
if (f.isIcon()) {
f.setIcon(false);
} else {
f.setSelected(true);
}
} catch (PropertyVetoException exc) {
}
}
}
public void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
//System.out.println("JExtDesktopPane.addImpl");
if (comp instanceof JDocFrame) {
JDocFrame f = (JDocFrame) comp;
int frameIndex = m_mnuWindow.getItemCount() - m_manager.WINDOW_LIST_START + 1;
if (f.getClientProperty(ExtDesktopManager.INDEX) != null) {
return;
}
f.putClientProperty(ExtDesktopManager.INDEX, new Integer(frameIndex));
JMenuItem m = new JMenuItem((frameIndex < 10 ? frameIndex + " " : "") + f.getTitle());
if (frameIndex < 10) {
m.setMnemonic((char) (0x30 + frameIndex));
m.setAccelerator(KeyStroke.getKeyStroke(0x30 + frameIndex, Event.ALT_MASK));
}
m.setToolTipText("Shows the window " + f.getTitle() + " an");
m.putClientProperty(ExtDesktopManager.FRAME, f);
m.addActionListener(m_actMenuFrame);
m_mnuWindow.add(m);
}
// if(comp instanceof Plot){
// Plot f = (Plot)comp;
// int frameIndex = m_mnuWindow.getItemCount() - m_manager.WINDOW_LIST_START + 1;
@ -254,8 +296,9 @@ public class JExtDesktopPane extends JDesktopPane{
// m.addActionListener(m_actMenuFrame);
// m_mnuWindow.add(m);
// }
}
public JMenu getWindowMenu(){
return m_mnuWindow;
}
}
public JMenu getWindowMenu() {
return m_mnuWindow;
}
}

View File

@ -9,13 +9,11 @@ package eva2.gui;
* $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $
* $Author: streiche $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.Insets;
import java.beans.*;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
/**
*
*/

View File

@ -7,33 +7,25 @@ package eva2.gui;
* Company: University of Tuebingen, Computer Architecture
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import eva2.server.stat.EvAJobList;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.io.Serializable;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JPanel;
import eva2.server.stat.EvAJobList;
public class JParaPanel implements Serializable, PanelMaker {
public static boolean TRACE = false;
protected String m_Name = "undefined";
protected Object m_LocalParameter;
protected Object m_ProxyParameter;
protected PropertyEditor m_Editor;
private JPanel m_Panel;
protected String name = "undefined";
protected Object localParameter;
protected Object proxyParameter;
protected PropertyEditor propertyEditor;
/**
* ToDo: Should be removed in future.
*/
private JPanel tempPanel = new JPanel();
public JParaPanel() {
}
@ -41,44 +33,36 @@ public class JParaPanel implements Serializable, PanelMaker {
/**
*/
public JParaPanel(Object Parameter, String name) {
m_Name = name;
m_LocalParameter = Parameter;
this.name = name;
localParameter = Parameter;
}
/**
*/
public JComponent makePanel() {
m_Panel = new JPanel();
//m_Panel.setPreferredSize(new Dimension(200, 200)); // MK: this was evil, killing all the auto-layout mechanisms
PropertyEditorProvider.installEditors();
if (m_LocalParameter instanceof EvAJobList) {
m_Editor = EvAJobList.makeEditor(m_Panel, (EvAJobList)m_LocalParameter);
if (localParameter instanceof EvAJobList) {
/* ToDo: First parameter is useless and should be removed */
propertyEditor = EvAJobList.makeEditor(tempPanel, (EvAJobList) localParameter);
} else {
m_Editor = new GenericObjectEditor();
((GenericObjectEditor) (m_Editor)).setClassType(m_LocalParameter.getClass());
((GenericObjectEditor) (m_Editor)).setValue(m_LocalParameter);
((GenericObjectEditor) (m_Editor)).disableOKCancel();
propertyEditor = new GenericObjectEditor();
((GenericObjectEditor) (propertyEditor)).setClassType(localParameter.getClass());
((GenericObjectEditor) (propertyEditor)).setValue(localParameter);
((GenericObjectEditor) (propertyEditor)).disableOKCancel();
}
m_Panel.setLayout(new BorderLayout());
m_Panel.add(m_Editor.getCustomEditor(), BorderLayout.CENTER);
m_Panel.setLayout(new FlowLayout(FlowLayout.TRAILING, 10, 10));
m_Panel.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
m_Panel.setLayout(new GridBagLayout());
m_Panel.add(Box.createRigidArea(new Dimension(0, 10)));
return m_Panel;
return (JComponent) propertyEditor.getCustomEditor();
}
/**
*/
public String getName() {
return m_Name;
return name;
}
public PropertyEditor getEditor() {
return m_Editor;
return propertyEditor;
}
/** This method will allow you to add a new Editor to a given class
@ -90,7 +74,6 @@ public class JParaPanel implements Serializable, PanelMaker {
try {
PropertyEditorManager.registerEditor(object, editor);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
return false;
}

View File

@ -9,57 +9,48 @@ package eva2.gui;
* $Date: 2007-11-15 14:58:12 +0100 (Thu, 15 Nov 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import eva2.EvAInfo;
import eva2.server.go.tools.FileTools;
import eva2.tools.BasicResourceLoader;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.Serializable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/**
*
*/
public class JTextoutputFrame implements JTextoutputFrameInterface,
ActionListener,
Serializable {
private JMenuItem clearItem, saveItem;
public static boolean TRACE = false;
protected String m_Name ="undefined";
private transient JTextArea m_TextArea = null;
// private boolean m_firstprint = true;
private final JFrame frame;
JPopupMenu popup;
public class JTextoutputFrame implements JTextoutputFrameInterface, ActionListener, Serializable {
private JMenuItem clearItem, saveItem;
public static boolean TRACE = false;
protected String frameTitle = "undefined";
private transient JTextArea textArea = null;
private final JInternalFrame frame;
private JPopupMenu popup;
/**
*
*/
public JTextoutputFrame(String Title) {
public JTextoutputFrame(String title) {
if (TRACE) System.out.println("JTextoutputFrame Constructor");
m_Name = Title;
frame = new JEFrame(m_Name);
m_TextArea = null;
frameTitle = title;
frame = new JEFrame(frameTitle);
textArea = null;
}
/**
*
*/
public void print(String Text) {
public void print(String text) {
//System.out.println("Print:"+Text);
if (m_TextArea == null) {
if (textArea == null) {
createFrame();
}
m_TextArea.append(Text);
m_TextArea.repaint();
textArea.append(text);
textArea.repaint();
}
public void println(String txt) {
@ -70,9 +61,9 @@ Serializable {
if (frame.isVisible() != bShow) {
if (frame.isVisible()) {
frame.dispose();
m_TextArea.setText(null);
textArea.setText(null);
} else {
if (m_TextArea == null) createFrame();
if (textArea == null) createFrame();
else frame.setVisible(true);
frame.setEnabled(true);
}
@ -84,26 +75,29 @@ Serializable {
*/
private void createFrame() {
if (TRACE) System.out.println("JTextoutputFrame createFrame");
m_TextArea = new JTextArea(10,80);
m_TextArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
m_TextArea.setLineWrap(true);
m_TextArea.setWrapStyleWord(true);
m_TextArea.setEditable(false);
m_TextArea.setCaretPosition(0);
textArea = new JTextArea(10,80);
textArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
textArea.setCaretPosition(0);
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
//frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
frame.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosing(InternalFrameEvent e) {
super.internalFrameClosing(e);
frame.dispose();
frame.setEnabled(false);
}
}
});
frame.getContentPane().setLayout(new BorderLayout());
//frame.getContentPane().add(new JScrollPane(m_TextArea), BorderLayout.CENTER);
final JScrollPane scrollpane = new JScrollPane(m_TextArea);
final JScrollPane scrollpane = new JScrollPane(textArea);
frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
scrollpane.getViewport().addChangeListener(new ChangeListener() {
private int lastHeight;
@ -122,23 +116,7 @@ Serializable {
frame.pack();
frame.setSize(800, 400);
frame.setVisible(true);
frame.setState(Frame.ICONIFIED);
}
/**
*output
*/
public static void main( String[] args ){
JTextoutputFrame test = new JTextoutputFrame("hi");
while (test.frame.isEnabled()) {
test.print("Test 12345");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Done!");
// frame.setState(Frame.ICONIFIED);
}
@ -158,7 +136,7 @@ Serializable {
//Add listener to components that can bring up popup menus.
MouseListener popupListener = new PopupListener(popup);
// frame.addMouseListener(popupListener);
m_TextArea.addMouseListener(popupListener);
textArea.addMouseListener(popupListener);
// menuBar.addMouseListener(popupListener);
@ -167,9 +145,9 @@ Serializable {
public void actionPerformed(ActionEvent e) {
JMenuItem src = (JMenuItem)e.getSource();
if (src == clearItem) {
m_TextArea.setText(null);
textArea.setText(null);
} else if (src == saveItem) {
FileTools.saveObjectWithFileChooser(frame, m_TextArea.getText());
FileTools.saveObjectWithFileChooser(frame, textArea.getText());
// File outfile = FileTools.writeString("TextOutput.txt", m_TextArea.getText());
} else System.err.println("Unknown popup component (JTextoutputFrame)!");
}

View File

@ -28,6 +28,7 @@ import javax.swing.event.ChangeListener;
import eva2.EvAInfo;
import eva2.tools.BasicResourceLoader;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
@ -51,20 +52,21 @@ public class LoggingPanel extends JPanel {
*/
public LoggingPanel(Logger logger) {
this.logger = logger;
loggingTextArea.setEditable(false);
loggingTextArea.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
loggingTextArea.setEditable(false);
loggingTextArea.setLineWrap(true);
loggingTextArea.setBorder(BorderFactory.createEmptyBorder());
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createTitledBorder("Info"));
setLayout(new BorderLayout());
add(new JLabel("Info"), BorderLayout.PAGE_START);
this.loggingHandler = new LoggingHandler(this);
logger.addHandler(loggingHandler);
mainPanel.setLayout(new BorderLayout());
final JScrollPane scrollpane = new JScrollPane(loggingTextArea);
scrollpane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
// scrollpane.setAutoscrolls(false);
mainPanel.add(scrollpane, BorderLayout.CENTER);
add(scrollpane, BorderLayout.CENTER);
scrollpane.getViewport().addChangeListener(new ChangeListener() {
private int lastHeight;
//
@ -78,8 +80,6 @@ public class LoggingPanel extends JPanel {
}
}
});
setLayout(new BorderLayout());
add(mainPanel, BorderLayout.CENTER);
}
/**
*

View File

@ -10,38 +10,46 @@ package eva2.gui;
/**
*
*/
class Mnemonic{
private char mnemonic;
private String text;
/**
*
*/
public Mnemonic(String s){
setString(s);
}
/**
*
*/
public void setString(String s){
StringBuffer buf = new StringBuffer(s);
for(int i = 0; i < buf.length(); i++)
if(buf.charAt(i) == '&'){
buf.deleteCharAt(i);
i++;
if(i < buf.length() && buf.charAt(i) != '&') mnemonic = buf.charAt(i - 1);
}
text = buf.toString();
}
/**
*
*/
public char getMnemonic(){
return mnemonic;
}
/**
*
*/
public String getText(){
return text;
}
class Mnemonic {
private char mnemonic;
private String text;
/**
*
*/
public Mnemonic(String s) {
setString(s);
}
/**
*
*/
public void setString(String s) {
StringBuffer buf = new StringBuffer(s);
for (int i = 0; i < buf.length(); i++) {
if (buf.charAt(i) == '&') {
buf.deleteCharAt(i);
i++;
if (i < buf.length() && buf.charAt(i) != '&') {
mnemonic = buf.charAt(i - 1);
}
}
}
text = buf.toString();
}
/**
*
*/
public char getMnemonic() {
return mnemonic;
}
/**
*
*/
public String getText() {
return text;
}
}

View File

@ -48,6 +48,9 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.populations.Population;
import eva2.tools.BasicResourceLoader;
import eva2.tools.chart2d.DPointSet;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/*==========================================================================*
* CLASS DECLARATION
@ -68,7 +71,7 @@ public class Plot implements PlotInterface, Serializable {
private String m_xname;
private String m_yname;
protected FunctionArea m_PlotArea;
protected JFrame m_Frame;
protected JInternalFrame m_Frame;
/**
* You might want to try to assign the x-range as x and y-range as y array
@ -221,7 +224,7 @@ public class Plot implements PlotInterface, Serializable {
m_Frame = new JEFrame("Plot: " + m_PlotName);
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
// m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
m_ButtonPanel = new JPanel();
m_PlotArea = new FunctionArea(m_xname, m_yname);
@ -233,12 +236,15 @@ public class Plot implements PlotInterface, Serializable {
m_Frame.getContentPane().add(m_ButtonPanel, "South");
m_Frame.getContentPane().add(m_PlotArea, "Center"); // north was not so
// nice
m_Frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
m_PlotArea.clearAll(); // this was a memory leak
m_Frame.addInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameClosing(InternalFrameEvent e) {
super.internalFrameClosing(e);
m_PlotArea.clearAll(); // this was a memory leak
m_PlotArea = null;
m_Frame.dispose();
}
}
});
m_Frame.pack();
m_Frame.setVisible(true);

View File

@ -1,17 +1,10 @@
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: 14 $
* $Date: 2006-12-18 16:32:23 +0100 (Mon, 18 Dec 2006) $
* $Author: marcekro $
* Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher @version: $Revision: 14 $
* $Date: 2006-12-18 16:32:23 +0100 (Mon, 18 Dec 2006) $ $Author: marcekro $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Toolkit;
@ -20,55 +13,57 @@ import java.beans.PropertyEditor;
import eva2.EvAInfo;
import eva2.tools.BasicResourceLoader;
import eva2.tools.EVAHELP;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
*
*/
public class PropertyDialog extends JEFrame {
private PropertyEditor m_Editor;
private Component m_EditorComponent;
/**
*
*/
public PropertyDialog (PropertyEditor editor,String Title, int x, int y) {
super(getFrameNameFromEditor(editor)); // that was the long class name !!
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
//System.out.println("PropertyDialog.Constructor of "+ Title);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
m_Editor = editor;
m_EditorComponent = editor.getCustomEditor();
getContentPane().add(m_EditorComponent, BorderLayout.CENTER);
pack();
setLocation(x, y);
setVisible(true);
}
protected static String getFrameNameFromEditor(PropertyEditor editor) {
if (editor.getValue().getClass().isArray()) {
return "Array of " + EVAHELP.cutClassName(editor.getValue().getClass().getComponentType().getName());
} else return EVAHELP.cutClassName(editor.getValue().getClass().getName());
}
/**
* Update the name of the dialogue from an editor instance.
*
* @param editor
*/
public void updateFrameTitle(PropertyEditor editor) {
setTitle(getFrameNameFromEditor(editor));
}
/**
*
*/
public PropertyEditor getEditor() {
return m_Editor;
}
}
public class PropertyDialog extends JDialog {
private PropertyEditor propertyEditor;
private Component editorComponent;
/**
*
*/
public PropertyDialog(PropertyEditor editor, String title, int x, int y) {
super();
setTitle(getFrameNameFromEditor(editor));
//super(getFrameNameFromEditor(editor)); // that was the long class name !!
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setLayout(new BorderLayout());
propertyEditor = editor;
editorComponent = editor.getCustomEditor();
add(editorComponent, BorderLayout.CENTER);
pack();
setLocation(x, y);
setVisible(true);
}
protected static String getFrameNameFromEditor(PropertyEditor editor) {
if (editor.getValue().getClass().isArray()) {
return "Array of " + EVAHELP.cutClassName(editor.getValue().getClass().getComponentType().getName());
} else {
return EVAHELP.cutClassName(editor.getValue().getClass().getName());
}
}
/**
* Update the name of the dialogue from an editor instance.
*
* @param editor
*/
public void updateFrameTitle(PropertyEditor editor) {
setTitle(getFrameNameFromEditor(editor));
}
/**
*
*/
public PropertyEditor getEditor() {
return propertyEditor;
}
}

View File

@ -9,69 +9,71 @@ package eva2.gui;
* $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $
* $Author: streiche $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import eva2.tools.EVAHELP;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyEditor;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import eva2.tools.EVAHELP;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class PropertyPanel extends JPanel {
private PropertyEditor m_PropertyEditor;
private PropertyDialog m_PropertyDialog;
private PropertyEditor propertyEditor;
private PropertyDialog propertyDialog;
private JLabel textLabel;
/**
*
*/
public PropertyPanel(PropertyEditor Editor) {
setBorder(BorderFactory.createEtchedBorder());
public PropertyPanel(PropertyEditor editor) {
setToolTipText("Click to edit properties for this object");
setOpaque(true);
m_PropertyEditor = Editor;
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (m_PropertyEditor.getValue() != null) {
setLayout(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.gridx = 0;
gbConstraints.gridy = 0;
gbConstraints.weightx = 1.0;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
propertyEditor = editor;
textLabel = new JLabel();
add(textLabel, gbConstraints);
JButton dialogButton = new JButton("...");
dialogButton.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.LIGHT_GRAY));
dialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent event) {
if (propertyEditor.getValue() != null) {
showDialog(getLocationOnScreen().x, getLocationOnScreen().y);
}
}
});
Dimension newPref = getPreferredSize();
newPref.height = getFontMetrics(getFont()).getHeight() * 6 / 4; //6 / 4;
newPref.width = newPref.height * 6; //5
setPreferredSize(newPref);
}
});
gbConstraints.weighty = 1.0;
gbConstraints.fill = GridBagConstraints.VERTICAL;
gbConstraints.anchor = GridBagConstraints.LINE_END;
gbConstraints.gridx = 1;
add(dialogButton, gbConstraints);
}
public void showDialog(int initX, int initY) {
if (m_PropertyDialog == null) {
// int x = getLocationOnScreen().x;
// int y = getLocationOnScreen().y;
m_PropertyDialog = new PropertyDialog(m_PropertyEditor, EVAHELP.cutClassName(m_PropertyEditor.getClass().getName()) , initX, initY);
m_PropertyDialog.setPreferredSize(new Dimension(500,300));
if (propertyDialog == null) {
propertyDialog = new PropertyDialog(propertyEditor, EVAHELP.cutClassName(propertyEditor.getClass().getName()) , initX, initY);
propertyDialog.setPreferredSize(new Dimension(500,300));
propertyDialog.setVisible(true);
}
else {
m_PropertyDialog.updateFrameTitle(m_PropertyEditor);
// System.out.println("" + BeanInspector.toString(m_PropertyDialog));
m_PropertyDialog.setVisible(false);
m_PropertyDialog.setExtendedState(JFrame.NORMAL);
m_PropertyDialog.setVisible(true);
m_PropertyDialog.requestFocus();
// System.out.println("" + BeanInspector.toString(m_PropertyDialog));
// System.out.println("Aft: " + m_PropertyDialog.isShowing() + " " + m_PropertyDialog.isVisible() + " " + m_PropertyDialog.isActive() + " " + m_PropertyDialog.isFocused());
propertyDialog.updateFrameTitle(propertyEditor);
propertyDialog.setVisible(false);
propertyDialog.setVisible(true);
propertyDialog.requestFocus();
}
}
@ -79,15 +81,8 @@ public class PropertyPanel extends JPanel {
*
*/
public void removeNotify() {
if (m_PropertyDialog != null) {
// System.out.println(" m_PropertyDialog.dispose();");
// System.out.println(m_PropertyDialog.isActive());
// System.out.println(m_PropertyDialog.isVisible());
// System.out.println(m_PropertyDialog.isValid());
// System.out.println(m_PropertyDialog.isDisplayable());
// if (m_PropertyDialog.isDisplayable()) m_PropertyDialog.dispose(); // this caused a deadlock!
// m_PropertyDialog.dispose(); // this also caused a deadlock!
m_PropertyDialog = null;
if (propertyDialog != null) {
propertyDialog = null;
}
}
@ -95,21 +90,21 @@ public class PropertyPanel extends JPanel {
*
*/
public void paintComponent(Graphics g) {
Insets i = getInsets();
Insets i = textLabel.getInsets();
Rectangle box = new Rectangle(i.left, i.top,
getSize().width - i.left - i.right ,
getSize().height - i.top - i.bottom);
g.clearRect(i.left, i.top,
getSize().width - i.right - i.left,
getSize().height - i.bottom - i.top);
m_PropertyEditor.paintValue(g, box);
propertyEditor.paintValue(g, box);
// Rectangle box = new Rectangle(i.left,i.top,
// this.getWidth() - i.right,
// this.getHeight() - i.bottom );
}
public PropertyEditor getEditor() {
return m_PropertyEditor;
return propertyEditor;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -27,30 +27,29 @@ import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class PropertySheetPanelStat extends JPanel implements Serializable {
public final static boolean TRACE = false;
private Object[] m_Values;
private JCheckBoxFlag[] m_Views;
private JLabel[] m_Labels;
private boolean[] m_flag;
/**
* Creates the property sheet panel.
*/
public PropertySheetPanelStat() {
// setBorder(BorderFactory.createLineBorder(Color.red));
setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
}
/** A support object for handling property change listeners */
/**
* A support object for handling property change listeners
*/
private PropertyChangeSupport m_support = new PropertyChangeSupport(this);
public synchronized void setTarget(String[] names, boolean[] flag) {
int componentOffset = 0;
// Close any child windows at this point
@ -60,8 +59,6 @@ public class PropertySheetPanelStat extends JPanel implements Serializable {
setVisible(false);
int rowHeight = 12;
JTextArea jt = new JTextArea();
JScrollPane js = null;
m_Values = new Object[flag.length];
m_Views = new JCheckBoxFlag[flag.length];
@ -69,23 +66,25 @@ public class PropertySheetPanelStat extends JPanel implements Serializable {
for (int i = 0; i < names.length; i++) {
m_Labels[i] = new JLabel(names[i], SwingConstants.RIGHT);
m_Labels[i].setBorder(BorderFactory.createEmptyBorder(10,10,0,5));
m_Labels[i].setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 5));
m_Views[i] = new JCheckBoxFlag(flag[i]);
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.EAST;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.gridy = i+componentOffset; gbConstraints.gridx = 0;
gbConstraints.gridy = i + componentOffset;
gbConstraints.gridx = 0;
gbLayout.setConstraints(m_Labels[i], gbConstraints);
add(m_Labels[i]);
JPanel newPanel = new JPanel();
newPanel.setBorder(BorderFactory.createEmptyBorder(10,5,0,10));
newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10));
newPanel.setLayout(new BorderLayout());
newPanel.add(m_Views[i], BorderLayout.CENTER);
gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.WEST;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.gridy = i+componentOffset; gbConstraints.gridx = 1;
gbConstraints.gridy = i + componentOffset;
gbConstraints.gridx = 1;
gbConstraints.weightx = 100;
gbLayout.setConstraints(newPanel, gbConstraints);
add(newPanel);
@ -93,28 +92,32 @@ public class PropertySheetPanelStat extends JPanel implements Serializable {
validate();
setVisible(true);
}
/**
*
*/
public boolean[] getState() {
boolean[] ret = new boolean[this.m_Views.length];
for (int i=0;i<ret.length;i++) {
for (int i = 0; i < ret.length; i++) {
ret[i] = m_Views[i].isSelected();
}
return ret;
}
}
/**
*
*/
class JCheckBoxFlag extends JCheckBox {
private boolean m_Flag = true;
public JCheckBoxFlag (boolean flag) {
public JCheckBoxFlag(boolean flag) {
super();
m_Flag = flag;
addItemListener(new ItemListener () {
public void itemStateChanged (ItemEvent evt) {
addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == evt.SELECTED) {
m_Flag = true;
}
@ -126,5 +129,3 @@ class JCheckBoxFlag extends JCheckBox {
}
}

View File

@ -1,98 +1,104 @@
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: 10 $
* $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $
* $Author: streiche $
* Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Architecture @author Holger Ulmer, Felix Streichert, Hannes Planatscher @version: $Revision: 10 $
* $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ $Author: streiche $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
*/
class PropertySlider extends JPanel {
private PropertyEditor m_Editor;
private JSlider m_Slider;
/**
*
*/
PropertySlider(PropertyEditor pe) {
//super(pe.getAsText());
m_Editor = pe;
//setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
//setBorder(new TitledBorder(getString("SliderDemo.plain")));
m_Slider = new JSlider(-10, 90, 20);
//s.getAccessibleContext().setAccessibleName(getString("SliderDemo.plain"));
//s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.a_plain_slider"));
m_Slider.addChangeListener(new SliderListener());
m_Slider.setValue(((Integer)m_Editor.getValue()).intValue());
m_Slider.setPaintTicks(true);
m_Slider.setMajorTickSpacing(20);
m_Slider.setMinorTickSpacing(5);
m_Slider.setPaintLabels( true );
this.add(m_Slider);
m_Editor.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
updateUs();
}
});
addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_ENTER)
updateEditor();
}
});
addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
updateEditor();
}
});
}
/**
*
*/
protected void updateUs() {
try {
//String x = m_Editor.getAsText();
m_Slider.setValue(((Integer)m_Editor.getValue()).intValue());
} catch (IllegalArgumentException ex) {}
}
/**
*
*/
protected void updateEditor() {
try {
m_Editor.setValue(new Integer (m_Slider.getValue()));
} catch (IllegalArgumentException ex) {}
}
/**
*
*/
class SliderListener implements ChangeListener {
private PropertyEditor propertyEditor;
private JSlider slider;
/**
*
*/
public SliderListener() {}
public void stateChanged(ChangeEvent e) {
JSlider s1 = (JSlider)e.getSource();
System.out.println("slider"+s1.getValue());
PropertySlider(PropertyEditor pe) {
//super(pe.getAsText());
propertyEditor = pe;
//setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
//setBorder(new TitledBorder(getString("SliderDemo.plain")));
slider = new JSlider(-10, 90, 20);
//s.getAccessibleContext().setAccessibleName(getString("SliderDemo.plain"));
//s.getAccessibleContext().setAccessibleDescription(getString("SliderDemo.a_plain_slider"));
slider.addChangeListener(new SliderListener());
slider.setValue(((Integer) propertyEditor.getValue()).intValue());
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setPaintLabels(true);
this.add(slider);
propertyEditor.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
updateUs();
}
});
addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_ENTER)
updateEditor();
}
});
addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
updateEditor();
}
});
}
/**
*
*/
protected void updateUs() {
try {
//String x = m_Editor.getAsText();
slider.setValue(((Integer) propertyEditor.getValue()).intValue());
} catch (IllegalArgumentException ex) {
}
}
/**
*
*/
protected void updateEditor() {
try {
propertyEditor.setValue(new Integer(slider.getValue()));
} catch (IllegalArgumentException ex) {
}
}
/**
*
*/
class SliderListener implements ChangeListener {
/**
*
*/
public SliderListener() {
}
public void stateChanged(ChangeEvent e) {
JSlider s1 = (JSlider) e.getSource();
System.out.println("slider" + s1.getValue());
updateEditor();
}
}
}
}

View File

@ -5,7 +5,7 @@ import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyEditor;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
/**
@ -13,13 +13,14 @@ import javax.swing.JTextField;
*
*/
public class PropertyText extends JTextField {
private PropertyEditor m_Editor;
private PropertyEditor propertyEditor;
/**
*
*/
public PropertyText(PropertyEditor pe) {
super(pe.getAsText());
m_Editor = pe;
this.setBorder(BorderFactory.createEmptyBorder());
propertyEditor = pe;
// m_Editor.addPropertyChangeListener(new PropertyChangeListener() {
// public void propertyChange(PropertyChangeEvent evt) {
// updateUs();
@ -44,8 +45,8 @@ public class PropertyText extends JTextField {
protected void updateEditor() {
try {
String x = getText();
if (!m_Editor.getAsText().equals(x)) {
m_Editor.setAsText(x);
if (!propertyEditor.getAsText().equals(x)) {
propertyEditor.setAsText(x);
// setText(m_Editor.getAsText());
}
} catch (IllegalArgumentException ex) {
@ -55,10 +56,10 @@ public class PropertyText extends JTextField {
public boolean checkConsistency() {
String x = getText();
return x.equals(m_Editor.getAsText());
return x.equals(propertyEditor.getAsText());
}
public void updateFromEditor() {
setText(m_Editor.getAsText());
setText(propertyEditor.getAsText());
}
}

View File

@ -1,55 +1,48 @@
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: 57 $
* $Date: 2007-05-04 14:22:16 +0200 (Fri, 04 May 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: 57 $
* $Date: 2007-05-04 14:22:16 +0200 (Fri, 04 May 2007) $ $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
import java.beans.PropertyEditor;
import java.beans.PropertyEditor;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
public class PropertyValueSelector extends JComboBox {
PropertyEditor m_Editor;
/**
*
*/
public PropertyValueSelector(PropertyEditor pe) {
m_Editor = pe;
Object value = m_Editor.getAsText();
String tags[] = m_Editor.getTags();
/**
*
*/
ComboBoxModel model = new DefaultComboBoxModel(tags) {
/**
*
*/
public Object getSelectedItem() {
return m_Editor.getAsText();
}
/**
*
*/
public void setSelectedItem(Object o) {
m_Editor.setAsText((String)o);
}
};
setModel(model);
setSelectedItem(value);
}
private PropertyEditor propertyEditor;
/**
*
*/
public PropertyValueSelector(PropertyEditor pe) {
propertyEditor = pe;
this.setBorder(BorderFactory.createEmptyBorder());
Object value = propertyEditor.getAsText();
String[] tags = propertyEditor.getTags();
/**
*
*/
ComboBoxModel model = new DefaultComboBoxModel(tags) {
/**
*
*/
public Object getSelectedItem() {
return propertyEditor.getAsText();
}
/**
*
*/
public void setSelectedItem(Object o) {
propertyEditor.setAsText((String) o);
}
};
setModel(model);
setSelectedItem(value);
}
}

View File

@ -9,33 +9,29 @@ package eva2.gui;
* $Date: 2007-10-23 13:43:24 +0200 (Tue, 23 Oct 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.beans.*;
import java.awt.*;
import javax.swing.*;
import eva2.server.stat.GenericStatistics;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
public class StatisticsEditor implements PropertyEditor {
private PropertyChangeSupport m_Support = new PropertyChangeSupport(this);
private PropertySheetPanelStat m_StatPanel;
private JScrollPane m_ScrollPane;
private JPanel m_Panel;
private GenericStatistics m_Value;
/**
*
*/
public StatisticsEditor () {
public StatisticsEditor() {
super();
m_StatPanel = new PropertySheetPanelStat();
m_StatPanel.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
m_Support.firePropertyChange("", null, null);
}
@ -47,89 +43,97 @@ public class StatisticsEditor implements PropertyEditor {
m_Panel.add(m_ScrollPane, BorderLayout.CENTER);
}
/**
*
*/
public void setValue (Object value) {
public void setValue(Object value) {
if (value instanceof GenericStatistics) {
m_Value=(GenericStatistics) value;
m_StatPanel.setTarget(m_Value.getPropertyNames(),m_Value.getState());
m_Value = (GenericStatistics) value;
m_StatPanel.setTarget(m_Value.getPropertyNames(), m_Value.getState());
}
m_Support.firePropertyChange("", null, null);
}
/**
*
*/
public Object getValue () {
public Object getValue() {
System.out.println("getValue !!!!!!!!!!!!");
m_Value.setState(m_StatPanel.getState());
return m_Value;
}
/**
*
*/
public String getJavaInitializationString () {
return "null";
public String getJavaInitializationString() {
return "null";
}
/**
*
*/
public boolean isPaintable () {
return true;
public boolean isPaintable() {
return true;
}
/**
*
*/
public void paintValue (Graphics gfx, Rectangle box) {
public void paintValue(Graphics gfx, Rectangle box) {
FontMetrics fm = gfx.getFontMetrics();
int vpad = (box.height - fm.getAscent())/2;
int vpad = (box.height - fm.getAscent()) / 2;
//String rep = EVAHELP.cutClassName(m_ElementClass.getName());
gfx.drawString("StatisticeEditor", 2, fm.getHeight() + vpad - 3);
}
/**
*
*/
public String getAsText () {
return null;
public String getAsText() {
return null;
}
/**
*
*/
public void setAsText (String text) throws IllegalArgumentException {
throw new IllegalArgumentException(text);
public void setAsText(String text) throws IllegalArgumentException {
throw new IllegalArgumentException(text);
}
/**
*
*/
public String[] getTags () {
return null;
public String[] getTags() {
return null;
}
/**
*
*/
public boolean supportsCustomEditor () {
return true;
public boolean supportsCustomEditor() {
return true;
}
/**
*
*/
public Component getCustomEditor () {
return m_Panel;
public Component getCustomEditor() {
return m_Panel;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
if (m_Support == null) m_Support = new PropertyChangeSupport(this);
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);
if (m_Support == null) {
m_Support = new PropertyChangeSupport(this);
}
m_Support.removePropertyChangeListener(l);
}
}

View File

@ -0,0 +1,248 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eva2.gui.utils;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class CustomTabbedPaneUI extends BasicTabbedPaneUI {
private static final Insets NO_INSETS = new Insets(0, 0, 0, 0);
private ColorSet selectedColorSet;
private ColorSet defaultColorSet;
private ColorSet hoverColorSet;
private boolean contentTopBorderDrawn = true;
private Color lineColor = new Color(158, 158, 158);
private Color dividerColor = new Color(200, 200, 200);
private Insets contentInsets = new Insets(10, 10, 10, 10);
private int lastRollOverTab = -1;
public static ComponentUI createUI(JComponent c) {
return new CustomTabbedPaneUI();
}
public CustomTabbedPaneUI() {
selectedColorSet = new ColorSet();
selectedColorSet.topGradColor1 = new Color(233, 237, 248);
selectedColorSet.topGradColor2 = new Color(158, 199, 240);
selectedColorSet.bottomGradColor1 = new Color(112, 173, 239);
selectedColorSet.bottomGradColor2 = new Color(183, 244, 253);
defaultColorSet = new ColorSet();
defaultColorSet.topGradColor1 = new Color(253, 253, 253);
defaultColorSet.topGradColor2 = new Color(237, 237, 237);
defaultColorSet.bottomGradColor1 = new Color(222, 222, 222);
defaultColorSet.bottomGradColor2 = new Color(255, 255, 255);
hoverColorSet = new ColorSet();
hoverColorSet.topGradColor1 = new Color(244, 244, 244);
hoverColorSet.topGradColor2 = new Color(223, 223, 223);
hoverColorSet.bottomGradColor1 = new Color(211, 211, 211);
hoverColorSet.bottomGradColor2 = new Color(235, 235, 235);
maxTabHeight = 20;
setContentInsets(0);
}
public void setContentTopBorderDrawn(boolean b) {
contentTopBorderDrawn = b;
}
public void setContentInsets(Insets i) {
contentInsets = i;
}
public void setContentInsets(int i) {
contentInsets = new Insets(i, i, i, i);
}
public int getTabRunCount(JTabbedPane pane) {
return 1;
}
protected void installDefaults() {
super.installDefaults();
RollOverListener l = new RollOverListener();
tabPane.addMouseListener(l);
tabPane.addMouseMotionListener(l);
tabAreaInsets = NO_INSETS;
tabInsets = new Insets(0, 0, 0, 1);
}
protected boolean scrollableTabLayoutEnabled() {
return false;
}
protected Insets getContentBorderInsets(int tabPlacement) {
return contentInsets;
}
protected int calculateTabHeight(int tabPlacement, int tabIndex,
int fontHeight) {
return 21;
}
protected int calculateTabWidth(int tabPlacement, int tabIndex,
FontMetrics metrics) {
int w = super.calculateTabWidth(tabPlacement, tabIndex, metrics);
int wid = metrics.charWidth('M');
w += wid * 2;
return w;
}
protected int calculateMaxTabHeight(int tabPlacement) {
return 21;
}
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) {
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(new GradientPaint(0, 0, defaultColorSet.topGradColor1, 0,
10, defaultColorSet.topGradColor2));
g2d.fillRect(0, 0, tabPane.getWidth(), 10);
g2d.setPaint(new GradientPaint(0, 10, defaultColorSet.bottomGradColor1,
0, 21, defaultColorSet.bottomGradColor2));
g2d.fillRect(0, 10, tabPane.getWidth(), 11);
super.paintTabArea(g, tabPlacement, selectedIndex);
if (contentTopBorderDrawn) {
g2d.setColor(lineColor);
g2d.drawLine(0, 20, tabPane.getWidth() - 1, 20);
}
}
protected void paintTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2d = (Graphics2D) g;
ColorSet colorSet;
Rectangle rect = rects[tabIndex];
if (isSelected) {
colorSet = selectedColorSet;
} else if (getRolloverTab() == tabIndex) {
colorSet = hoverColorSet;
} else {
colorSet = defaultColorSet;
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int width = rect.width;
int xpos = rect.x;
if (tabIndex > 0) {
width--;
xpos++;
}
g2d.setPaint(new GradientPaint(xpos, 0, colorSet.topGradColor1, xpos,
10, colorSet.topGradColor2));
g2d.fillRect(xpos, 0, width, 10);
g2d.setPaint(new GradientPaint(0, 10, colorSet.bottomGradColor1, 0, 21,
colorSet.bottomGradColor2));
g2d.fillRect(xpos, 10, width, 11);
if (contentTopBorderDrawn) {
g2d.setColor(lineColor);
g2d.drawLine(rect.x, 20, rect.x + rect.width - 1, 20);
}
}
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
Rectangle rect = getTabBounds(tabIndex, new Rectangle(x, y, w, h));
g.setColor(dividerColor);
g.drawLine(rect.x + rect.width, 0, rect.x + rect.width, 20);
}
protected void paintContentBorderTopEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
}
protected void paintContentBorderRightEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
// Do nothing
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex, Rectangle iconRect,
Rectangle textRect, boolean isSelected) {
// Do nothing
}
protected int getTabLabelShiftY(int tabPlacement, int tabIndex,
boolean isSelected) {
return 0;
}
private class ColorSet {
Color topGradColor1;
Color topGradColor2;
Color bottomGradColor1;
Color bottomGradColor2;
}
private class RollOverListener implements MouseMotionListener,
MouseListener {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
checkRollOver();
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
checkRollOver();
}
public void mouseExited(MouseEvent e) {
tabPane.repaint();
}
private void checkRollOver() {
int currentRollOver = getRolloverTab();
if (currentRollOver != lastRollOverTab) {
lastRollOverTab = currentRollOver;
Rectangle tabsRect = new Rectangle(0, 0, tabPane.getWidth(), 20);
tabPane.repaint(tabsRect);
}
}
}
}

View File

@ -0,0 +1,86 @@
package eva2.gui.utils;
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicButtonUI;
public class VerticalButtonUI extends BasicButtonUI {
protected int angle;
public VerticalButtonUI(int angle) {
super();
this.angle = angle;
}
@Override
public Dimension getPreferredSize(JComponent c) {
Dimension dim = super.getPreferredSize(c);
return new Dimension( dim.height, dim.width );
}
private static Rectangle paintIconR = new Rectangle();
private static Rectangle paintTextR = new Rectangle();
private static Rectangle paintViewR = new Rectangle();
private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
@Override
public void paint(Graphics g, JComponent c) {
JButton button = (JButton)c;
String text = button.getText();
Icon icon = (button.isEnabled()) ? button.getIcon() : button.getDisabledIcon();
if ((icon == null) && (text == null)) {
return;
}
FontMetrics fm = g.getFontMetrics();
paintViewInsets = c.getInsets(paintViewInsets);
paintViewR.x = paintViewInsets.left;
paintViewR.y = paintViewInsets.top;
// Use inverted height & width
paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
Graphics2D g2 = (Graphics2D) g;
AffineTransform tr = g2.getTransform();
if (angle == 90) {
g2.rotate( Math.PI / 2 );
g2.translate( 0, - c.getWidth() );
paintViewR.x = c.getHeight()/2 - (int)fm.getStringBounds(text, g).getWidth()/2;
paintViewR.y = c.getWidth()/2 - (int)fm.getStringBounds(text, g).getHeight()/2;
}
else if (angle == 270 || angle == -90) {
g2.rotate( - Math.PI / 2 );
g2.translate( - c.getHeight(), 0 );
paintViewR.x = c.getHeight()/2 - (int)fm.getStringBounds(text, g).getWidth()/2;
paintViewR.y = c.getWidth()/2 - (int)fm.getStringBounds(text, g).getHeight()/2;
}
if (icon != null) {
icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
}
if (text != null) {
int textX = paintTextR.x;
int textY = paintTextR.y + fm.getAscent();
if (button.isEnabled()) {
paintText(g,c,new Rectangle(paintViewR.x,paintViewR.y,textX,textY),text);
} else {
paintText(g,c,new Rectangle(paintViewR.x,paintViewR.y,textX,textY),text);
}
}
g2.setTransform( tr );
}
}

View File

@ -8,33 +8,27 @@ package eva2.server;
* $Date: 2007-11-16 17:25:09 +0100 (Fri, 16 Nov 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import eva2.server.go.InterfaceGOParameters;
import eva2.server.modules.ModuleAdapter;
import eva2.tools.jproxy.MainAdapter;
import eva2.tools.jproxy.MainAdapterClient;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface EvAMainAdapter extends MainAdapter {
public String[] getModuleNameList();
// returns the corresponding ModuleAdapter
public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI,
String hostAddress,
MainAdapterClient client);
public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI,
String hostAddress,
InterfaceGOParameters goParams,
String noGuiStatsFile,
MainAdapterClient client);
public String[] getModuleNameList();
// returns the corresponding ModuleAdapter
public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI,
String hostAddress,
MainAdapterClient client);
public ModuleAdapter getModuleAdapter(String selectedModuleName,
boolean withoutRMI,
String hostAddress,
InterfaceGOParameters goParams,
String noGuiStatsFile,
MainAdapterClient client);
}

View File

@ -9,40 +9,33 @@ package eva2.server;
* $Date: 2007-12-04 15:23:57 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import eva2.EvAInfo;
import eva2.server.go.InterfaceGOParameters;
import eva2.server.modules.ModuleAdapter;
import eva2.tools.jproxy.MainAdapterClient;
import eva2.tools.jproxy.MainAdapterImpl;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class EvAMainAdapterImpl extends MainAdapterImpl implements EvAMainAdapter {
private ModuleServer m_ModulServer=null;
public EvAMainAdapterImpl() {
super();
m_ModulServer = new ModuleServer(EvAInfo.getProperties());
}
private ModuleServer moduleServer = null;
public String[] getModuleNameList() {
return m_ModulServer.getModuleNameList();
}
public EvAMainAdapterImpl() {
super();
moduleServer = new ModuleServer(EvAInfo.getProperties());
}
public ModuleAdapter getModuleAdapter(String selectedModuleName, boolean withoutRMI, String hostAddress, MainAdapterClient client) {
return getModuleAdapter(selectedModuleName, withoutRMI, hostAddress, null, null, client);
}
public ModuleAdapter getModuleAdapter(String selectedModuleName, boolean withoutRMI, String hostAddress, InterfaceGOParameters goParams,String noGuiStatsFile, MainAdapterClient client) {
if (TRACE) System.out.println("MainAdapterImpl.GetModuleAdapter() for module " +
selectedModuleName +" for Client: "+hostAddress+ " called");
return m_ModulServer.createModuleAdapter(selectedModuleName,client,withoutRMI,hostAddress, goParams, noGuiStatsFile);
}
public String[] getModuleNameList() {
return moduleServer.getModuleNameList();
}
public ModuleAdapter getModuleAdapter(String selectedModule, boolean withoutRMI, String hostAddress, MainAdapterClient client) {
return getModuleAdapter(selectedModule, withoutRMI, hostAddress, null, null, client);
}
public ModuleAdapter getModuleAdapter(String selectedModule, boolean withoutRMI, String hostAddress, InterfaceGOParameters goParams, String noGuiStatsFile, MainAdapterClient client) {
return moduleServer.createModuleAdapter(selectedModule, client, withoutRMI, hostAddress, goParams, noGuiStatsFile);
}
}

View File

@ -29,10 +29,9 @@ import java.util.logging.Logger;
* Collect available ModuleAdapter implementations and load them on request.
*/
public class ModuleServer {
private static final Logger logger = Logger.getLogger(eva2.EvAInfo.defaultLogger);
private int m_InstanceCounter = 0;
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
private static int instanceCounter = 0;
private List<Class<?>> moduleClassList;
// private ArrayList m_RunnungModules;
private ModuleAdapter moduleAdapter;
private int moduleAdapterCounter = 0;
@ -40,7 +39,7 @@ public class ModuleServer {
*
*/
public ModuleServer(Properties EvAProps) {
if (m_InstanceCounter > 0) {
if (instanceCounter > 0) {
EVAERROR.EXIT("ModuleServer created twice");
}
moduleClassList = new ArrayList<Class<?>>();
@ -48,13 +47,14 @@ public class ModuleServer {
String modulePckg = null;
Class<?> filterBy = null;
try {
/* Fetch the name of the package containing the modules */
modulePckg = EvAProps.getProperty("ModulePackage");
/* Fetch the the super class for all modules */
filterBy = Class.forName(EvAProps.getProperty("ModuleFilterClass"));
} catch(Exception e) {
System.err.println("Creating ModuleServer failed: couldnt load modules:" + e.getMessage());
} catch (Exception ex) {
System.err.println("Creating ModuleServer failed: couldnt load modules:" + ex.getMessage());
System.err.println("module path was " + modulePckg + ", is it valid?");
System.err.println("filter class path was " + ((filterBy==null) ? "null" : filterBy.getName()));
// e.printStackTrace();
System.err.println("filter class path was " + ((filterBy == null) ? "null" : filterBy.getName()));
}
// this gets a list of all valid modules from the package
@ -63,35 +63,39 @@ public class ModuleServer {
moduleClassList.add((Class<?>) cls);
}
m_InstanceCounter++;
instanceCounter++;
}
/**
*
* Iterates over the list of available modules and fetches
* the name of the module by calling the static getName()
* method.
*
* @return Array of available modules
*/
public String[] getModuleNameList() {
List<String> moduleNameList = new ArrayList<String>();
for (int i = 0; i < moduleClassList.size(); i++) {
try {
Class<?> Modul = (Class<?>) moduleClassList.get(i);
Method[] methods = Modul.getDeclaredMethods();
for (int ii = 0; ii < methods.length; ii++) {
if (methods[ii].getName().equals("getName") == true) {
//System.out.println("name is =="+methods[ii].invoke(null,null));
String name = (String)methods[ii].invoke((Object[])null, (Object[])null);
if (name != null) moduleNameList.add(name);
break;
}
}
//ModuleNameList.add ( Modul.getName());
}
catch (Exception e) {
System.err.println("ModuleServer.getModuleNameList() " + e.getMessage());
}
public String[] getModuleNameList() {
List<String> moduleNameList = new ArrayList<String>();
for (Class<?> module : moduleClassList) {
try {
Method[] methods = module.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals("getName")) {
String name = (String) method.invoke((Object[]) null, (Object[]) null);
if (name != null) {
moduleNameList.add(name);
} else {
LOGGER.log(Level.FINE, "Module {0} does not specify a diplayable name.", module.getCanonicalName());
}
break;
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Error while fetching name from module.", ex);
}
}
// and the running modules
// @todo running modules sind abgeschaltet
}
// and the running modules
// @todo running modules sind abgeschaltet
// for (int i = 0; i < m_RunnungModules.size(); i++) {
// String AdapterName = null;
@ -104,10 +108,10 @@ public class ModuleServer {
// ModuleNameList.add(AdapterName);
// }
String[] x = new String[moduleNameList.size()];
moduleNameList.toArray(x);
return x;
}
String[] x = new String[moduleNameList.size()];
moduleNameList.toArray(x);
return x;
}
/**
* Load the module indicated by the selectedModuleName from all available
@ -122,21 +126,19 @@ public class ModuleServer {
moduleAdapterCounter++;
String adapterName = "ERROR MODULADAPTER !!";
String moduleName = null;
Class<?> module;
Method[] methods;
for (int i = 0; i < moduleClassList.size(); i++) {
module = moduleClassList.get(i);
for (Class<?> module : moduleClassList) {
try {
methods = module.getDeclaredMethods();
for (int ii = 0; ii < methods.length; ii++) {
if (methods[ii].getName().equals("getName") == true) {
moduleName = (String) methods[ii].invoke((Object[]) null, (Object[]) null);
for (Method method : methods) {
if (method.getName().equals("getName")) {
moduleName = (String) method.invoke((Object[]) null, (Object[]) null);
}
}
}
catch (Exception ex) {
logger.log(Level.WARNING, ex.getMessage(), ex);
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
if ((moduleName != null) && (selectedModuleName.equals(moduleName))) {
try {
@ -154,7 +156,7 @@ public class ModuleServer {
System.err.println("Cant deactivate GUI - no matching constructor found for " + adapterName + " (ModuleServer)");
}
Object[] Para = new Object[2];
while ((constructorArr[constrIndex].getParameterTypes().length!=2) && (constrIndex < constructorArr.length)) {
while ((constructorArr[constrIndex].getParameterTypes().length!=2) && (constrIndex < constructorArr.length)) {
constrIndex++;
}
Class<?> paramTypes[] = (constructorArr[constrIndex]).getParameterTypes();
@ -163,10 +165,10 @@ public class ModuleServer {
moduleAdapter = (ModuleAdapter) constructorArr[constrIndex].newInstance(Para);
} else {
Object[] param = new Object[4];
param[0] = (String)adapterName;
param[1] = (InterfaceGOParameters)goParams;
param[2] = (String)noGuiLogFile;
param[3] = (MainAdapterClient)Client;
param[0] = (String) adapterName;
param[1] = (InterfaceGOParameters) goParams;
param[2] = (String) noGuiLogFile;
param[3] = (MainAdapterClient) Client;
while ((constructorArr[constrIndex].getParameterTypes().length!=4) && (constrIndex < constructorArr.length)) {
constrIndex++;
}
@ -178,13 +180,13 @@ public class ModuleServer {
* implement the ModuleAdapter interface for a strange reason,
* it is _not_ enough if a superclass implements the same interface!
*/
moduleAdapter = (ModuleAdapter)RMIProxyLocal.newInstance(moduleAdapter, adapterName);
moduleAdapter = (ModuleAdapter) RMIProxyLocal.newInstance(moduleAdapter, adapterName);
(moduleAdapter).setRemoteThis(moduleAdapter);
}
// m_RunnungModules.add(m_ModuleAdapter);
}
catch (Exception ex) {
logger.log(Level.SEVERE, "Error in RMI-Moduladapter initialization", ex);
LOGGER.log(Level.SEVERE, "Error in RMI-Moduladapter initialization", ex);
EVAERROR.EXIT("Error in RMI-Moduladapter initialization: " + ex.getMessage());
return null;
}
@ -207,7 +209,7 @@ public class ModuleServer {
// }
// }
logger.log(Level.SEVERE, "No valid module defined: {0}", selectedModuleName);
LOGGER.log(Level.SEVERE, "No valid module defined: {0}", selectedModuleName);
return null;
}
}

View File

@ -36,7 +36,7 @@ public class RMIServerEvA extends RMIServer {
mainAdapterName + "_" + numberOfVM);
mainRemoteObject.setRemoteThis(mainRemoteObject);
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not create main remote object!", ex);
LOGGER.log(Level.WARNING, "Could not create main remote object!", ex);
}
}
}

View File

@ -12,19 +12,37 @@ import eva2.tools.jproxy.RemoteStateListener;
* $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
* Interface for Optimization Processor.
*/
public interface InterfaceProcessor {
public void startOpt();
public void restartOpt();
public void stopOpt();
public void addListener(RemoteStateListener module);
public String getInfoString();
}
/**
* Start optimization.
*/
void startOpt();
/**
* Restart optimization.
*/
void restartOpt();
/**
* Stop optimization if running.
*/
void stopOpt();
/**
* Adds a new RemoteStateListener.
*
* @param module The module to add.
*/
void addListener(RemoteStateListener module);
/**
* Get Info String about the Optimization.
* @return The info String
*/
String getInfoString();
}

View File

@ -20,6 +20,7 @@ import javax.swing.JOptionPane;
import eva2.gui.BeanInspector;
import eva2.tools.BasicResourceLoader;
import eva2.tools.StringTools;
import java.beans.XMLEncoder;
/**
@ -201,9 +202,9 @@ public class FileTools {
}
public static JFileChooser createFileChooser() {
JFileChooser fc = new JFileChooser(new File("resources"));
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
return fc;
JFileChooser fileChooser = new JFileChooser(new File("resources"));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
return fileChooser;
}
public static boolean saveObjectToFolder(Object object, File folder, boolean forceOverwrite, Component parentComponent) {

View File

@ -153,7 +153,7 @@ public class GeneralGenericObjectEditorPanel extends JPanel implements ItemListe
// add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER);
JPanel okcButs = new JPanel();
okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
okcButs.setBorder(BorderFactory.createEmptyBorder());
okcButs.setLayout(new GridLayout(1, 4, 5, 5));
okcButs.add(m_OpenBut);
okcButs.add(m_SaveBut);

View File

@ -9,9 +9,6 @@ package eva2.server.modules;
* $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.net.InetAddress;
import java.util.Vector;
@ -20,6 +17,8 @@ import eva2.server.go.InterfaceGOParameters;
import eva2.server.go.InterfaceProcessor;
import eva2.tools.jproxy.MainAdapterClient;
import eva2.tools.jproxy.RemoteStateListener;
import java.util.ArrayList;
import java.util.List;
/**
* The module server expects a constructor with two arguments: String adapterName and MainAdapterClient client.
@ -27,176 +26,183 @@ import eva2.tools.jproxy.RemoteStateListener;
*
*/
abstract public class AbstractModuleAdapter implements ModuleAdapter, Serializable {
public static boolean TRACE = false;
private static int m_InstanceCounter;
protected int m_Instance;
protected String m_AdapterName;
protected InterfaceProcessor m_Processor;
protected String m_myHostName = "not defined";
protected boolean m_Connection = true;
protected ModuleAdapter m_RemoteThis = null;
protected boolean m_RMI = true;
protected MainAdapterClient m_MainAdapterClient; // connection to client
private Vector<RemoteStateListener> m_RemoteStateListeners;
protected AbstractModuleAdapter(MainAdapterClient Client) {
if (TRACE) System.out.println("AbstractModuleAdapter.AbstractModuleAdapter()");
m_InstanceCounter++;
m_Instance = m_InstanceCounter;
if (TRACE) System.out.println ("AbstractModuleAdapter Nr. "+m_InstanceCounter +" on EvAServer");
private static int instanceCounter;
protected int instanceNumber;
protected String adapterName;
protected InterfaceProcessor processor;
protected String hostName = "not defined";
protected boolean hasConnection = true;
protected ModuleAdapter remoteModuleAdapter = null;
protected boolean useRMI = true;
protected MainAdapterClient mainAdapterClient; // connection to client
private List<RemoteStateListener> remoteStateListeners;
if (Client != null) {
try {
m_myHostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
System.out.println("InetAddress.getLocalHost().getHostAddress() --> ERROR" + e.getMessage());
}
} else m_myHostName = "localhost";
if ((Client==null) || Client.getHostName().equals(m_myHostName)) {
m_RMI = false;
} else {// we use RMI
m_RMI = true;
protected AbstractModuleAdapter(MainAdapterClient client) {
instanceCounter++;
instanceNumber = instanceCounter;
if (client != null) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
System.out.println("InetAddress.getLocalHost().getHostAddress() --> ERROR" + e.getMessage());
}
} else {
hostName = "localhost";
}
if ((client == null) || client.getHostName().equals(hostName)) {
useRMI = false;
} else {
/* we use RMI */
useRMI = true;
}
remoteStateListeners = new ArrayList<RemoteStateListener>();
}
m_RemoteStateListeners = new Vector<RemoteStateListener>();
}
/**
* From the interface RemoteStateListener. Added this method to make progress bar possible.
*/
public void updateProgress(final int percent, String msg) {
if (TRACE) System.out.println("AbstractModuleAdapter::updateProgress");
for (RemoteStateListener listener : m_RemoteStateListeners) {
listener.updateProgress(percent, msg);
}
}
/**
*
*/
public String getAdapterName() {
return m_AdapterName;
}
/**
*
*/
public void startOpt() {
if (TRACE) System.out.println("Module AbstractModuleAdapter on EvA-Server StartOpt called:" );
m_Processor.startOpt();
}
/**
*
*/
public void restartOpt() {
if (TRACE) System.out.println("Module AbstractModuleAdapter on EvA-Server ReStartOpt called:" );
m_Processor.restartOpt();
}
/**
*
*/
public void stopOpt() {
if (TRACE) System.out.println("Module AbstractModuleAdapter on EvA-Server StopOpt called:" );
m_Processor.stopOpt(); // This means user break
}
public boolean hasPostProcessing() {
return ((m_Processor instanceof Processor) && ((Processor)m_Processor).getGOParams().getPostProcessParams().isDoPostProcessing());
}
public boolean startPostProcessing() {
if (hasPostProcessing() && ((Processor)m_Processor).getGOParams().getPostProcessParams().isDoPostProcessing()) {
((Processor)m_Processor).performPostProcessing();
return true;
} else return false;
}
public InterfaceGOParameters getGOParameters() {
if ((m_Processor != null) && (m_Processor instanceof Processor)) {
return ((Processor)m_Processor).getGOParams();
} else return null;
}
public void setGOParameters(InterfaceGOParameters goParams) {
if ((m_Processor != null) && (m_Processor instanceof Processor)) {
((Processor)m_Processor).setGOParams(goParams);
}
}
// public void loadGOParameters(String serParamsFile) {
// if ((m_Processor != null) && (m_Processor instanceof Processor)) {
// ((Processor)m_Processor).setGOParams(GOParameters.getInstance(serParamsFile, false));
// }
// }
public boolean isOptRunning() {
if ((m_Processor != null) && (m_Processor instanceof Processor)) {
return ((Processor)m_Processor).isOptRunning();
} else return false;
}
/**
*
*/
public void runScript() {
}
/**
*
*/
public void addRemoteStateListener(RemoteStateListener x) {
if (TRACE) System.out.println("module adapter on Server addRemoteStateListener called:" );
m_RemoteStateListeners.add(x);
}
/**
*
*/
public void setConnection (boolean flag) {
if (TRACE) System.out.println("module adapter on Server setConnection "+flag+" called:" );
m_Connection = flag;
}
public boolean hasConnection() {
return m_Connection;
}
/**
*
*/
public void setRemoteThis (ModuleAdapter x) {
if (TRACE) System.out.println("module adapter on Server setRemoteThis called:" );
m_RemoteThis = x;
}
/**
*
*/
public String getHostName () {
if (TRACE) System.out.println("module adapter on Server getHostName called:"+m_myHostName );
return m_myHostName;
}
/**
*
*/
public void performedStop () {
if (TRACE) System.out.println("AbstractModuleAdapter::performedStop");
for (RemoteStateListener listener : m_RemoteStateListeners) {
listener.performedStop();
}
// if (logPanel != null) logPanel.logMessage("Stopped optimization run");
}
/**
* From the interface RemoteStateListener. Added this method to make progress bar possible.
*/
public void updateProgress(final int percent, String msg) {
for (RemoteStateListener listener : remoteStateListeners) {
listener.updateProgress(percent, msg);
}
}
public void performedStart(String infoString) {
if (TRACE) System.out.println("AbstractModuleAdapter::performedStart");
for (RemoteStateListener listener : m_RemoteStateListeners) {
listener.performedStart(infoString);
}
// if (logPanel != null) logPanel.logMessage("Started optimization " + m_Processor.getInfoString());
}
/**
* Get the name of the current adapter.
*
* @return The adapter name
*/
public String getAdapterName() {
return adapterName;
}
public void performedRestart(String infoString) {
if (TRACE) System.out.println("AbstractModuleAdapter::performedRestart");
for (RemoteStateListener listener : m_RemoteStateListeners) {
listener.performedRestart(infoString);
}
// if (logPanel != null) logPanel.logMessage("Restarted optimization run");
}
/**
* Start optimization on processor.
*/
public void startOpt() {
processor.startOpt();
}
/**
* Restart optimization on processor.
*/
public void restartOpt() {
processor.restartOpt();
}
/**
* Stop optimization on processor.
*/
public void stopOpt() {
// This means user break
processor.stopOpt();
}
/**
* Returns whether the current optimization provides post processing.
*
* @return true if post processing is available
*/
public boolean hasPostProcessing() {
return ((processor instanceof Processor) && ((Processor) processor).getGOParams().getPostProcessParams().isDoPostProcessing());
}
/**
* Starts post processing if available.
*
* @return true if post processing was performed, false otherwise.
*/
public boolean startPostProcessing() {
if (hasPostProcessing() && ((Processor) processor).getGOParams().getPostProcessParams().isDoPostProcessing()) {
((Processor) processor).performPostProcessing();
return true;
} else {
return false;
}
}
public InterfaceGOParameters getGOParameters() {
if ((processor != null) && (processor instanceof Processor)) {
return ((Processor) processor).getGOParams();
} else {
return null;
}
}
public void setGOParameters(InterfaceGOParameters goParams) {
if ((processor != null) && (processor instanceof Processor)) {
((Processor) processor).setGOParams(goParams);
}
}
public boolean isOptRunning() {
if ((processor != null) && (processor instanceof Processor)) {
return ((Processor) processor).isOptRunning();
} else {
return false;
}
}
/**
* Adds a remote state listener.
*/
public void addRemoteStateListener(RemoteStateListener remoteListener) {
remoteStateListeners.add(remoteListener);
}
/**
*
*/
public void setConnection(boolean flag) {
hasConnection = flag;
}
/**
* Returns whether the module has a connection.
*
* @return true if the adapter has a connection.
*/
public boolean hasConnection() {
return hasConnection;
}
/**
*
*/
public void setRemoteThis(ModuleAdapter x) {
remoteModuleAdapter = x;
}
/**
* Returns the host name.
*
* @return The host name
*/
public String getHostName() {
return hostName;
}
/**
*
*/
public void performedStop() {
for (RemoteStateListener listener : remoteStateListeners) {
listener.performedStop();
}
}
public void performedStart(String infoString) {
for (RemoteStateListener listener : remoteStateListeners) {
listener.performedStart(infoString);
}
}
public void performedRestart(String infoString) {
for (RemoteStateListener listener : remoteStateListeners) {
listener.performedRestart(infoString);
}
}
}

View File

@ -3,26 +3,23 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the DE module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 27.10.2004
* Time: 13:54:55
* To change this template use File | Settings | File Templates.
/**
* This the DE module adapter necessary to access this implementation from the EvA top level.
*/
public class DEModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Differential_Evolution";
private static final String moduleName = "Differential_Evolution";
public DEModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "DE.html", client, DEParameters.getInstance(), true);
super(adapterName, "DE.html", client, DEParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapters.
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -2,26 +2,23 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the EP module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 27.10.2004
* Time: 13:54:55
* To change this template use File | Settings | File Templates.
/**
* This the EP module adapter necessary to access this implementation from the EvA top level.
*/
public class EPModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Evolutionary_Programming";
private static final String moduleName = "Evolutionary_Programming";
public EPModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "EP.html", client, EPParameters.getInstance(), true);
super(adapterName, "EP.html", client, EPParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapter
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -2,26 +2,23 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the GA module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 08.06.2004
* Time: 21:29:20
* To change this template use File | Settings | File Templates.
/**
* This the GA module adapter necessary to access this implementation from the EvA top level.
*/
public class GAModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Genetic_Algorithm";
private static final String moduleName = "Genetic_Algorithm";
public GAModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "GA.html", client, GAParameters.getInstance(), true);
super(adapterName, "GA.html", client, GAParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}
}

View File

@ -1,50 +1,44 @@
package eva2.server.modules;
import java.io.Serializable;
import eva2.server.go.InterfaceGOParameters;
import eva2.tools.jproxy.MainAdapterClient;
import java.io.Serializable;
/**
* Starts a statistics GUI and the GOProcessor thread.
*
* User: streiche
* Date: 11.05.2003
* Time: 13:08:38
* To change this template use Options | File Templates.
*/
public class GOModuleAdapter extends GenericModuleAdapter implements ModuleAdapter, Serializable {
public static String m_Name = "Genetic_Optimization";
/**
*
*/
public static String getName() {
return m_Name;
}
private static final String moduleName = "Genetic_Optimization";
/**
* Starts a statistics GUI and the GOProcessor thread.
*
* @param AdapterName the title of the ModulAdapter
* @param Client the client instance
*/
public GOModuleAdapter(String adapterName, MainAdapterClient client) {
super(adapterName, "", client, GOParameters.getInstance(), false);
}
/**
* Starts a statistics GUI and the GOProcessor thread with a given GOParameters file.
*
* @param AdapterName the title of the ModulAdapter
* @param Client the client instance
*/
public GOModuleAdapter(String adapterName, InterfaceGOParameters goParams, String noGuiLogFile, MainAdapterClient client) {
//super(adapterName, "", client, GOParameters.getInstance(serParamsFile, false), false);
super(adapterName, "", client, goParams, false, noGuiLogFile);
}
/**
*
*/
public static String getName() {
return moduleName;
}
/**
* Starts a statistics GUI and the GOProcessor thread.
*
* @param AdapterName the title of the ModulAdapter
* @param Client the client instance
*/
public GOModuleAdapter(String adapterName, MainAdapterClient client) {
super(adapterName, "", client, GOParameters.getInstance(), false);
}
/**
* Starts a statistics GUI and the GOProcessor thread with a given GOParameters file.
*
* @param AdapterName the title of the ModulAdapter
* @param Client the client instance
*/
public GOModuleAdapter(String adapterName, InterfaceGOParameters goParams, String noGuiLogFile, MainAdapterClient client) {
//super(adapterName, "", client, GOParameters.getInstance(serParamsFile, false), false);
super(adapterName, "", client, goParams, false, noGuiLogFile);
}
// /**
// * Starts a statistics GUI and the GOProcessor thread with a given GOParameters file.
// *

View File

@ -20,34 +20,36 @@ import eva2.tools.jproxy.RMIProxyLocal;
public class GenericModuleAdapter extends AbstractModuleAdapter implements Serializable {
private AbstractStatistics m_StatisticsModul;
private EvAJobList jobList = null;
public String helperFilename;
JParaPanel jobPanel=null, paramPanel=null;
private AbstractStatistics statisticsModule;
private EvAJobList jobList = null;
public String helperFilename;
JParaPanel jobPanel = null, paramPanel = null;
/**
* Constructor of the ModuleAdapter
* @param adapterName The AdapterName
* @param helperFName name of a html help file name
* @param Client The client to serve
* @param params a parameter set describing the optimizer module
* @param optimizerExpert set to true if setting the optimizer is an expert option being hidden from the gui
* @param noGUIStatOut if null, statistics with GUI are used, else the standalone statistics with given output filename.
*
* @param adapterName The AdapterName
* @param helperFName Name of a HTML help file name
* @param adapterClient The client to serve
* @param params A parameter set describing the optimizer module
* @param optimizerExpert Set to true if setting the optimizer is an expert option being hidden
* from the gui
* @param noGUIStatOut If null, statistics with GUI are used, else the standalone statistics
* with given output filename.
*/
public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient Client, InterfaceGOParameters params, boolean optimizerExpert, String noGUIStatOut) {
super (Client);
if (TRACE) System.out.println("Constructor GenericModuleAdapter --> start");
m_RemoteThis = this;
m_AdapterName = adapterName;
m_MainAdapterClient = Client;
helperFilename = helperFName;
public GenericModuleAdapter(String adapterName, String helperFName, MainAdapterClient adapterClient, InterfaceGOParameters params, boolean optimizerExpert, String noGUIStatOut) {
super(adapterClient);
remoteModuleAdapter = this;
this.adapterName = adapterName;
mainAdapterClient = adapterClient;
helperFilename = helperFName;
if (noGUIStatOut==null) {
m_StatisticsModul = new StatisticsWithGUI(Client);
statisticsModule = new StatisticsWithGUI(adapterClient);
} else {
m_StatisticsModul = new StatisticsStandalone(noGUIStatOut);
statisticsModule = new StatisticsStandalone(noGUIStatOut);
}
m_Processor = new Processor(m_StatisticsModul,this, params);
processor = new Processor(statisticsModule, this, params);
// the statistics want to be informed if the strategy or the optimizer (which provide statistical data as InterfaceAdditionalInformer) change.
// THIS is now done directly in the constructor of a Processor
@ -56,8 +58,7 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria
// this prevents the optimizer property to be shown by the GOE if optimizerExpert is true
GenericObjectEditor.setExpertProperty(params.getClass(), "optimizer", optimizerExpert);
((Processor)m_Processor).start();
if (TRACE) System.out.println("Constructor GenericModuleAdapter <-- end");
((Processor) processor).start();
}
/**
@ -86,72 +87,79 @@ public class GenericModuleAdapter extends AbstractModuleAdapter implements Seria
* @return the EvATabbedFrameMaker
*/
public EvATabbedFrameMaker getModuleFrame() {
if (TRACE) System.out.println("GenericModulAdapter.getModuleFrame");
if (!(m_StatisticsModul instanceof StatisticsWithGUI)) {
if (!(statisticsModule instanceof StatisticsWithGUI)) {
System.err.println("Error: Unable to create Frame when startet with noGUI option (GenericModuleAdapter)!");
return null;
}
EvATabbedFrameMaker frmMkr = new EvATabbedFrameMaker();
InterfaceStatisticsParameter Stat = ((StatisticsWithGUI)m_StatisticsModul).getStatisticsParameter();
EvAModuleButtonPanelMaker ButtonPanel = new EvAModuleButtonPanelMaker(m_RemoteThis,((Processor)m_Processor).isOptRunning());
InterfaceStatisticsParameter Stat = ((StatisticsWithGUI) statisticsModule).getStatisticsParameter();
EvAModuleButtonPanelMaker ButtonPanel = new EvAModuleButtonPanelMaker(remoteModuleAdapter, ((Processor) processor).isOptRunning());
ButtonPanel.setHelperFilename(helperFilename);
frmMkr.addPanelMaker(ButtonPanel);
InterfaceGOParameters goParams = ((Processor)m_Processor).getGOParams();
if (TRACE) System.out.println("parameters are of type "+goParams.getClass());
InterfaceGOParameters goParams = ((Processor) processor).getGOParams();
// TODO do we really need proxies here?
if (m_RMI && !Proxy.isProxyClass(goParams.getClass())) frmMkr.addPanelMaker(paramPanel = new JParaPanel( RMIProxyLocal.newInstance(goParams), goParams.getName()));
else frmMkr.addPanelMaker(paramPanel = new JParaPanel(goParams, goParams.getName()));
if (m_RMI && !Proxy.isProxyClass(Stat.getClass())) frmMkr.addPanelMaker(new JParaPanel( RMIProxyLocal.newInstance(Stat), Stat.getName()));
else frmMkr.addPanelMaker(new JParaPanel(Stat, Stat.getName()));
if (useRMI && !Proxy.isProxyClass(goParams.getClass())) {
frmMkr.addPanelMaker(paramPanel = new JParaPanel(RMIProxyLocal.newInstance(goParams), goParams.getName()));
} else {
frmMkr.addPanelMaker(paramPanel = new JParaPanel(goParams, goParams.getName()));
}
if (useRMI && !Proxy.isProxyClass(Stat.getClass())) {
frmMkr.addPanelMaker(new JParaPanel(RMIProxyLocal.newInstance(Stat), Stat.getName()));
} else {
frmMkr.addPanelMaker(new JParaPanel(Stat, Stat.getName()));
}
jobList = new EvAJobList(new EvAJob[]{});
jobList.setModule(this);
jobList.addTextListener((AbstractStatistics) ((Processor)m_Processor).getStatistics());
// if (m_RMI && !Proxy.isProxyClass(Stat.getClass())) frmMkr.addPanelMaker(new JParaPanel( RMIProxyLocal.newInstance(jobList), jobList.getName()));
// else frmMkr.addPanelMaker(new JParaPanel(jobList, jobList.getName()));
if (m_RMI && !Proxy.isProxyClass(Stat.getClass())) jobPanel = new JParaPanel( RMIProxyLocal.newInstance(jobList), jobList.getName());
else jobPanel = new JParaPanel(jobList, jobList.getName());
jobList.addTextListener((AbstractStatistics) ((Processor) processor).getStatistics());
if (useRMI && !Proxy.isProxyClass(Stat.getClass())) {
jobPanel = new JParaPanel(RMIProxyLocal.newInstance(jobList), jobList.getName());
} else {
jobPanel = new JParaPanel(jobList, jobList.getName());
}
frmMkr.addPanelMaker(jobPanel);
((Processor)m_Processor).getGOParams().addInformableInstance(frmMkr);
((Processor) processor).getGOParams().addInformableInstance(frmMkr);
return frmMkr;
}
@Override
public void performedStart(String infoString) {
super.performedStart(infoString);
EvAJob job = scheduleJob();
((AbstractStatistics)(((Processor)m_Processor).getStatistics())).addDataListener(job);
}
public void performedStart(String infoString) {
super.performedStart(infoString);
EvAJob job = scheduleJob();
((AbstractStatistics) (((Processor) processor).getStatistics())).addDataListener(job);
}
@Override
public void performedStop() {
super.performedStop();
}
public static String getName() {
return null;
public void performedStop() {
super.performedStop();
}
public static String getName() {
return null;
}
/**
* Return the statistics module instance of this module.
*
* @return
*/
public AbstractStatistics getStatistics() {
return m_StatisticsModul;
return statisticsModule;
}
public EvAJob scheduleJob() {
EvAJob job = jobList.addJob(((Processor)m_Processor).getGOParams(), (AbstractStatistics)(((Processor)m_Processor).getStatistics()));
jobPanel.getEditor().setValue(jobList);
return job;
}
@Override
public void setGOParameters(InterfaceGOParameters goParams) {
super.setGOParameters(goParams);
paramPanel.getEditor().setValue(goParams);
}
public EvAJob scheduleJob() {
EvAJob job = jobList.addJob(((Processor) processor).getGOParams(), (AbstractStatistics) (((Processor) processor).getStatistics()));
jobPanel.getEditor().setValue(jobList);
return job;
}
@Override
public void setGOParameters(InterfaceGOParameters goParams) {
super.setGOParameters(goParams);
paramPanel.getEditor().setValue(goParams);
}
}

View File

@ -2,30 +2,29 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the HC module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 08.06.2004
* Time: 21:17:02
* To change this template use File | Settings | File Templates.
/**
* This the HC module adapter necessary to access this implementation from the EvA top level.
*/
public class HCModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Hill_Climber";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
private static final String moduleName = "Hill_Climber";
/**
* Constructor of the ModuleAdapter
*
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public HCModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "HC.html", client, HCParameters.getInstance(), true);
super(adapterName, "HC.html", client, HCParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -2,30 +2,29 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the MC module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 08.06.2004
* Time: 21:00:48
* To change this template use File | Settings | File Templates.
/**
* This the MC module adapter necessary to access this implementation from the EvA top level.
*/
public class MCModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Monte_Carlo_Search";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
private static final String moduleName = "Monte_Carlo_Search";
/**
* Constructor of the ModuleAdapter.
*
* @param adapterName The AdapterName
* @param client The client to serve
*/
public MCModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "MC.html", client, MCParameters.getInstance(), true);
super(adapterName, "MC.html", client, MCParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -4,30 +4,29 @@ import eva2.tools.jproxy.MainAdapterClient;
import java.io.Serializable;
/** This the MOEA module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 27.10.2004
* Time: 13:54:55
* To change this template use File | Settings | File Templates.
/**
* This the MOEA module adapter necessary to access this implementation from the EvA top level.
*/
public class MOEAModuleAdapter extends GenericModuleAdapter implements Serializable, ModuleAdapter {
public class MOEAModuleAdapter extends GenericModuleAdapter implements Serializable, ModuleAdapter {
public static String m_Name = "Multi-Objective_Evolutionary_Algorithms";
private static final String moduleName = "Multi-Objective_Evolutionary_Algorithms";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
/**
* Constructor of the ModuleAdapter
*
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public MOEAModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "MOEA.html", client, MOEAParameters.getInstance(), true);
super(adapterName, "MOEA.html", client, MOEAParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}
}

View File

@ -9,43 +9,54 @@ package eva2.server.modules;
* $Date: 2007-11-21 18:06:36 +0100 (Wed, 21 Nov 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import eva2.gui.EvATabbedFrameMaker;
import eva2.server.stat.EvAJob;
import eva2.tools.jproxy.RemoteStateListener;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface ModuleAdapter extends RemoteStateListener {
public EvATabbedFrameMaker getModuleFrame();
public void startOpt(); // called from client
/**
* Schedule a certain job to a job list.
*/
public EvAJob scheduleJob();
public void restartOpt();
public void stopOpt();
public void runScript();
/**
* Return true if post processing is available in principle, else false.
* @return true if post processing is available in principle, else false
*/
public boolean hasPostProcessing();
/**
* Return true if post processing was performed, else false.
* @return true if post processing was performed, else false
*/
public boolean startPostProcessing();
public void addRemoteStateListener(RemoteStateListener x);
public String getAdapterName();
public void setConnection(boolean flag);
public boolean hasConnection();
public void setRemoteThis(ModuleAdapter x);
public String getHostName();
EvATabbedFrameMaker getModuleFrame();
void startOpt(); // called from client
/**
* Schedule a certain job to a job list.
*
* @return A new Job
*/
EvAJob scheduleJob();
void restartOpt();
void stopOpt();
//void runScript();
/**
* Return true if post processing is available in principle, else false.
*
* @return true if post processing is available in principle, else false
*/
boolean hasPostProcessing();
/**
* Return true if post processing was performed, else false.
*
* @return true if post processing was performed, else false
*/
boolean startPostProcessing();
void addRemoteStateListener(RemoteStateListener x);
String getAdapterName();
void setConnection(boolean flag);
boolean hasConnection();
void setRemoteThis(ModuleAdapter x);
String getHostName();
}

View File

@ -2,30 +2,29 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the PBIL module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 08.06.2004
* Time: 21:52:22
* To change this template use File | Settings | File Templates.
/**
* This the PBIL module adapter necessary to access this implementation from the EvA top level.
*/
public class PBILModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Population_Based_Incremental_Learning";
private static final String moduleName = "Population_Based_Incremental_Learning";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public PBILModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "PBIL.html", client, PBILParameters.getInstance(), true);
}
/**
* Constructor of the ModuleAdapter
*
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public PBILModuleAdapter(String adapterName, MainAdapterClient client) {
super(adapterName, "PBIL.html", client, PBILParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
* @return The name
*/
public static String getName() {
return m_Name;
}
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return moduleName;
}
}

View File

@ -2,30 +2,29 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the PSO module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 16.11.2004
* Time: 17:58:19
* To change this template use File | Settings | File Templates.
/**
* This the PSO module adapter necessary to access this implementation from the EvA top level.
*/
public class PSOModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Particle_Swarm_Optimization";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
private static final String moduleName = "Particle_Swarm_Optimization";
/**
* Constructor of the Moduladapter
*
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public PSOModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "PSO.html", client, PSOParameters.getInstance(), true);
super(adapterName, "PSO.html", client, PSOParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapter
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -2,17 +2,12 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the SA module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 08.06.2004
* Time: 21:25:00
* To change this template use File | Settings | File Templates.
/**
* This the SA module adapter necessary to access this implementation from the EvA top level.
*/
public class SAModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Simulated_Annealing";
private static final String moduleName = "Simulated_Annealing";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
@ -23,10 +18,11 @@ public class SAModuleAdapter extends GenericModuleAdapter implements ModuleAdapt
super (adapterName, "SA.html", client, SAParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
/**
* This method returns the name of the ModulAdapter
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}
}

View File

@ -2,30 +2,29 @@ package eva2.server.modules;
import eva2.tools.jproxy.MainAdapterClient;
/** This the SSGA module adapter necessary to access this implementation
* from the EvA top level.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 19.07.2005
* Time: 15:44:53
* To change this template use File | Settings | File Templates.
/**
* This the SSGA module adapter necessary to access this implementation from the EvA top level.
*/
public class SSGAModuleAdapter extends GenericModuleAdapter implements ModuleAdapter {
public static String m_Name = "Steady_State_Genetic_Algorithm";
private static final String moduleName = "Steady_State_Genetic_Algorithm";
/** Constructor of the Moduladapter
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
/**
* Constructor of the ModuleAdapter
*
* @param AdapterName The AdapterName
* @param Client The client to serve
*/
public SSGAModuleAdapter(String adapterName, MainAdapterClient client) {
super (adapterName, "SSGA.html", client, SSGAParameters.getInstance(), true);
}
/** This method returns the name of the ModulAdapters
super(adapterName, "SSGA.html", client, SSGAParameters.getInstance(), true);
}
/**
* This method returns the name of the ModulAdapters
*
* @return The name
*/
public static String getName() {
return m_Name;
return moduleName;
}
}

View File

@ -25,249 +25,265 @@ import eva2.server.modules.AbstractModuleAdapter;
import eva2.server.modules.GenericModuleAdapter;
import eva2.server.modules.ModuleAdapter;
import eva2.tools.Serializer;
import java.awt.Color;
import javax.swing.*;
/**
* A selectable list of EvAJobs. Each job contains a GOParameters instance and potentially statistical data.
*
* A selectable list of EvAJobs. Each job contains a GOParameters instance and potentially
* statistical data.
*
* @author mkron
*
*/
public class EvAJobList extends PropertySelectableList<EvAJob> implements Serializable, InterfaceTextListener {
List<InterfaceTextListener> listeners = null;
private ModuleAdapter module = null;
public EvAJobList(EvAJob[] initial) {
super(initial);
}
List<InterfaceTextListener> listeners = null;
private ModuleAdapter module = null;
public String getName() {
return "Job Set";
}
public String globalInfo() {
return "Display a set of jobs consisting of a multi-run experiment.";
}
/**
* This adds a new job to the list.
*
* @param params
* @param stats
*/
public EvAJob addJob(InterfaceGOParameters params, AbstractStatistics stats) {
EvAJob job = new EvAJob((InterfaceGOParameters)Serializer.deepClone(params), stats);
stats.addDataListener(job);
addJob(job, true);
return job;
}
private void addJob(EvAJob j, boolean selected) {
EvAJob[] curArr = getObjects();
EvAJob[] newArr = null;
boolean[] newSelection = null;
if (curArr!=null && curArr.length>0) {
newArr = new EvAJob[curArr.length + 1];
newSelection = new boolean[newArr.length];
System.arraycopy(curArr, 0, newArr, 0, curArr.length);
System.arraycopy(m_Selection, 0, newSelection, 0, curArr.length);
} else {
newArr = new EvAJob[1];
newSelection = new boolean[1];
}
newSelection[newArr.length-1]=selected;
newArr[newArr.length-1] = j;
setObjects(newArr, newSelection);
}
public EvAJobList(EvAJob[] initial) {
super(initial);
}
/**
* Return the last job in the list, which is also the last one added.
*
* @return
*/
public EvAJob lastJob() {
EvAJob[] curArr = getObjects();
if (curArr!=null && curArr.length>0) return curArr[curArr.length-1];
else return null;
}
public String getName() {
return "Job Set";
}
/**
* Return a list of the currently selected jobs.
*
* @return
*/
public ArrayList<EvAJob> getSelectedJobs() {
EvAJob[] selected = getSelectedObjects();
ArrayList<EvAJob> l = new ArrayList<EvAJob>();
for (EvAJob j : selected) {
if (j!=null) l.add(j);
}
return l;
}
public String globalInfo() {
return "Display a set of jobs consisting of a multi-run experiment.";
}
public boolean saveSelectedJobs(Component parentComponent) {
EvAJob[] selected = getSelectedObjects();
if (selected!=null && (selected.length>0)) {
JFileChooser fc = new JFileChooser();
fc.setName("Select a directory to save jobs to...");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(parentComponent);
if (returnVal==JFileChooser.APPROVE_OPTION) {
File sFile = fc.getSelectedFile();
if (sFile.exists()) {
for (EvAJob job : selected) {
if (job!=null) {
if (!FileTools.saveObjectToFolder(job, sFile, false, parentComponent)) {
System.err.println("Error on saving jobs...");
return false;
}
}
}
} else return false; // invalid folder chosen
} else return false; // user break
}
return true;
}
/**
* This adds a new job to the list.
*
* @param params
* @param stats
*/
public EvAJob addJob(InterfaceGOParameters params, AbstractStatistics stats) {
EvAJob job = new EvAJob((InterfaceGOParameters) Serializer.deepClone(params), stats);
stats.addDataListener(job);
addJob(job, true);
return job;
}
/**
* Search for a job in the list which has the given parameter structure assigned.
* This is tested by reference, so the exact same instance of InterfaceGOParameters
* must be known. If no matching job is found, null is returned.
* @param params
* @return
*/
public EvAJob getJobOf(InterfaceGOParameters params) {
for (EvAJob job : getObjects()) {
if (job.getGOParams()==params) return job;
}
return null;
}
private void addJob(EvAJob j, boolean selected) {
EvAJob[] curArr = getObjects();
EvAJob[] newArr = null;
boolean[] newSelection = null;
if (curArr != null && curArr.length > 0) {
newArr = new EvAJob[curArr.length + 1];
newSelection = new boolean[newArr.length];
System.arraycopy(curArr, 0, newArr, 0, curArr.length);
System.arraycopy(m_Selection, 0, newSelection, 0, curArr.length);
} else {
newArr = new EvAJob[1];
newSelection = new boolean[1];
}
newSelection[newArr.length - 1] = selected;
newArr[newArr.length - 1] = j;
setObjects(newArr, newSelection);
}
/**
* Create a customized editor for the job list based on an array editor.
*
* @param jobList
* @return
*/
public static PropertyEditor makeEditor(final Component parent, final EvAJobList jobList) {
final GenericArrayEditor genericArrayEditor = new GenericArrayEditor();
genericArrayEditor.setWithAddButton(false);
genericArrayEditor.setWithSetButton(false);
ActionListener al=new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println("PING!");
// System.out.println(BeanInspector.toString(edi.getSelectedIndices()));
EvAStatisticalEvaluation.evaluate((InterfaceTextListener)jobList, jobList.getObjects(), genericArrayEditor.getSelectedIndices(),
(StatsOnSingleDataSetEnum[])EvAStatisticalEvaluation.statsParams.getOneSampledStats().getSelectedEnum(StatsOnSingleDataSetEnum.values()),
(StatsOnTwoSampledDataEnum[])EvAStatisticalEvaluation.statsParams.getTwoSampledStats().getSelectedEnum(StatsOnTwoSampledDataEnum.values()));
// System.out.println(BeanInspector.toString(EvAStatisticalEvaluation.statsParams.getPairedStats().getSelected()));
}
// public void actionPerformed(ActionEvent e) {
// if (statsFrame ==null) {
// statsFrame = new JEFrame("EvA2 Statistics Evaluation", true);
// JPanel tmpPan = createStatsPanel(jobList, edi);
// statsFrame.getContentPane().add(tmpPan);
// }
// if (!statsFrame.isVisible()) {
// statsFrame.pack();
// statsFrame.validate();
// statsFrame.setVisible(true);
// } else statsFrame.requestFocus();
// }
};
ActionListener sl=new ActionListener() {
public void actionPerformed(ActionEvent e) {
genericArrayEditor.selectDeselectAll();
}
};
ActionListener sal=new ActionListener() {
public void actionPerformed(ActionEvent e) {
jobList.saveSelectedJobs(genericArrayEditor);
}
};
genericArrayEditor.addUpperActionButton("(De-)Sel. all", sl);
genericArrayEditor.addUpperActionButton("Test Stats", al);
genericArrayEditor.addLowerActionButton("Save selected", sal);
/**
* Return the last job in the list, which is also the last one added.
*
* @return
*/
public EvAJob lastJob() {
EvAJob[] curArr = getObjects();
if (curArr != null && curArr.length > 0) {
return curArr[curArr.length - 1];
} else {
return null;
}
}
/**
* Return a list of the currently selected jobs.
*
* @return
*/
public ArrayList<EvAJob> getSelectedJobs() {
EvAJob[] selected = getSelectedObjects();
ArrayList<EvAJob> l = new ArrayList<EvAJob>();
for (EvAJob j : selected) {
if (j != null) {
l.add(j);
}
}
return l;
}
public boolean saveSelectedJobs(Component parentComponent) {
EvAJob[] selected = getSelectedObjects();
if (selected != null && (selected.length > 0)) {
JFileChooser fc = new JFileChooser();
fc.setName("Select a directory to save jobs to...");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(parentComponent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = fc.getSelectedFile();
if (sFile.exists()) {
for (EvAJob job : selected) {
if (job != null) {
if (!FileTools.saveObjectToFolder(job, sFile, false, parentComponent)) {
System.err.println("Error on saving jobs...");
return false;
}
}
}
} else {
return false; // invalid folder chosen
}
} else {
return false; // user break
}
}
return true;
}
/**
* Search for a job in the list which has the given parameter structure assigned. This is tested
* by reference, so the exact same instance of InterfaceGOParameters must be known. If no
* matching job is found, null is returned.
*
* @param params
* @return
*/
public EvAJob getJobOf(InterfaceGOParameters params) {
for (EvAJob job : getObjects()) {
if (job.getGOParams() == params) {
return job;
}
}
return null;
}
/**
* Create a customized editor for the job list based on an array editor.
*
* @param jobList
* @return
*/
public static PropertyEditor makeEditor(final Component parent, final EvAJobList jobList) {
final GenericArrayEditor genericArrayEditor = new GenericArrayEditor();
genericArrayEditor.setWithAddButton(false);
genericArrayEditor.setWithSetButton(false);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
EvAStatisticalEvaluation.evaluate((InterfaceTextListener) jobList, jobList.getObjects(), genericArrayEditor.getSelectedIndices(),
(StatsOnSingleDataSetEnum[]) EvAStatisticalEvaluation.statsParams.getOneSampledStats().getSelectedEnum(StatsOnSingleDataSetEnum.values()),
(StatsOnTwoSampledDataEnum[]) EvAStatisticalEvaluation.statsParams.getTwoSampledStats().getSelectedEnum(StatsOnTwoSampledDataEnum.values()));
}
};
ActionListener sl = new ActionListener() {
public void actionPerformed(ActionEvent e) {
genericArrayEditor.selectDeselectAll();
}
};
ActionListener sal = new ActionListener() {
public void actionPerformed(ActionEvent e) {
jobList.saveSelectedJobs(genericArrayEditor);
}
};
genericArrayEditor.addUpperActionButton("(De-)Sel. all", sl);
genericArrayEditor.addUpperActionButton("Test Stats", al);
genericArrayEditor.addLowerActionButton("Save selected", sal);
// edi.addPopupItem("Reset selected", getClearSelectedActionListener(parent, jobList)); // this option does not make much sense - instead of deleting data, taking over the settings for a new run is more plausible
genericArrayEditor.addPopupItem("Reuse as current settings", getReuseActionListener(parent, jobList));
genericArrayEditor.setAdditionalCenterPane(createStatsPanel(jobList, genericArrayEditor));
genericArrayEditor.setValue(jobList);
return genericArrayEditor;
}
genericArrayEditor.addPopupItem("Reuse as current settings", getReuseActionListener(parent, jobList));
genericArrayEditor.setAdditionalCenterPane(createStatsPanel(jobList, genericArrayEditor));
genericArrayEditor.setValue(jobList);
private static JPanel createStatsPanel(final EvAJobList jobList, final GenericArrayEditor edi) {
JParaPanel pan = new JParaPanel(EvAStatisticalEvaluation.statsParams, "Statistics");
JComponent paraPan = pan.makePanel();
JPanel tmpPan = new JPanel();
tmpPan.add(paraPan);
return tmpPan;
}
private static ActionListener getReuseActionListener(final Component parent, final EvAJobList jobList) {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<EvAJob> jobs = jobList.getSelectedJobs();
if (jobs.size()==1) {
EvAJob job = jobs.get(0);
AbstractGOParameters curParams = (AbstractGOParameters)((AbstractModuleAdapter)jobList.module).getGOParameters();
curParams.setSameParams((AbstractGOParameters) job.getGOParams());
((GenericModuleAdapter)jobList.module).setGOParameters(curParams);
((GenericModuleAdapter)jobList.module).getStatistics().getStatisticsParameter().setMultiRuns(job.getNumRuns());
((GenericModuleAdapter)jobList.module).getStatistics().getStatisticsParameter().setFieldSelection(job.getFieldSelection(((GenericModuleAdapter)jobList.module).getStatistics().getStatisticsParameter().getFieldSelection()));
} else JOptionPane.showMessageDialog(parent, "Select exactly one job to reuse!", "Error", JOptionPane.ERROR_MESSAGE);
}
};
return al;
}
return genericArrayEditor;
}
private static ActionListener getClearSelectedActionListener(final Component parent, final EvAJobList jobList) {
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
List<EvAJob> jobs = jobList.getSelectedJobs();
for (EvAJob j : jobs) j.resetJob();
}
};
return al;
}
private static JComponent createStatsPanel(final EvAJobList jobList, final GenericArrayEditor edi) {
JParaPanel pan = new JParaPanel(EvAStatisticalEvaluation.statsParams, "Statistics");
JComponent paraPan = pan.makePanel();
return paraPan;
}
/**
* Link a processor to the job list for re-scheduling jobs.
* @param processor
*/
public void setModule(ModuleAdapter mod) {
module = mod;
}
private static ActionListener getReuseActionListener(final Component parent, final EvAJobList jobList) {
ActionListener al = new ActionListener() {
public void addTextListener(InterfaceTextListener tListener) {
if (listeners==null) listeners = new LinkedList<InterfaceTextListener>();
if (!listeners.contains(tListener)) listeners.add(tListener);
}
public boolean removeTextListener(InterfaceTextListener tListener) {
if (listeners!=null) {
return listeners.remove(tListener);
} else return false;
}
public void actionPerformed(ActionEvent e) {
List<EvAJob> jobs = jobList.getSelectedJobs();
if (jobs.size() == 1) {
EvAJob job = jobs.get(0);
AbstractGOParameters curParams = (AbstractGOParameters) ((AbstractModuleAdapter) jobList.module).getGOParameters();
curParams.setSameParams((AbstractGOParameters) job.getGOParams());
((GenericModuleAdapter) jobList.module).setGOParameters(curParams);
((GenericModuleAdapter) jobList.module).getStatistics().getStatisticsParameter().setMultiRuns(job.getNumRuns());
((GenericModuleAdapter) jobList.module).getStatistics().getStatisticsParameter().setFieldSelection(job.getFieldSelection(((GenericModuleAdapter) jobList.module).getStatistics().getStatisticsParameter().getFieldSelection()));
} else {
JOptionPane.showMessageDialog(parent, "Select exactly one job to reuse!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
};
return al;
}
/*
* (non-Javadoc)
* @see eva2.server.stat.InterfaceTextListener#print(java.lang.String)
*/
public void print(String str) {
if (listeners!=null) for (InterfaceTextListener lst : listeners) {
lst.print(str);
}
}
private static ActionListener getClearSelectedActionListener(final Component parent, final EvAJobList jobList) {
ActionListener al = new ActionListener() {
/*
* (non-Javadoc)
* @see eva2.server.stat.InterfaceTextListener#println(java.lang.String)
*/
public void println(String str) {
if (listeners!=null) for (InterfaceTextListener lst : listeners) {
lst.println(str);
}
}
public void actionPerformed(ActionEvent e) {
List<EvAJob> jobs = jobList.getSelectedJobs();
for (EvAJob j : jobs) {
j.resetJob();
}
}
};
return al;
}
/**
* Link a processor to the job list for re-scheduling jobs.
*
* @param processor
*/
public void setModule(ModuleAdapter mod) {
module = mod;
}
public void addTextListener(InterfaceTextListener tListener) {
if (listeners == null) {
listeners = new LinkedList<InterfaceTextListener>();
}
if (!listeners.contains(tListener)) {
listeners.add(tListener);
}
}
public boolean removeTextListener(InterfaceTextListener tListener) {
if (listeners != null) {
return listeners.remove(tListener);
} else {
return false;
}
}
/*
* (non-Javadoc) @see eva2.server.stat.InterfaceTextListener#print(java.lang.String)
*/
public void print(String str) {
if (listeners != null) {
for (InterfaceTextListener lst : listeners) {
lst.print(str);
}
}
}
/*
* (non-Javadoc) @see eva2.server.stat.InterfaceTextListener#println(java.lang.String)
*/
public void println(String str) {
if (listeners != null) {
for (InterfaceTextListener lst : listeners) {
lst.println(str);
}
}
}
}

View File

@ -150,7 +150,9 @@ public class StatisticsWithGUI extends AbstractStatistics implements Serializabl
}
public void maybeShowProxyPrinter() {
if (proxyPrinter != null) proxyPrinter.setShow(m_StatsParams.isShowTextOutput());
if (proxyPrinter != null) {
proxyPrinter.setShow(m_StatsParams.isShowTextOutput());
}
}
protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) {

View File

@ -9,50 +9,46 @@ package eva2.tools;
* $Date: 2007-11-15 14:58:12 +0100 (Thu, 15 Nov 2007) $
* $Author: mkron $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.*;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.Properties;
/**
*
*/
public class EVAHELP {
private static long m_TimeStamp;
/**
*
*/
/**
*
*/
/**
*
*/
public static String getmyRUP() {
String Out= new String();
String Out = new String();
String HostName = "";
try {
HostName = InetAddress.getLocalHost().getHostName();
}
catch (Exception e) {
} catch (Exception e) {
System.out.println("ERROR getting HostName EVAHELP " + e.getMessage());
}
try {
BufferedReader in = null;
Process pro = null;
String command = "rup "+HostName;
String command = "rup " + HostName;
pro = Runtime.getRuntime().exec(command);
in = new BufferedReader ( new InputStreamReader (pro.getInputStream()));
in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = null;
while((line = in.readLine()) != null ) {
while ((line = in.readLine()) != null) {
//System.out.println(line);
Out = Out + line;
}
} catch (Exception e) {
System.out.println("Error in calling the command:"+e.getMessage());
System.out.println("Error in calling the command:" + e.getMessage());
}
return Out;
}
@ -63,17 +59,19 @@ public class EVAHELP {
public static void setTimeStamp() {
m_TimeStamp = System.currentTimeMillis();
}
/**
*
*/
public static long getTimeStamp() {
return System.currentTimeMillis() - m_TimeStamp;
}
/**
*
*/
public static void returnForExit() {
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("return for exit:");
try {
in.readLine();
@ -81,6 +79,7 @@ public class EVAHELP {
System.out.println(e.getMessage());
}
}
/**
*
*/
@ -98,6 +97,7 @@ public class EVAHELP {
}
return sBuf.toString();
}
/**
* @param longName The FQDN of a class
* @return Returns the class Name without package.
@ -110,6 +110,7 @@ public class EVAHELP {
}
return className; // now is shortName
}
/**
*
*/
@ -126,8 +127,8 @@ public class EVAHELP {
}
/**
* Log a String to a log-file indicated by the file name.
* If the file exists, the String is appended.
* Log a String to a log-file indicated by the file name. If the file
* exists, the String is appended.
*
* @param msg
* @param fileName
@ -136,8 +137,7 @@ public class EVAHELP {
final File logFile = new File(fileName);
try {
BufferedWriter bW = new BufferedWriter(
new PrintWriter(new FileOutputStream(logFile, logFile.exists()))
);
new PrintWriter(new FileOutputStream(logFile, logFile.exists())));
bW.write(msg);
bW.close();
} catch (IOException ex) {
@ -146,8 +146,8 @@ public class EVAHELP {
}
/**
* Deletes the given file in the current directory.
* If the file does not exist nothing happens.
* Deletes the given file in the current directory. If the file does not
* exist nothing happens.
*
* @param fileName The name of the log file
*/

View File

@ -2,9 +2,8 @@ package eva2.tools;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import java.awt.Toolkit;
import javax.swing.*;
/**
* Some helper methods connected to the GUI.
@ -17,7 +16,7 @@ public class ToolBoxGui {
/**
* Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial
* value can be set.
*
*
* @see JOptionPane
* @param parent the parent component
* @param title title of the dialog
@ -28,7 +27,7 @@ public class ToolBoxGui {
public static String getInputPaneInitialVal(Component parent, String title, String message, String initialVal) {
return getInputPaneInitialVal(parent, title, message, initialVal, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
}
/**
* Create a modal dialog similar to JOptionPane.showInputDialog, with the difference that an initial
* value can be set.
@ -50,11 +49,24 @@ public class ToolBoxGui {
jop.setInitialValue(initialVal); // this I expected to work next
jop.setInitialSelectionValue(initialVal); // this actually seems to work...
JDialog dialog = jop.createDialog(parent, title);
dialog.show();
dialog.setVisible(true);
Object value = jop.getValue();
if (value!=null && (value instanceof Integer) && ((Integer)value)==JOptionPane.OK_OPTION) {
String newStr=(String)jop.getInputValue();
return newStr;
} else return null;
if (value != null && (value instanceof Integer) && ((Integer) value) == JOptionPane.OK_OPTION) {
return (String) jop.getInputValue();
} else {
return null;
}
}
public static JButton createIconifiedButton(final String iconSrc, final String title, final boolean withTitle) {
JButton newButton;
byte[] bytes;
bytes = BasicResourceLoader.instance().getBytesFromResourceLocation(iconSrc, false);
if (bytes == null) {
newButton = new JButton(title);
} else {
newButton = new JButton(title, new ImageIcon(Toolkit.getDefaultToolkit().createImage(bytes)));
}
return newButton;
}
}

View File

@ -17,15 +17,10 @@ import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import eva2.tools.Serializer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.AccessControlException;
import java.util.logging.Level;
import java.util.logging.Logger;

View File

@ -8,24 +8,15 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:29 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.io.Serializable;
import java.util.ArrayList;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class JProxyRemoteThread implements InvocationHandler,
Serializable {
public class JProxyRemoteThread implements InvocationHandler, Serializable {
private static ComAdapter m_ComAdapter;
private Object m_Object;
private RMIThreadInvocationHandler m_RMIThreadHandler;
@ -33,7 +24,7 @@ public class JProxyRemoteThread implements InvocationHandler,
/**
*
*/
public static Object newInstance(Serializable object, String host) throws NO_RMIServerAvailable {
public static Object newInstance(Serializable object, String host) throws RMIServerNotAvailableException {
return Proxy.newProxyInstance(
object.getClass().getClassLoader(),
object.getClass().getInterfaces(),
@ -43,7 +34,7 @@ public class JProxyRemoteThread implements InvocationHandler,
/**
*
*/
public static Object newInstance(Serializable object) throws NO_RMIServerAvailable {
public static Object newInstance(Serializable object) throws RMIServerNotAvailableException {
return Proxy.newProxyInstance(
object.getClass().getClassLoader(),
object.getClass().getInterfaces(),
@ -80,7 +71,7 @@ public class JProxyRemoteThread implements InvocationHandler,
/**
*
*/
private JProxyRemoteThread(Serializable object, String host) throws NO_RMIServerAvailable {
private JProxyRemoteThread(Serializable object, String host) throws RMIServerNotAvailableException {
if (m_ComAdapter == null)
m_ComAdapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object, host);
@ -89,7 +80,7 @@ public class JProxyRemoteThread implements InvocationHandler,
/**
*
*/
private JProxyRemoteThread(Serializable object) throws NO_RMIServerAvailable {
private JProxyRemoteThread(Serializable object) throws RMIServerNotAvailableException {
if (m_ComAdapter == null)
m_ComAdapter = ComAdapter.getInstance();
m_RMIThreadHandler = m_ComAdapter.getRMIThreadHandler(object);

View File

@ -8,24 +8,26 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:29 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/
public interface MainAdapter {
public String getExecOutput(String command);
public void setBuf(String s);
public void killServer();
public void restartServer();
public String getBuf();
public RMIInvocationHandler getRMIHandler(Object obj);
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj);
public void setRemoteThis (MainAdapter x);
public String getExecOutput(String command);
public void setBuf(String s);
public void killServer();
public void restartServer();
public String getBuf();
public RMIInvocationHandler getRMIHandler(Object obj);
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj);
public void setRemoteThis(MainAdapter x);
}

View File

@ -8,13 +8,7 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/

View File

@ -8,14 +8,8 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.net.InetAddress;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/

View File

@ -8,146 +8,139 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
*/
public class MainAdapterImpl implements MainAdapter {
static final public String MAIN_ADAPTER_NAME = "MainRemoteObjectName";
static final public int PORT = 1099;
static public boolean TRACE = false;
private String m_Buf = "";
private MainAdapter m_RemoteThis;
/**
*
*/
public MainAdapterImpl() {
if (TRACE) System.out.println("Constructor MainAdapterImpl !!!!!!");
m_RemoteThis = this;
}
/**
*
*/
public void setBuf(String s) {
if (TRACE) System.out.println("MainAdapterImpl.setBuf:"+s);
m_Buf = s;
}
/**
*
*/
public void restartServer() {
System.out.println("Received message to restartServer !!!!");
try {
String command = "java -cp . eva2.server.EvAServer &";
System.out.println("Calling the command:"+"java eva2.server.EvAServer");
Process pro = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader ( new InputStreamReader (pro.getInputStream()));
// String line = null;
// while((line = in.readLine()) != null ) {
// System.out.println(line);
// Out = Out + line;
// }
System.out.println("command="+command);
} catch (Exception e) {
System.out.println("Error in calling the command:"+e.getMessage());
}
killServer();
}
/**
*
*/
public void killServer() {
//Mail.SendMail("Received message to kill EvAServer");
System.out.println("Received message to kill EvAServer !!!!");
KillThread x = new KillThread();
x.start();
return;
}
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
public static final String MAIN_ADAPTER_NAME = "MainRemoteObjectName";
public static final int PORT = 1099;
private String m_Buf = "";
private MainAdapter remoteThis;
/**
*
*/
public String getBuf() {
return m_Buf;
}
/**
*
*/
public String getExecOutput(String command) {
String Out= new String();
try {
BufferedReader in = null;
Process pro = null;
if (TRACE) System.out.println("Calling the command:"+command);
pro = Runtime.getRuntime().exec(command);
in = new BufferedReader ( new InputStreamReader (pro.getInputStream()));
String line = null;
while((line = in.readLine()) != null ) {
if (TRACE) System.out.println(line);
Out = Out + line;
}
} catch (Exception e) {
System.err.println("Error in calling the command:"+e.getMessage());
/**
*
*/
public MainAdapterImpl() {
remoteThis = this;
}
return Out;
}
/**
*
*/
public RMIInvocationHandler getRMIHandler(Object obj) {
System.out.println("getRMIHandler");
RMIInvocationHandler ret = null;
try {
ret = new RMIInvocationHandlerImpl(obj);
}
catch (Exception e) {
System.out.println("Error: RMIInvokationHandler getRMIHandler");
}
return ret;
}
/**
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj) {
if (TRACE) System.out.println("getRMIThreadHandler");
RMIThreadInvocationHandler ret = null;
try {
ret = new RMIThreadInvocationHandlerImpl(obj);
/**
*
*/
public void setBuf(String s) {
m_Buf = s;
}
catch (Exception e) {
System.out.println("Error: RMIThreadInvokationHandler getRMIThreadHandler");
/**
*
*/
public void restartServer() {
LOGGER.log(Level.INFO, "Received a Message to restart the server.");
try {
String command = "java -cp . eva2.server.EvAServer &";
LOGGER.log(Level.INFO, "Calling the command:" + "java eva2.server.EvAServer");
Process pro = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Error while restarting the server.", ex);
}
killServer();
}
/**
*
*/
public void killServer() {
LOGGER.log(Level.INFO, "Received a Message to kill the server.");
KillThread x = new KillThread();
x.start();
}
/**
*
*/
public String getBuf() {
return m_Buf;
}
/**
*
*/
public String getExecOutput(String command) {
StringBuffer output = new StringBuffer();
try {
BufferedReader in = null;
Process pro = null;
pro = Runtime.getRuntime().exec(command);
in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output.append(line);
}
} catch (Exception e) {
System.err.println("Error in calling the command:" + e.getMessage());
}
return output.toString();
}
/**
*
*/
public RMIInvocationHandler getRMIHandler(Object obj) {
System.out.println("getRMIHandler");
RMIInvocationHandler ret = null;
try {
ret = new RMIInvocationHandlerImpl(obj);
} catch (Exception e) {
System.out.println("Error: RMIInvokationHandler getRMIHandler");
}
return ret;
}
/**
*
*/
public RMIThreadInvocationHandler getRMIThreadHandler(Object obj) {
RMIThreadInvocationHandler ret = null;
try {
ret = new RMIThreadInvocationHandlerImpl(obj);
} catch (Exception e) {
System.out.println("Error: RMIThreadInvokationHandler getRMIThreadHandler");
}
return ret;
}
/**
*
*/
public void setRemoteThis(MainAdapter x) {
remoteThis = x;
}
return ret;
}
/**
*
*/
public void setRemoteThis (MainAdapter x) {
m_RemoteThis = x;
}
}
/**
*
*/
class KillThread extends Thread {
/**
*
*/
public void run() {
try {sleep(3000);}
catch(Exception e) {
System.out.println("Error in sleep");
/**
*
*/
public void run() {
try {
sleep(3000);
} catch (Exception e) {
System.out.println("Error in sleep");
}
System.exit(-1);
}
System.exit(-1);
}
}

View File

@ -22,134 +22,142 @@ import java.util.logging.Logger;
*
*/
public class RMIServer {
/* Version string of the server application. */
protected static RMIServer instance;
/* Name of host on which the server is running. */
private String myHostName = "undefined";
/* IP of host on which the server is running. */
private String myHostIP = "undefined";
/* MainAdapterImp object. This is need for the first
connection between the server and the client program. */
protected MainAdapter mainRemoteObject;
/* String describing the properties of the enviroment. */
/*
* Version string of the server application.
*/
protected static RMIServer instance;
/*
* Name of host on which the server is running.
*/
private String myHostName = "undefined";
/*
* IP of host on which the server is running.
*/
private String myHostIP = "undefined";
/*
* MainAdapterImp object. This is need for the first connection between the server and the
* client program.
*/
protected MainAdapter mainRemoteObject;
/*
* String describing the properties of the enviroment.
*/
// private ComAdapter m_ComAdapter;
protected static String userName;
protected static int numberOfVM = 0;
private Registry myRegistry = null;
protected static final Logger logger = Logger.getLogger(EvAInfo.defaultLogger);
/**
*
*/
public static RMIServer getInstance() {
if (instance == null) {
instance = new RMIServer();
}
return instance;
}
/**
* Constructor of EvAServer.
* Calls RMIConnection().
*/
protected RMIServer() {
userName = System.getProperty("user.name");
initConnection();
}
protected static String userName;
protected static int numberOfVM = 0;
private Registry myRegistry = null;
protected static final Logger LOGGER = Logger.getLogger(EvAInfo.defaultLogger);
/**
* Main method of this class.
* Is the starting point of the server application.
*/
public static void main(String[] args) {
logger.log(Level.INFO, "Start RMIServer !");
RMIServer application = RMIServer.getInstance();
}
/**
* Launches the RMIRegistry and makes the registration
* of the MainAdapterImpl class at the rmiregistry.
* @param
*/
private void initConnection() {
String mainAdapterName = userName + MainAdapterImpl.MAIN_ADAPTER_NAME;
System.setProperty("java.security.policy", "server.policy");
launchRMIRegistry();
try {
myHostIP = InetAddress.getLocalHost().getHostAddress();
myHostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
logger.log(Level.SEVERE, "Error getting HostName " + e.getMessage(), e);
/**
*
*/
public static RMIServer getInstance() {
if (instance == null) {
instance = new RMIServer();
}
return instance;
}
logger.log(Level.INFO, "Start of EvA RMI-Server on host " + myHostName + " = " + myHostIP);
try {
String[] list = Naming.list("rmi://localhost:" + MainAdapterImpl.PORT);
numberOfVM = getNumberOfVM(list);
} catch (RemoteException e) {
logger.log(Level.WARNING, "No RMI registry available yet");
} catch (MalformedURLException ex) {
logger.log(Level.SEVERE, "MalformedURLException: Error while looking up " + ex.getMessage(), ex);
}
createMainRemoteObject(mainAdapterName);
logger.log(Level.INFO, "End of RMI-Server Initialisation");
logger.log(Level.INFO, "Host: " + myHostName + " = " + myHostIP + ", adapter name is " + mainAdapterName);
logger.log(Level.INFO, "Waiting for a client.");
}
protected void createMainRemoteObject(String mainAdapterName) {
try {
mainRemoteObject = new MainAdapterImpl();
mainRemoteObject =
(MainAdapter) RMIProxyLocal.newInstance(mainRemoteObject,mainAdapterName + "_" + numberOfVM);
mainRemoteObject.setRemoteThis(mainRemoteObject);
} catch (Exception ex) {
logger.log(Level.WARNING, "Could not create main remote object!", ex);
}
}
/**
*
*/
public MainAdapter getMainRemoteObject() {
return mainRemoteObject;
}
/**
* Install RMIregistry on default port !!
*/
private void launchRMIRegistry() {
try {
myRegistry = java.rmi.registry.LocateRegistry.createRegistry(MainAdapterImpl.PORT);
} catch (Throwable e) {
myRegistry = null;
}
if (myRegistry == null) {
logger.log(Level.INFO, "Try to get registry with getRegistry on port " + MainAdapterImpl.PORT);
try {
myRegistry = java.rmi.registry.LocateRegistry.getRegistry(MainAdapterImpl.PORT);
} catch (RemoteException e) {
myRegistry = null;
}
}
if (myRegistry == null) {
logger.log(Level.WARNING, "Got no RMIREGISTRY");
}
}
/**
*
*/
private int getNumberOfVM(String[] list) {
int ret = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1)
ret++;
/**
* Constructor of EvAServer. Calls RMIConnection().
*/
protected RMIServer() {
userName = System.getProperty("user.name");
initConnection();
}
/**
* Main method of this class. Is the starting point of the server application.
*/
public static void main(String[] args) {
LOGGER.log(Level.INFO, "Start RMIServer !");
RMIServer application = RMIServer.getInstance();
}
/**
* Launches the RMIRegistry and makes the registration of the MainAdapterImpl class at the
* rmiregistry.
*
* @param
*/
private void initConnection() {
String mainAdapterName = userName + MainAdapterImpl.MAIN_ADAPTER_NAME;
System.setProperty("java.security.policy", "server.policy");
launchRMIRegistry();
try {
myHostIP = InetAddress.getLocalHost().getHostAddress();
myHostName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error getting HostName " + e.getMessage(), e);
}
LOGGER.log(Level.INFO, "Start of EvA RMI-Server on host " + myHostName + " = " + myHostIP);
try {
String[] list = Naming.list("rmi://localhost:" + MainAdapterImpl.PORT);
numberOfVM = getNumberOfVM(list);
} catch (RemoteException e) {
LOGGER.log(Level.WARNING, "No RMI registry available yet");
} catch (MalformedURLException ex) {
LOGGER.log(Level.SEVERE, "MalformedURLException: Error while looking up " + ex.getMessage(), ex);
}
createMainRemoteObject(mainAdapterName);
LOGGER.log(Level.INFO, "End of RMI-Server Initialisation");
LOGGER.log(Level.INFO, "Host: " + myHostName + " = " + myHostIP + ", adapter name is " + mainAdapterName);
LOGGER.log(Level.INFO, "Waiting for a client.");
}
protected void createMainRemoteObject(String mainAdapterName) {
try {
mainRemoteObject = new MainAdapterImpl();
mainRemoteObject =
(MainAdapter) RMIProxyLocal.newInstance(mainRemoteObject, mainAdapterName + "_" + numberOfVM);
mainRemoteObject.setRemoteThis(mainRemoteObject);
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Could not create main remote object!", ex);
}
}
/**
*
*/
public MainAdapter getMainRemoteObject() {
return mainRemoteObject;
}
/**
* Install RMIregistry on default port !!
*/
private void launchRMIRegistry() {
try {
myRegistry = java.rmi.registry.LocateRegistry.createRegistry(MainAdapterImpl.PORT);
} catch (Exception ex) {
myRegistry = null;
}
if (myRegistry == null) {
LOGGER.log(Level.INFO, "Try to get registry with getRegistry on port " + MainAdapterImpl.PORT);
try {
myRegistry = java.rmi.registry.LocateRegistry.getRegistry(MainAdapterImpl.PORT);
} catch (RemoteException e) {
myRegistry = null;
}
}
if (myRegistry == null) {
LOGGER.log(Level.WARNING, "Got no RMIREGISTRY");
}
}
/**
*
*/
private int getNumberOfVM(String[] list) {
int ret = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].indexOf(MainAdapterImpl.MAIN_ADAPTER_NAME) != -1) {
ret++;
}
}
return ret;
}
return ret;
}
}

View File

@ -8,17 +8,15 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/**
* This exception will be thrown when no
* RMIServer con be found by the ComAdapter.
* RMIServer can be found by the ComAdapter.
*/
public class NO_RMIServerAvailable extends Exception {
NO_RMIServerAvailable() {
printStackTrace();
}
public final class RMIServerNotAvailableException extends Exception {
@Override
public String getMessage() {
return "There is no RMI Server available.";
}
}

View File

@ -8,14 +8,8 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:31 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.rmi.Remote;
import java.rmi.RemoteException;
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*
*/

View File

@ -8,13 +8,6 @@ package eva2.tools.jproxy;
* $Date: 2004/04/15 09:12:30 $
* $Author: ulmerh $
*/
/*==========================================================================*
* IMPORTS
*==========================================================================*/
/*==========================================================================*
* INTERFACE DECLARATION
*==========================================================================*/
/**
*