Returning a JButton

Hey i want a method to return a JButton like so:
public JButton createButton(); // Make the actual button on the screen and pass it back to main
button = new JButton(""); // Creates the button
return button; // Returns the button to main
so only a few problems:
square.java:23: missing method body, or declare abstract
square.java:26: return outside method
So can you or cant you return a JButton in a method.

Hi
remove the semicolon after the method signature and then it should work.
public JButton createButton() {
} instead of
public JButton createButton();hope it helped

Similar Messages

  • How to create and use a new jbutton method?

    hi i'm making a program which has a lot of buttons so i decided to create a jbutton method, here it is
    public JButton newButton(String url, String url2)
              URL imgURL = MachineInterface.class.getResource(url);
              ImageIcon icon = new ImageIcon(imgURL);
              JButton button = new JButton(icon);
              button.setBorder(null);
              Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
              button.setCursor(cursor);
              URL imgURL2 = MachineInterface.class.getResource(url2);
              ImageIcon icon2 = new ImageIcon(imgURL2);
              button.setPressedIcon(icon2);
              return button;
         }the button shows up alrite if i do it like this
    panelEastSouth.add(tm.newButton("images/10p.png", "images/10pIn.png"));but i would like to do it like this
    newButton button10 = new newButton("images/10p.png", "images/10pIn.png");
              button10.addActionListener(this);i want it like this so i can add actionlisteners to them.
    how do i make this work?
    thanks
    brad

    newButton is a method returning a JButton, not a class, so it would be just
    JButton button10 = newButton("images/10p.png", "images/10pIn.png");
    button10.addActionListener(this);

  • How to return java objects on the button click

    hello all,
    i wonder if any body let me know ,how to return java objects on button click,
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class base
         base()
              JFrame frame = new JFrame("Base class Message Dialog Box");
              JPanel panel = new JPanel();
              JButton buttonchildone = new JButton("Child class one");
              buttonchildone.addActionListener(new ActionListener(){
                   public actionPerformed(ActionEvent e)
                        childone ch1=new childone();
                   return ch1;
              JButton buttonchildtwo = new JButton("Child class two");
              buttonchildtwo.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e)
                        childtwo ch2=new childtwo();
                        return ch2;
              panel.add(buttonchildone);
              panel.add(buttonchildtwo);
              frame.add(panel);
              frame.setSize(300, 300);
              frame.setVisible(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         void show()
              System.out.println("Base class show() method");
    public class mainmethod
         public static void main(String[] args)
              base baseobj=new base();
    here my aim is to achieve dynamic polymorphism by button click's ,where based on the button click i can send back an object of childone or childtwo classes
    thanks and regard
    Mac
    Message was edited by:
    LoveOpensource

    You probably need to rethink your design. Where are these child classes going? What is using or consuming them? I agree with the message above about a button instantiating a parent field variable to one child or the other depending on which button is pressed.
    Message was edited by:
    petes1234

  • JButton "sticking" in a JTable Cell

    So I've modified the renderer and what not and slapped a button into a JTable Cell. The assignment requires it to turn red/green altrenativly when pressed. It works perfectly aside from the fact that the buttons appear to not "bounce back" when they switch colors. (i.e. They appear depressed when red and pressed when green). The code is below. any ideas?
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JButton;
    public class ButtonTableModel extends AbstractTableModel {
         private static final long serialVersionUID = 1;
         private Object[][] rows = new Object[2][1];
         private String[] columns = new String[1];
         public ButtonTableModel() {
              for(int k = 0; k < rows.length; k++) {
                   JButton button3 = new JButton("222");
                   button3.setSize(200, 200);
                   button3.setBackground(Color.red);
                   button3.addMouseListener(new ColorChanger(button3));
                   rows[k][0] = button3;
              /*button = new JButton("Test Button");
              button.setBackground(Color.red);
              button.addMouseListener(new ColorChanger(button));
              button2 = new JButton("asdf");
              button2.setBackground(Color.red);
              button2.addMouseListener(new ColorChanger(button2));
              rows[0][0] = button;
              rows[1][0] = button2;*/
         private class ColorChanger implements MouseListener {
              private JButton callingButton; //Stores the button that added the Listener
              public ColorChanger(JButton pCallingButton) {  //Constructs a ColorChanger that stores a given JButton
                   callingButton = pCallingButton;
              public void mouseClicked(MouseEvent e) { //When callingButton is clicked, its color changes alternativly to green/red
                   if(isGreen(callingButton) == false)
                        callingButton.setBackground(Color.green);
                   else
                        callingButton.setBackground(Color.red);
              //The 4 methods below are unused leftovers specified by the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         private boolean isGreen(JButton pButton) { //Returns true if a button's background is green, false otherwise
              if(pButton.getBackground() == Color.green)
                   return true;
              return false;
         public int getColumnCount() { //Returns the number of Columns in a table
              return columns.length;
         public int getRowCount() { //Returns the number of rows in the table
              return rows.length;
         public String getColumnName(int pCollumnIndex) { //Returns the name of the collumn
              return columns[pCollumnIndex];
         public Object getValueAt(int pRow, int pColumn) { //Returns the value at given table coordinates
              return rows[pRow][pColumn];
         public boolean isCellEditable(int pRow, int pColumn) { //Returns true if a cell at given coordinates is editable, false otherwise
                  return false;
         public Class getColumnClass(int pColumnIndex) { //Retrieves the class of the objects in a column
              return getValueAt(0, pColumnIndex).getClass();
    import java.awt.Color;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JTable;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.table.TableCellRenderer;
    public class JButtonJTableTest extends JFrame {
         private static final long serialVersionUID = 1;
         private JTable table;
         private TableCellRenderer tableCellRenderer;
         private MouseEvent e2;
         private Class columnClass;
         private JButton button;
         private Point mousePos;
         private int mouseRow, mouseColumn;
         public JButtonJTableTest() {
              super("JButton Table Test");
              table = new JTable(); //Setup the table, assigning the new renderer and model
              tableCellRenderer = table.getDefaultRenderer(JButton.class);
              table.setDefaultRenderer(JButton.class, new JButtonRenderer(tableCellRenderer));
              table.setModel(new ButtonTableModel());
              table.setGridColor(Color.blue);
              table.addMouseListener(new MouseForwarder());
              table.setShowGrid(true);
              add(table); //Add the table to the content pane
         private class MouseForwarder implements MouseListener {
              public void mouseClicked(MouseEvent e) {
                   mousePos = new Point(e.getX(), e.getY()); //Assing mouse coordinates to a point data structure
                   mouseRow = table.rowAtPoint(mousePos);  //Ascertain the mouse's row & column
                   mouseColumn = table.columnAtPoint(mousePos);
                   if(mouseRow == -1 || mouseColumn == -1)  //Ensure that the column is within the table
                        return;
                   columnClass = table.getColumnClass(mouseColumn); //Ascertain the column's class
                   if(columnClass != JButton.class) //If the class is not JButton, exit MouseForwarder
                        return;
                   button = (JButton)table.getValueAt(mouseRow, mouseColumn); //Access the button where the mouse clicked
                   e2 = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button); //Forward click to button
                   button.dispatchEvent(e2); //Have button take action
                   table.repaint(); //Repaint the table to ensure proper button animation
              //The 4 methods below are unused methods from the MouseListener Interface
              public void mouseEntered(MouseEvent arg0) {
              public void mouseExited(MouseEvent arg0) {
              public void mousePressed(MouseEvent arg0) {
              public void mouseReleased(MouseEvent arg0) {
         public static void main(String[] args) { //Setup and run the window
              JButtonJTableTest test = new JButtonJTableTest();
              test.setSize(300, 300);
              test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              test.setVisible(true);
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    public class JButtonRenderer implements TableCellRenderer {
         private TableCellRenderer defaultRenderer;
         private Component jTableButton;
         public JButtonRenderer(TableCellRenderer pRenderer) {
              defaultRenderer = pRenderer;
         public Component getTableCellRendererComponent(JTable pTable, Object pButton, boolean isSelected,
                                                                     boolean hasFocus, int pRow, int pCollumn) {
              try {
                   jTableButton = (Component)pButton;
                   return (Component)pButton;
              catch(ClassCastException exception) {
                   return defaultRenderer.getTableCellRendererComponent(pTable, pButton, isSelected,
                        hasFocus, pRow, pCollumn);
    }

    This question was crossposted into the Swing forum and should be answered there as that is the correct location for it http://forum.java.sun.com/thread.jspa?threadID=753812

  • Whether JTable supports nesting of JButton or JCheckBox?

    Hi All,
    I need to show JButton or JCheckBoxes inside JTable. I tried extending from AbstractTableModel and overiden following method:
    public Object getValueAt(int row, int column)
    to return either JButton or JCheckBox, but while rendering the JTable it calls toString() method of the returned object i.e. either JButton or JCheckBox.
    Can any one pls guide me whether JTable supports nesting of JButton or JCheckBox? And if yes, How do I achieve the same.
    Pls reply at the earliest.
    Thanks,
    Sandesh

    Take a look at creating your own table cell renderer and table cell editor. Search for that on these forums, or better yet within Sun's Swing Java Tutorial. It can be done and it's not hard once you get the concept down. Note that JTable has a prepareRenderer method that returns a component to renderer, which can be any component you want and there are methods to easily assign a renderer and editor by column (or even more by cell, but that's a bit more complicated).

  • How to use Action/Input maps

    It seems to me that the move to sharing actions menus, buttons, and other components is a logical one, given that it is desirable to have all references to the action reflect its enabled state.
    The question that arises is: which ActionMap object to use as the central store? Do you create your own and pass it on somewhere?
    And, if you try to do anything with homegrown InputMaps then the components stop seeing the events. I wish there was a definitive YOU MUST DO IT THIS WAY tutorial.
    Why is there no factory API that can create UI components pre-attached to actions and with accelerators or mnemonics already set? Then we would not need to write half the code we do now. My solution:
    public class ComponentFactory {
       ActionMap myMap;
       public ComponentFactory(ActionMap map) {
          myMap = map;
       public JButton createButton(String actioncommand) {
           Action a = myMap.get(actioncommand)
           if(a==null)
              return null;
           return new JButton(a);
       public JMenuItem createMenuItem(String actioncommand) {
        // etc...
       public void setAction(Action a) {
           myMap.put(a.getValue(ACTION_COMMAND_KEY),a);
       public void setEnabled(String actioncommand, boolean state) {
           Action a = myMap.get(actioncommand);
           if(a!=null)
               a.setEnabled(state);
    }Is there any concensus as to the best way to handle ActionMaps/InputMaps?

    Hugh,
    >
    The tutorial is a touch short on this subject, whilst
    it is good on how to create and use actions with
    toolbars and the like, the section on InputMaps and
    ActionMaps is far too brief to get the wider picture.
    The API docs on the same is about one paragraph's
    worth.okay, I just checked the tutorial - it's a bit short on the inputMap/actionMap indeed.
    >
    You are mixing up two different issues:
    a) customize a button with an action
    b) bind a keyStroke to an action for an arbitrary
    jComponent
    a) has nothing to do with b)If b) has nothing to do with a) why have MNEMONIC_KEY
    and ACCELERATOR_KEY on the action?Hmm... where do you see a contradiction to my statement? Those keys are part of a) as they are used for customization of the AbstractButtons: the button's mnenmonic/accelerator properties are set to the corresponding values of the action. This propertyChange triggers an update of the keyBinding to the button's "pressed"/"doClick" actions as registered in the actionMap. They are never used (at least not internally by Swing) for b)
    Historically the action is older than the inputMap/actionMap: basically it's an ActionListener (which is more or less a command pattern) plus some (view) state. This "plus" was designed right in the beginning of Swing for a) to enable state sharing between different "buttons" but not really integrated until version 1.4. parallel to that the need for a general mechanism of binding between keyStrokes and "commands" became obvious and inputMap/actionMap were introduced in 1.3. The only action state that's needed for this mechanism to work is the enabled property. All values are ignored - so currently they somehow appear to be overloaded in the context of the inputMap/actionMap. Personally I think they are very powerful because of this extra flexibility.
    >
    There is still not a single diagram; and I maintain
    that it is less than useful to beginners who are not
    familiar with the terminology used. Well, IMO diagrams are not everything - I still think it much easier to understand than the dnd spec or the focus spec f.i.
    >
    you are free to use whatever object you want as akey
    - write a utility method to use the name, if feellike
    doeing so. There is nothing in the framework that
    would single out the name as "the" key to use, The keybindings document specifically states:
    "New actions can be added to a component equally
    easily."
    "The conventional key for an action is it's
    name." If there is a conventional way then it
    should be encouraged with an appropriate API. I get your point. And I definitely agree on following a convention if there is one. Except when the convention is quite immature (to formulate mildly) - and not even followed by Swing internally: most of the default actions registered in the actionMap don't even have a name, the binding is done by string literals ... duplicated in at least two places: the XXLookAndFeel and the ui-delegates.
    Greetings
    Jeanette

  • Hiding a form card layout

    Hey folks i have the code below, its an example that i have been messing around with.
    I have a on the first card button 2 which has an action listener on, it simply opens another formwhich it does correct but i want the form with the card layout on it to be hidden.
    As you can see from my code i have triediy numerous ways with no luck, hope i'm in the right forum and this shouldnt be in event handling
    Any ideas welcomed
    Ambrose
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Tab_Demo implements ActionListener
         final static String ROUTER1 = "Router One";
         final static String ROUTER2 = "Router Two";
         final static String ROUTER3 = "Router Three";
         final static String ROUTER4 = "Router Four";
         final static String ROUTER5 = "Router Five";
         final static String ROUTER6 = "Router Six";
         private     JTable          table1;
         private     JTable          table2;
         private     JTable          table3;
         private     JTable          table4;
         private     JTable          table5;
               public JFrame frame;
         private Button b1 = new Button("Add");
         public void addComponentToPane(Container pane)
              JTabbedPane tabbedPane = new JTabbedPane(); //Create the "cards".           
              JPanel card1 = new JPanel()
         //Make the panel wider than it really needs, so //the window's wide enough for the tabs to stay //in one row.
         public Dimension getPreferredSize()
              Dimension size = super.getPreferredSize();
              size.width += 100;
              size.height += 600;
              return size;
              JButton button2 = new JButton("Button 2");
           button2.addActionListener(this);
           button2.setActionCommand("button2");
            card1.add(button2);
              card1.add(b1);
              card1.add(new JButton("But3"));
              card1.add(new JTextField("f",20));
              JPanel card2 = new JPanel();
              card2.add(new JButton("buttonDays"));
              // Create columns names
              String columnNames[] = { "IP Address ", "Address", "Private User", };
              // Create some data
              String dataValues[][] =
                   { "IP1", "Dublin 1 Ireland", "Yes" },
                   { "1P2", "Dublin 1 Ireland", "Yes" },
                   { "IP3", "Dublin 1 Ireland", "Yes" },
                   { "IP4", "Dublin 1 Ireland", "Yes" },
                   { "IP5", "Dublin 1 Ireland", "Yes" }
              // Create a new table instance
              table2 = new JTable( dataValues, columnNames );
              card2.add(new JScrollPane(table2));
              JPanel card3 = new JPanel();
              JPanel card4 = new JPanel();
              JPanel card5 = new JPanel();
              JPanel card6 = new JPanel();
              tabbedPane.addTab(ROUTER1, card1);
              tabbedPane.addTab(ROUTER2, card2);
              tabbedPane.addTab(ROUTER3, card3);
              tabbedPane.addTab(ROUTER4, card4);
              tabbedPane.addTab(ROUTER5, card5);
              tabbedPane.addTab(ROUTER6, card6);
              pane.add(tabbedPane, BorderLayout.CENTER);
              b1.addActionListener(this);
              public void actionPerformed( ActionEvent e)
              if (e.getActionCommand().equals("button2"))
                   Main_Menu fr = new Main_Menu("User Main Menu");
                   //Test.setDefaultLookAndFeelDecorated(true);
                   fr.show();
                   //this.hide();
                   //frame.setVisible(false);
              /** * Create the GUI and show it. For thread safety, *
              *this method should be invoked from the * event-dispatching thread. */
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new JFrame("TabDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              Tab_Demo demo = new Tab_Demo();
              demo.addComponentToPane(frame.getContentPane());
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
         public void run()
         createAndShowGUI();
    }

    HIDE_WINDOW does not hide a window that is associated to the main canvas of a form, same goes for HIDE_VIEW. And what do you mean by open_form?

  • Hiding a form using card layout

    Hey folks i have the code below, its an example that i have been messing around with.
    I ahve a on the first card button 2 which has an action listener on, it simply opens another formwhich it does correct but i want the form with the card layout on it to be hidden.
    As you can see from my code i have triediy numerous ways with no luck, hope i'm in the right forum and this shouldnt be in event handling
    Any ideas welcomed
    Ambrose
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Tab_Demo implements ActionListener
         final static String ROUTER1 = "Router One";
         final static String ROUTER2 = "Router Two";
         final static String ROUTER3 = "Router Three";
         final static String ROUTER4 = "Router Four";
         final static String ROUTER5 = "Router Five";
         final static String ROUTER6 = "Router Six";
         private     JTable          table1;
         private     JTable          table2;
         private     JTable          table3;
         private     JTable          table4;
         private     JTable          table5;
               public JFrame frame;
         private Button b1 = new Button("Add");
         public void addComponentToPane(Container pane)
              JTabbedPane tabbedPane = new JTabbedPane(); //Create the "cards".           
              JPanel card1 = new JPanel()
         //Make the panel wider than it really needs, so //the window's wide enough for the tabs to stay //in one row.
         public Dimension getPreferredSize()
              Dimension size = super.getPreferredSize();
              size.width += 100;
              size.height += 600;
              return size;
              JButton button2 = new JButton("Button 2");
           button2.addActionListener(this);
           button2.setActionCommand("button2");
            card1.add(button2);
              card1.add(b1);
              card1.add(new JButton("But3"));
              card1.add(new JTextField("f",20));
              JPanel card2 = new JPanel();
              card2.add(new JButton("buttonDays"));
              // Create columns names
              String columnNames[] = { "IP Address ", "Address", "Private User", };
              // Create some data
              String dataValues[][] =
                   { "IP1", "Dublin 1 Ireland", "Yes" },
                   { "1P2", "Dublin 1 Ireland", "Yes" },
                   { "IP3", "Dublin 1 Ireland", "Yes" },
                   { "IP4", "Dublin 1 Ireland", "Yes" },
                   { "IP5", "Dublin 1 Ireland", "Yes" }
              // Create a new table instance
              table2 = new JTable( dataValues, columnNames );
              card2.add(new JScrollPane(table2));
              JPanel card3 = new JPanel();
              JPanel card4 = new JPanel();
              JPanel card5 = new JPanel();
              JPanel card6 = new JPanel();
              tabbedPane.addTab(ROUTER1, card1);
              tabbedPane.addTab(ROUTER2, card2);
              tabbedPane.addTab(ROUTER3, card3);
              tabbedPane.addTab(ROUTER4, card4);
              tabbedPane.addTab(ROUTER5, card5);
              tabbedPane.addTab(ROUTER6, card6);
              pane.add(tabbedPane, BorderLayout.CENTER);
              b1.addActionListener(this);
              public void actionPerformed( ActionEvent e)
              if (e.getActionCommand().equals("button2"))
                   Main_Menu fr = new Main_Menu("User Main Menu");
                   //Test.setDefaultLookAndFeelDecorated(true);
                   fr.show();
                   //this.hide();
                   //frame.setVisible(false);
              /** * Create the GUI and show it. For thread safety, *
              *this method should be invoked from the * event-dispatching thread. */
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new JFrame("TabDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Create and set up the content pane.
              Tab_Demo demo = new Tab_Demo();
              demo.addComponentToPane(frame.getContentPane());
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
         public void run()
         createAndShowGUI();
    }

    HIDE_WINDOW does not hide a window that is associated to the main canvas of a form, same goes for HIDE_VIEW. And what do you mean by open_form?

  • Add button to a JTable

    i added a button a Jtable.but am not able to dispatch the mouse click event to the button. I am not seeing any change in the button when clicked....its not getting the focus. the code is as below:
    class TableButtonMouseListener implements MouseListener {
    private JTable table;
    private void forwardEventToButton(MouseEvent e) {
    TableColumnModel columnModel = table.getColumnModel();
    int column = columnModel.getColumnIndexAtX(e.getX());
    System.out.println("column "+column);
    int row = e.getY() / table.getRowHeight();
    System.out.println("row "+row);
    Object value;
    JButton button;
    MouseEvent buttonEvent;
    if(row >= table.getRowCount() || row < 0 ||
    column >= table.getColumnCount() || column < 0)
    return;
    value = table.getValueAt(row, column);
    if(!(value instanceof JButton))
    return;
    button = (JButton)value;
    buttonEvent =(MouseEvent)SwingUtilities.convertMouseEvent(table, e, button);
    button.dispatchEvent(buttonEvent);
    // This is necessary so that when a button is pressed and released
    // it gets rendered properly. Otherwise, the button may still appear
    // pressed down when it has been released.
    table.repaint();
    public TableButtonMouseListener(JTable table) {
    this.table = table;
    public void mouseClicked(MouseEvent e) {
    forwardEventToButton(e);
    public void mouseEntered(MouseEvent e) {
    //forwardEventToButton(e);
    public void mouseExited(MouseEvent e) {
    //forwardEventToButton(e);
    public void mousePressed(MouseEvent e) {
    forwardEventToButton(e);
    public void mouseReleased(MouseEvent e) {
    forwardEventToButton(e);
    pls help ....

    -> I am a first time user.that is y....
    What does that have to do with anything. As a first time user you should take the time to learn how to use the forum. In any forum, not just this one, it is common sense to search first before asking questions.
    -> but can u pls tell me y the button is nt getting the event
    Did you read the JTable API? It has a link to the Swing tutorial that explains how tables work. You need to understand the section on renderers. In general a renderer is a drawing of the button, it is not a real button so it doesn't receive events.
    The problem has nothing to do with the TableModel.

  • Inner/anonymous classes

    I have searched and found other versions of this question, but haven't run across the answer yet, so...
    My program runs correctly from the command line.
    When I try to execute the .jar file using the java -jar TIS.jar command I get a noclassdeffound error. The class it can't find happens to be the first inner class it encounters. I have checked the jar file, and the class is in there. Is there a problem with java finding inner classes in jar files?
    Some supporting info:
    here is my manifest:
    Manifest-Version: 1.0
    Created-By: 1.4.1_01 (Sun Microsystems Inc.)
    Main-Class: ToolInventorySystem
    class not found has the name ControlScreen$addToolListener.class
    I found in another post that the $ indicates either an anonymous class or an inner class (I have both in my programs)
    Thanks in advance

    Wow, that formatting didn't work, let me try that again...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class ControlScreen extends JFrame {
         //Fields for screen size
         public static final int DEFAULT_WIDTH = 500;
         public static final int DEFAULT_HEIGHT = 500;
         public ControlScreen(){
              setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
              Container contentPane = getContentPane();
              JPanel SelectButtonPanel = new JPanel();
              //Selection Buttons     
              //add new tools
              JButton addToolButton = new JButton("Add Tool");
              SelectButtonPanel.add(addToolButton);
              ActionListener atl = new AddToolListener();
              addToolButton.addActionListener(atl);
              //add new projects
              JButton addProjectButton = new JButton("Add Project");
              SelectButtonPanel.add(addProjectButton);
              ActionListener apl = new AddProjectListener();
              addProjectButton.addActionListener(apl);
              //check out tools
              JButton checkOutToolButton = new JButton("Check Out Tools");
              SelectButtonPanel.add(checkOutToolButton);
              ActionListener cotl = new CheckOutToolListener();
              checkOutToolButton.addActionListener(cotl);
              //return tools
              JButton returnToolButton = new JButton("Return Tool");
              SelectButtonPanel.add(returnToolButton);
              ActionListener rtl = new ReturnToolListener();
              returnToolButton.addActionListener(rtl);
              //generate bill
              JButton billButton = new JButton("Create Billing Statement");
              SelectButtonPanel.add(billButton);
              ActionListener bl = new BillListener();
              billButton.addActionListener(bl);
              contentPane.add(SelectButtonPanel, BorderLayout.SOUTH);
         }//close constructor
         class AddToolListener implements ActionListener{
         public void actionPerformed(ActionEvent event){
              //This class will display the tool entry frame
              ToolScreen ts = new ToolScreen();
              ts.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              ts.show();
              }//close method
         }//close addToolListener
         class AddProjectListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //This class will display the project entry frame
                   ProjectScreen ps = new ProjectScreen();
                   ps.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   ps.show();
              }//close method
         }//close addprojectlistener
         class CheckOutToolListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   CheckoutProjectListDisplayScreen cplds = new CheckoutProjectListDisplayScreen(projectList);
                   cplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   cplds.show();
              }//close method
         }//close check out tool listener
         class ReturnToolListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   ReturnProjectListDisplayScreen rplds = new ReturnProjectListDisplayScreen(projectList);
                   rplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   rplds.show();
              }//close method
         }//close check out tool listener
         class BillListener implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   //this class displays the list of active projects
                   Project[] projectList = TISController.getProjectList();
                   BillProjectListDisplayScreen bplds = new BillProjectListDisplayScreen(projectList);
                   bplds.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   bplds.show();
              }//close method
         }//close create bill listener
    }//close Control Screen class

  • JpopupMenu disappear after click one it.

    Hi , I have a problem with a 3rd party library. by the way. please help,
    Applet contain Panel name "Chooser"
    "Chooser" contain a button "open"
    After click on the "open" button it will invoke Jpopupmenu
    JpopupMnu have another panel inside
    Some people overridden setVisible() method
    I seem that when i click on any area on anything this panel on Jpopupmenu Jpopupmanu will be diappear.
    someone HINT that :
    have to do something with the popup's overriden setVisible method. Tell the "Chooser" from applet that the application is an applet, so it doesn't set the "popup" window non-visible.

    no ..... is it?
    This is my code......
    when i deploy applet i can't click any button on Jpopupmenu it will disappear before
    someone said to overridden setvisible method to said that the application is an applet ...........??!?!?!?! any body understand what does that mean ....
    package test;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    public class JChooser extends JApplet implements ActionListener{
    private JPopupMenu m_objJPopupMenu;
    private boolean m_bInitialized;
    protected boolean m_bDateSelected;
    private JButton m_objXButton;
    public JChooser(){
    public void init(){
    JLabel test = new JLabel();
    test.setText("Test");
    getContentPane().add(test);
    getContentPane().add(getXButton(), BorderLayout.EAST);
    m_objJPopupMenu = new JPopupMenu()
    public void setVisible(boolean bVisibleP)
    Boolean isCanceled =
    (Boolean) getClientProperty("JPopupMenu.firePopupMenuCanceled");
    if (bVisibleP
    || (!bVisibleP && m_bDateSelected)
    || ((isCanceled != null) && !bVisibleP && isCanceled.booleanValue()))
    super.setVisible(bVisibleP);
    m_objJPopupMenu.setLightWeightPopupEnabled(true);
    m_objJPopupMenu.add(getXPanel());
    m_bInitialized = true;
    * @return
    private JButton getXButton() {
    if (m_objXButton == null)
    m_objXButton = new JButton();
    m_objXButton.addActionListener(this);
    return m_objXButton;
    public void actionPerformed(ActionEvent e)
    int x =
    getXButton().getWidth() - (int) m_objJPopupMenu.getPreferredSize().getWidth();
    int y = getXButton().getY() + getXButton().getHeight();
    m_objJPopupMenu.show(getXButton(), x, y);
    * @return
    private JPanel getXPanel() {
    JPanel aPanel = new JPanel();
    aPanel.setLayout(new GridLayout(5,2));
    aPanel.add(one_btn);
    aPanel.add(two_btn);
    aPanel.add(three_btn);
    aPanel.add(four_btn);
    aPanel.add(five_btn);
    aPanel.add(six_btn);
    aPanel.add(seven_btn);
    aPanel.add(eight_btn);
    aPanel.add(nine_btn);
    aPanel.add(ten_btn);
    aPanel.add(eleven_btn);
    aPanel.add(twelve_btn);
    aPanel.setSize(100,100);
    twelve_btn.addActionListener(new Eavesdropper());
    return aPanel;
    private JButton one_btn = new JButton();
    private JButton two_btn = new JButton();
    private JButton three_btn = new JButton();
    private JButton four_btn = new JButton();
    private JButton five_btn = new JButton();
    private JButton six_btn = new JButton();
    private JButton seven_btn = new JButton();
    private JButton eight_btn = new JButton();
    private JButton nine_btn = new JButton();
    private JButton ten_btn = new JButton();
    private JButton eleven_btn = new JButton();
    private JButton twelve_btn = new JButton();
    class Eavesdropper implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    one_btn.setText("aaaa");
    }

  • Putting more than one picture on a component?

    Hey
    im creating an AI agent that wanders around a world and eat and drinks and all that in java. Each position in the world is represented by a JButton(at the mo). My problem is that i need to be able to show two or more pictures on the one JButton at a time on top of each other, i.e. a position in the world could have the agent and a food source at the same time. Does anyone know if i can do this with a JButton or should i change to a panel or something different -
    Thanks

    Hello, I think what tjacobs01 means is to overwrite the paintComponent method. In doing this, you do not have to worry about the Graphics g Object . This is passed to the method automatically.
    The img1 and img 2 references would be the two images you wanted to place with the button, ie, a world location and a food location. (S)He has placd them as img1 and img2 as generic references, perhaps putting in img1 is worldImage and img2 as foodImage it may have been more understandable. I am not trying to bag tjacobs01, just trying to show you what (s)he may have meant..
    tjacobso1's code is below
    public void paintComponent(Graphics g) {
    g.drawImage(img1, ...)
    g.drawImage(img2, ...)
    }The code I am replying to was,
    public Graphics paintComponent(Graphics g)
    g.drawImage(img1, ...)
    g.drawImage(img2, ...)
    return g;
    JButton jb = new JButton();
    jb.setIcon(paintComponent(new Graphics));You could try something like
    // you image does not have to be an ImageIcon, it can be whatever you would like
    ImageIcon worldImage = new ImageIcon("yourWorldImage.gif");
    ImageIcon canOfDrinkImage = new ImageIcon("yourCanOfDrinkImage.gif");
    ImageIcon hotdogImage = new ImageIcon("yourHotdogImage");
    // as many images as you would like
    // it would be best to have boolean values for saying whether to display an image or not, or flags of some sort to determine which images to display. Then in the paintComponents method below, you can easily choose which image to paint.
    JButton jb = new JButton() {
            // this is called an anonymous inner class, as it is an inner class without a name.
            public void paintComponent(Graphics g) {
                // make some ints to hold the positions of the next image to draw, update these after every image added below.
                int x = 0;
                int y = 0;
                int distanceBetweenImages = 3;
                int imageWidth = 32; // this size should be known by you or you can find out from the ImageIcon.getIconWidth();
                int imageHeight = 32; // same as above comment
                // use the booleans that i mentioned previously here, in a manner similar to ...
                if (showWorldImage) {
                     * since the g.drawImage has a lot of overloaded methods, meaning you can call it with different parameters, it is worth looking at the api code for the java.awt.Graphics class.
                     * This seems like the most basic method for your use
                     * drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
                     * I have not talked about the ImageObserver at all, but you should be able to find details about it also in the API.
                   g.drawImage(worldImage, x, y, imageWidth, imageHeight, observer);
                   x += imageWidth + distanceBetweenImages;
                if (showCanOfDrinkImage) {
                    // include same as showWorldImage
                   g.drawImage(worldImage, x, y, imageWidth, imageHeight, observer);
                   x += imageWidth + distanceBetweenImages;
    };Then when the JButton needs to be repainted it will call that method and repaint according to what images you have.
    I have not icluded the code to paint any text string, if you wanted to display text..
    If you think this is too much work, and you would prefer to use a JPanel, that is up to you. With a JPanel you will not have to worry about spacing between the icons etc, and I would recommend you use JLabels for the Images.
    Jack573

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

  • Urgent - How to add buttons to a Table

    How to add buttons to a Table and enable them for Mouse Listeners/ Action Listeners

    extends the defaultcellrenderer make it return a Jbutton as the component to draw.
    class OverCellRendererClass extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
    //put your stuff here to make or get a button
    return myButton;
    Use something like this to set the renderer for the column :
    tb.getColumnModel().getColumn(4).setCellRenderer(new YourCellRendererClass());

  • Error opening environment more than once

    Hi,
    I have two java classes which both need to access a container in an environment (in parallel). When the first class is instantiated the environment is opened successfully. However, when the second class subsequently attempts to open the same environment I get an error. (I do not want to close the env from the first class, while the second class does its thing)
    The classes are Stylesheet extensions for an xmleditor which allows the stylesheet to look up item ID codes and display their names to the user by looking up the values in an xml file stored in a bdbxml container. There is a situation where two different objects need to have access to the environment at the same time - but its giving me an error when I instantiate the env for the second time - without having closed the first one)
    Any help would by gratefully received
    Kind Regards
    Swami Kevala
    I thought I could create multiple handles to the same environment?

    First is a class to encapsulate the environment (lifted mostly from the example code)
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open and close a Berkeley DB environment
    public class DbEnv
    private Environment dbEnv_ = null;
    private XmlManager mgr_ = null;
    private boolean dbEnvIsOpen_ = false;
    private File path2DbEnv_ = null;
    public DbEnv(File path2DbEnv)
         throws Throwable {
              if (! path2DbEnv.isDirectory()) {
                   throw new Exception(path2DbEnv.getPath() +
                             " does not exist or is not a directory.");
              EnvironmentConfig config = new EnvironmentConfig();
              config.setCacheSize(50 * 1024 * 1024);
              config.setAllowCreate(true);
              config.setInitializeCache(true);
              config.setTransactional(true);
              config.setInitializeLocking(true);
              config.setInitializeLogging(true);
              config.setErrorStream(System.err);
              config.setThreaded(true);
              config.setRunRecovery(true);
              config.setLogAutoRemove(true);
              dbEnv_ = new Environment(path2DbEnv, config);
              //Boolean used to know whether to close the environment
              // when the cleanup() method is called.
              dbEnvIsOpen_ = true;
              path2DbEnv_ = path2DbEnv;
              mgr_ = new XmlManager(dbEnv_, null);
    //Returns the path to the database environment
    public File getDbEnvPath() { return path2DbEnv_; }
    //Returns the database environment encapsulated by this class.
    public Environment getEnvironment() { return dbEnv_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the environment
    public void cleanup() throws DatabaseException
    if (dbEnvIsOpen_) {
    dbEnv_.close();
    dbEnvIsOpen_ = false;
    Second is a class which encapsulates a container with a method for querying itself
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open, query and close a Berkeley DB container
    public class DbContainer
         private XmlContainer dbCont_ = null;
    private XmlManager mgr_ = null;
    private boolean dbContainerIsOpen_ = false;
    private File path2DbContainer_ = null;
    private XmlContainerConfig cfg_= null;
    private String cntr_ = "";
    public DbContainer(XmlManager myManager, String containerFileName, XmlContainerConfig containerConfig)
              throws Throwable {
              String containerFilepath = myManager.getHome() + "\\" + containerFileName;
              path2DbContainer_ = new File(containerFilepath);
              mgr_ = myManager;
              cfg_ = containerConfig;
              cntr_ = containerFileName;
              if (! path2DbContainer_.isFile()) {
                   throw new Exception(path2DbContainer_.getPath() +
                             " does not exist or is not a directory.");
              dbCont_ = new XmlContainer();
    //Return the XmlContainer itself
    public XmlContainer getContainer() { return dbCont_; }
    //Returns the filename of the container
         public String getFilename() { return cntr_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the container
    public void close() throws DatabaseException
    if (dbContainerIsOpen_) {
    dbCont_.close();
    dbContainerIsOpen_ = false;
    //Used to open the container
    public void open() {
              try {
                   dbCont_ = mgr_.openContainer(cntr_, cfg_);
                   dbContainerIsOpen_ = true;
              catch (Exception e) {
    //Used to query the container
    public String[] runQuery(String myQuery){
              String [] queryOutput = null;
              int counter = 0;
              try {
                   XmlQueryContext context = mgr_.createQueryContext();
                   //Default namespace declaration does not work yet - this will work in the next release of BDB XML
                   //Until then we have to remove the namespace declaration from the reference.xml root element
                   //When this becomes available we can add the namespace declaration and uncomment the following line
                   //context.setNamespace("", defaultNS);
                   XmlResults results = mgr_.query(myQuery, context);
                   //Get the result set
                   queryOutput = new String[results.size()];
                   XmlValue value = results.next();
                   while (value != null)
                        queryOutput[counter] = value.asString().replaceAll("\\n", "").replaceAll(" "," ");
                        System.out.println(queryOutput[counter]);
                        counter ++;
                        value = results.next();
              catch (Exception e) {
                   //Exception Handling code here
              return queryOutput;
    Now to explain what is happening:
    When I open an xml document in xmlmind, it displays the document according to a prespecified CSS sheet. Sometimes the CSS rules alone are not sufficient to achieve the necessary effect/functionality, so the API allows you to write your own class, which contains methods to do what you want. As soon as the xml document is displayed, the CSS extension class gets instantiated.
    Here is my extension class (called StyleSheetExtension). It contains a method called getKeywords. This method can then be invoked from within the CSS sheet, and is used to replace the keyword ID codes in the xml document with their corresponding keyword names - stored in an xml reference look-up document...
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs.trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs[i].trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    This instance (and consequently the newly created env and container objects) stay alive until the document is closed.
    The xmlmind API also allows you to specify custom classes that will return a component that can be embedded in the stylesheet. (My class returns a JButton which - when clicked - brings up a dialog box which allows the user to specify /modify/addnew keywords to the selected text). As soon as the button is pressed I create a new env and container instance, for the duration of the pop-up window (since I have no way to pass the reference to the existing environment created by the StyleSheetExtension class.
    Here's the class defn: (Here goes!) The env and container stuff is at the start of the nested-nested class called KpForm.
    package org.isha.archives.xmlmind;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.BadLocationException;
    import javax.swing.event.*;
    import javax.swing.text.DocumentFilter.FilterBypass;
    import java.util.*;
    import java.util.regex.*;
    import java.lang.*;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.Element;
    import com.xmlmind.xmledit.edit.*;
    import com.xmlmind.xmledit.stylesheet.*;
    import com.xmlmind.xmledit.styledgadget.*;
    import com.xmlmind.xmledit.styledview.*;
    import com.xmlmind.xmledit.doc.*;
    import java.util.logging.*;
    import org.isha.archives.bdbxml.DbEnv;
    import org.isha.archives.bdbxml.DbContainer;
    public class OpenKeywordPicker implements ComponentFactory {
    public Component createComponent(Element element,
    Style style, StyleValue[] parameters,
    StyledViewFactory viewFactory,
    boolean[] stretch){
    KeywordEdit topic = new KeywordEdit();
    return topic;
         private class KeywordEdit extends JButton {
              //private Element element;
              public KeywordEdit()
                   super.setText("Edit");
                   super.addMouseListener(new java.awt.event.MouseAdapter() {
                                  public void mouseClicked(java.awt.event.MouseEvent evt) {
                                       myJButtonMouseClicked(evt);
              private void myJButtonMouseClicked(java.awt.event.MouseEvent evt) {
                        KpForm myForm = new KpForm();
                        myForm.setVisible(true);
    private class KpForm extends javax.swing.JFrame {
         // Variables declaration - do not modify
         private javax.swing.JButton jButton1;
         private javax.swing.JButton jButton2;
         private javax.swing.JButton jButton3;
         private javax.swing.JButton jButton4;
         private javax.swing.JButton jButton5;
         private javax.swing.JButton jButton6;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JList jList1;
         private javax.swing.JList jList2;
         private javax.swing.JList jList3;
         private javax.swing.JScrollPane jScrollPane1;
         private javax.swing.JScrollPane jScrollPane2;
         private javax.swing.JScrollPane jScrollPane3;
         private javax.swing.JScrollPane jScrollPane4;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JTextField jTextField1;
         private DefaultListModel model_1 = new DefaultListModel();
              private DefaultListModel model_2 = new DefaultListModel();
              private DefaultListModel model_3 = new DefaultListModel();
              private javax.swing.JOptionPane jOptionPane1;
              //private KeywordFilter filter_1 = new KeywordFilter();
              //BDB variables
              private DbEnv myDbEnv = null;
              private File envDir = new File("C:\\BerkeleyDB");
              private DbContainer myDbContainer = null;
              private String containerFileName = "reference.dbxml";
              private XmlContainerConfig containerCfg = null;
              private Logger logger = Logger.getLogger("OpenKeywordPicker.KeywordEdit.KpForm");
              private Handler fh = null;
              private java.util.logging.Formatter sf = null;
    // End of variables declaration
         /** Creates new form kpForm */
         public KpForm() {
                   super();
         initComponents();
         customInit();
              private void customInit(){
                        //Set up simple logging system
                   try {
                        fh = new FileHandler("%t/_keywordPicker.log");
                        sf = new SimpleFormatter();
                        fh.setFormatter(sf);
                        logger.addHandler(fh);
                        logger.setLevel(Level.ALL);
                        logger.info("Starting Custom initialization");
                   } catch (Exception e) {System.out.println("CustomErr: " + e.getMessage());
                              //Exception Handling code
                        //Create custom BDB Environment and Container Objects
                        try {
                             logger.info("0");
                             myDbEnv = new DbEnv(envDir);
                             logger.info("1");
                             containerCfg = new XmlContainerConfig();
                             logger.info("2");
                             myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                             logger.info("3");
                             myDbContainer.open();
                        } catch (Throwable t) {
                             logger.severe("Problem with Env or Container new thing - Component: "+ t.getMessage());
              String[] dbIDKeywords;
              jList1.setModel(model_1);
              jList2.setModel(model_2);
              jList3.setModel(model_3);
              dbIDKeywords = getKeywordsFromDB();
              int i=0;
              for(i=0; i < dbIDKeywords.length; i+=2){
              model_1.addElement(new keywordOb(dbIDKeywords[i], dbIDKeywords[i+1]));
              jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              //Setup Document Filter for TextField component
              AbstractDocument doc;
              doc = (AbstractDocument)(jTextField1.getDocument());
              doc.setDocumentFilter(filter_1);
              //Setup Document Listener for TextField component
              jTextField1.getDocument().addDocumentListener(new DocumentListener(){
              public void insertUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & val.trim() != ""){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void removeUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & !val.trim().equals("")){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void changedUpdate(DocumentEvent e) {
              //Plain text components do not fire these events
              private String[] getKeywordsFromDB(){
              String[] k = null;
              String flwor = "";
              flwor = "for $i in collection('" + containerFileName + "') /reference/keywords/keyword \n";
              flwor += "let $id := $i/@id/text() \n";
              flwor += "let $val := $i/@value/text() \n";
              flwor += "order by $val ascending \n";
              flwor += "return ($id, $val)";
              return k = myDbContainer.runQuery(flwor);
              private class keywordOb implements Comparable{
              private String id;
              private String value;
              public keywordOb(String id, String value){
              this.id = id;
              this.value = value;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public int compareTo(Object o){
                                  int result = (((keywordOb)this).toString()).compareTo(((keywordOb)o).toString());
                                  return result;
              private class questionOb implements Comparable{
              private String id;
              private String value;
              private String[] keywordRefs;
              public questionOb(String id, String value, String[] keywordRefs){
              this.id = id;
              this.value = value;
              this.keywordRefs = keywordRefs;
              public questionOb(){
              this.id = "";
              this.value = "";
              this.keywordRefs = null;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public String[] getKeywordRefs(){
              return keywordRefs;
              public void setId(String id){
              this.id = id;
              public void setValue(String value){
              this.value = value;
              public void setKeywordRefs(String[] keywords){
              this.keywordRefs = keywordRefs;
              public int compareTo(Object o){
                             int result = (((questionOb)this).toString()).compareTo(((questionOb)o).toString());
                             return result;
              //Add New Keyword to xml reference File
              private void addNewKeyword(String k){
              String keyword = k;
              int len = jTextField1.getDocument().getLength();
              //Tidy up string
              keyword = keyword.trim();
              keyword = keyword.replaceAll("\\s+"," ");
              keyword = capitalizeWords(keyword);
              String flwor = "";
              //Check that the keyword value doesn't already exist
              flwor = "let $i := collection('" + containerFileName + "')/reference/keywords/keyword[@value = '" + keyword + "'] \n";
              flwor += "return \n";
              flwor += "if(count($i)) then fn:true() \n";
              flwor += "else fn:false() \n";
              boolean keywordExists = bDbConnection.runBooleanQuery(flwor);
              if (keywordExists){
              jOptionPane1.showMessageDialog(new Frame(),
              "The keyword '" + keyword + "' already exists", "Message", jOptionPane1.INFORMATION_MESSAGE);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              //Terminate method execution
              return;
              //Need to get ID of last keyword
              flwor = "for $i in collection('" + containerFileName + "')/reference/keywords/keyword/@id/text() \n";
              flwor += "order by $i descending \n";
              flwor += "return $i[fn:last()]";
              String[] lastIDArray = new String[1];
              lastIDArray = bDbConnection.runQuery(flwor);
              String lastIDStr = lastIDArray[0];
              //create incremented ID value
              //Note: XML ID attributes must start with a letter - that's why we need to do all this nonsense!
              int lastIDNum = new Integer(lastIDStr.substring(1));
              int nextIDNum = ++lastIDNum;
              String nextIDStr = String.format("%04d", nextIDNum);
              nextIDStr = "K" + nextIDStr;
              //OK Finally - actually add the keyword to the xml reference file
              //use BDB API for updating - since XQuery does not allow
              try
              XmlQueryContext qc = myManager.createQueryContext();
              XmlUpdateContext uc = myManager.createUpdateContext();
              XmlModify mod = myManager.createModify();
              XmlQueryExpression select = myManager.prepare("/reference/keywords", qc);
              mod.addAppendStep(select, XmlModify.Element, "keyword", "");
              select = myManager.prepare("/reference/keywords/keyword[fn:last()]", qc);
              mod.addAppendStep(select, XmlModify.Attribute, "id", nextIDStr);
              mod.addAppendStep(select, XmlModify.Attribute, "value", keyword);
              XmlDocument updateDoc = myContainer.getDocument(docName);
              XmlValue docValue = new XmlValue(updateDoc);
              mod.execute(docValue, qc, uc);
              catch(Exception e){
              System.out.println("Error adding keyword: " + e.getMessage());
              //Add the new keyword to the list of selected keywords
              model_2.addElement(keyword);
              sortModelElements(model_2);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              private questionOb[] getQuestionsFromDB(keywordOb[] keywordIDs){
              questionOb[] qobs = null;
              String seq = "";
              String flwor = "";
              int num = 0;
              seq = keywordObsToSeq(keywordIDs);
              flwor = "for $i in " + seq + "\n";
              flwor += "let $q := collection('" + containerFileName + "') /reference/questions/question[./keywordRef/@idref/text() = $i] \n";
              flwor += "return $q";
              try
              XmlQueryContext context = myManager.createQueryContext();
              context.setEvaluationType(XmlQueryContext.Eager);
              context.setReturnType(XmlQueryContext.DeadValues);
              XmlResults results = myManager.query(flwor, context);
              // Report Query Info
              String message = "Found ";
              message += results.size() + " entries for query: '";
              message += flwor + "'\n";
              System.out.println(message);
              int numQuestions;
              numQuestions = results.size();
              qobs = new questionOb[numQuestions];
              String[] keyRefs = new String[1];
              String[] keyRefs2 = new String[1];
              XmlResults atts, atts2 = null;
              XmlValue keyRefElem, keyRefAtt = null;
              int i;
              for(i=0; i < numQuestions; i++){
              XmlValue val = results.next();
              atts = val.getAttributes();
              String id = atts.next().getNodeValue();
              String value = atts.next().getNodeValue();
              keyRefElem = val.getFirstChild();
              int j=0;
              while (!keyRefElem.isType(XmlValue.NONE)){
              if(keyRefElem.getType() == XmlValue.TEXT_NODE){
              keyRefElem = keyRefElem.getNextSibling();
              if(keyRefElem.isType(XmlValue.NONE)){
              break;
              System.out.println("1");
              atts2 = keyRefElem.getAttributes();
              System.out.println("2");
              keyRefs[j] = atts2.next().getNodeValue();
              System.out.println("3" + keyRefs[j]);
              System.arraycopy(keyRefs,0,keyRefs2,0,j+1);
              System.out.println("4");
              keyRefs = new String[j+2];
              System.out.println("5");
              System.arraycopy(keyRefs2,0,keyRefs,0,j+1);
              System.out.println("6");
              keyRefs2 = new String[j+2];
              System.out.println("7");
              keyRefElem = keyRefElem.getNextSibling();
              System.out.println("8");
              j++;
              System.out.println(keyRefs[0]+keyRefs[1]);
              //Create new Question Object with retrieved values
              System.out.println("bef");
              questionOb qo = new questionOb(id, value, keyRefs);
              System.out.println("aft");
              qobs[i] = qo;
                        catch(Exception e)
              System.out.println("XML Exception is "+ e.getMessage());
              return qobs;
              private void sortModelElements(DefaultListModel model){
              //Getting the size of the model
              int size = model.getSize();
              //Creating the keyword object based on the size of the model
              keywordOb[] word = new keywordOb[size];
              int i=0;
              //keywordOb j;
              for(i=0; i < size; i++){
              word[i] = (keywordOb) model.getElementAt(i);
              Arrays.sort(word);
              for(i=0; i < size; i++){
              //model.setElementAt(word[i], i);
              model.set(i,word[i]);
              public void messageBox(String message)
              jOptionPane1.showMessageDialog(new Frame(), message , "Message", jOptionPane1.INFORMATION_MESSAGE);
              class KeywordFilter extends DocumentFilter {
              public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.insertString(offset, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.replace(offset, length, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              private boolean noFunnyChars(String s){
              String regex = "[A-Za-z\\s]+";
              boolean b = Pattern.matches(regex, s);
              return b;
              private String capitalizeWords(String s){
              String s2;
              char[] c = s.toCharArray();
              int i = 0;
              c[0] = Character.toUpperCase(c[0]);
              for(i=0; i < c.length; i++){
              if (!Character.isLetter(c[i])){
              c[i+1] = Character.toUpperCase(c[i+1]);
              s2 = String.valueOf(c);
              return s2;
              private String keywordObsToSeq(keywordOb[] a) {
              StringBuffer result = new StringBuffer();
              String resultStr = "";
              result.append("('" + a[0].getId() + "', ");
              for (int i=1; i < a.length; i++) {
              result.append("'" + a[i].getId() + "', ");
              resultStr = result.toString();
              resultStr = resultStr.trim();
              resultStr = resultStr.substring(0,resultStr.length()-1) + ")";
              return resultStr;
         // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
              private void initComponents() {
              jScrollPane1 = new javax.swing.JScrollPane();
              jList1 = new javax.swing.JList();
              jScrollPane2 = new javax.swing.JScrollPane();
              jList2 = new javax.swing.JList();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              jLabel3 = new javax.swing.JLabel();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jButton2 = new javax.swing.JButton();
              jButton3 = new javax.swing.JButton();
              jScrollPane3 = new javax.swing.JScrollPane();
              jList3 = new javax.swing.JList();
              jLabel4 = new javax.swing.JLabel();
              jButton4 = new javax.swing.JButton();
              jButton5 = new javax.swing.JButton();
              jLabel5 = new javax.swing.JLabel();
              jScrollPane4 = new javax.swing.JScrollPane();
              jTextArea1 = new javax.swing.JTextArea();
              jButton6 = new javax.swing.JButton();
              setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
              jList1.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList1MouseClicked(evt);
              jScrollPane1.setViewportView(jList1);
              jList2.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList2MouseClicked(evt);
              jScrollPane2.setViewportView(jList2);
              jLabel1.setText("Available Keywords");
              jLabel2.setText("Selected Keywords");
              jLabel3.setText("Add New Keyword");
              jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12));
              jTextField1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jTextField1ActionPerformed(evt);
              jButton1.setText("Add Keyword");
              jButton1.setEnabled(false);
              jButton1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton1ActionPerformed(evt);
              jButton2.setText("Modify Keyword");
              jButton3.setText("Remove Keyword");
              jList3.setModel(new javax.swing.AbstractListModel() {
              String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
              public int getSize() { return strings.length; }
              public Object getElementAt(int i) { return strings[i]; }
              jScrollPane3.setViewportView(jList3);
              jLabel4.setText("Questions");
              jButton4.setText("OK");
              jButton4.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton4ActionPerformed(evt);
              jButton5.setText("Cancel");
              jLabel5.setText("Add New Question");
              jTextArea1.setColumns(20);
              jTextArea1.setRows(2);
              jScrollPane4.setViewportView(jTextArea1);
              jButton6.setText("Add Question");
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
              .addContainerGap(488, Short.MAX_VALUE)
              .addComponent(jButton5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(29, 29, 29))
              .addGroup(layout.createSequentialGroup()
              .addGap(38, 38, 38)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jButton6)
              .addContainerGap())
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
              .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(jLabel5)
              .addComponent(jLabel4)
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel2)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(32, 32, 32)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel3)
              .addComponent(jButton1)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING))))
              .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)))
              .addContainerGap(58, Short.MAX_VALUE))))
              layout.setVerticalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addGap(24, 24, 24)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel3)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton3))))
              .addGap(29, 29, 29)
              .addComponent(jLabel4)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(20, 20, 20)
              .addComponent(jLabel5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton6)
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jButton4)
              .addComponent(jButton5))
              .addGap(21, 21, 21))
              pack();
    }// </editor-fold>
              //Event handlers
              private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        try {
                             myDbContainer.close();
                             myDbEnv.cleanup();
                        } catch (Exception e) {
                             logger.info("Could not close container/or env - Component");
                        super.setVisible(false);
                        super.dispose();
                   private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        String val;
                        val = jTextField1.getText();
                        if(val != null & val.trim() != "" & noFunnyChars(val) ){
                             jButton1.setEnabled(true);
                        else {
                             jButton1.setEnabled(false);
                   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                   // Add new keyword to the xml reference file
                        //addNewKeyword(jTextField1.getText());
                   private void jList2MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                        if(evt.getClickCount() == 2) {
                             keywordOb k = (keywordOb)jList2.getSelectedValue();
                             model_2.removeElement(k);
                             model_1.addElement(k);
                             sortModelElements(model_1);
                             questionOb q = null;
                             //Remove associated questions from listbox
                             int i,j;
                             for(i=0; i < model_3.size(); i++){
                                  q = (questionOb)model_3.getElementAt(i);
                                  for(j=0; j < model_3.size(); j++){
                                       if (q.getKeywordRefs()[j].equals(k.getId())){
                                            model_3.removeElement(q);
                                            i--;
                                            break;
                   private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                   if(evt.getClickCount() == 2) {
                             //Getting properties of the selecteditem item in jList1.
                        keywordOb k = (keywordOb)jList1.getSelectedValue();
                        //Removing the element from jList1
                        model_1.removeElement(k);
                        //Adding the element to jList2
                        model_2.addElement(k);
                        sortModelElements(model_2);
                        //Load the questions for the selected keywords
                        int len;
                        len = model_2.getSize();
                        keywordOb[] dbQuestionsOb = new keywordOb[5];
                        keywordOb[] selectedKeywordsOb = new keywordOb[len];
                        String[] selectedKeywordIDs = new String[len];
                        int i;
                        for(i=0; i < len; i++) {
                             selectedKeywordsOb[i] = (keywordOb)model_2.getElementAt(i);
                             selectedKeywordIDs[i] = selectedKeywordsOb[i].getId();
                        questionOb[] questionsOb = getQuestionsFromDB(selectedKeywordsOb);
                        model_3.removeAllElements();
                        for(i=0; i < questionsOb.length; i++){
                             model_3.addElement(questionsOb[i]);
                        // sortModelElements(model_3);
    I think thats too much code for one post!

Maybe you are looking for

  • Send PO to Vendor by EDI

    Dear All, We have to implement a scenario wherein we can send PO to Vendor by EDI. What are the system prerequisites for this at our end & vendor end?Does the vendor require SAP for this? Also what are configurations to be done & what are the transac

  • Does the Protection Plant warranty expire if it is not registered?

    I purchased the Protection Plan for the iPhone4 when i bought the phone, over 16 months ago. I didn't realise that the warranty needs to be registered online with the phone. And the warranty can only be purchased within one year of purchasing the pho

  • Mountain Lion damaged my hard disk

    I tried installing ML in my iMac running Snow Leopard, and I also got the hard disk damage problem. It seems some people that were running Lion have been able to run de Disk Utility booting from the Recover Partition, which is not featured in Snow Le

  • Aiport Utility "Not Responding"

    Hi All, I've just set up my Airport Extreme under Windows Vista 64-bit. I have installed the Airport Utility. As soon as I start the Airport Utility program, it says "discovering Apple Wireless Devies".... then it basically hangs and goes into a 'Not

  • Erased free disk space what does it do thats diff from normal trash?

    Hi guys what does erase fre disc do that is diff from normal trash deletion? thanks so much. CarolineUK Black MacBook LION, MBP Snow Leopard, iBook G4 Tiger, Quicksilver PPC Tiger