Setting up LAF

I'm trying to change how my java app looks so i've gone to www.javootoo.com and downloaded a theme. from that i've got a .jar file. Now being a noobie I don't know how to set it up.
I setup a CLASPATH environment variable but then I can't compile my java app.
Can anyone tell me how I can setup my system to use the LAF files?

You can set LNF in two ways, (1) before any components are realized, and (2) after they are realized.
(1)
public static void main(String args[])
   //set the LNF before any component is created and realized
   try
      javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
   catch (Exception e) { }
   // new MyApplicationThatExtendsSomeTopLevelContainer();
}(2)
try
   UIManager.setLookAndFeel(the_path_to_your_LNF);
   SwingUtilities.updateComponentTreeUI(this);
catch (Exception exc)
   System.out.println("Failure in changing the LNF.");
}

Similar Messages

  • Is it possible to set a laf to only one component in the application?

    I'm developing a GUI and wanted to know if it is possible to set a particular laf to one of the guis components, thanks a lot.

    I believe that the LAF of a component is determined by the current LAF when the component is created. So I think you can create and display you GUI normally. Then switch to your other LAF to create your component and then switch back to the default..

  • Setting kunstoff laf

    I'm sorry for this stupid question. Where should I put jar file kunstoff.jar if I want to my code work...
    try {
                UIManager.setLookAndFeel(new com.incors.plaf.kunststoff.KunststoffLookAndFeel());
                System.out.println("Success...");
                SwingUtilities.updateComponentTreeUI(frame);
                frame.pack();
                frame.setVisible(true);
            catch(UnsupportedLookAndFeelException uex){
                uex.printStackTrace();
            }\MyApplication.class

    Put it in your classpath.

  • Using different LAFs in different applets in the same browser

    Hi All!
    I created my own LAF, which I want to use in my own applets. However, if I set the LAF through
    UIManager.setLookAndFeel(myLAF);
    it affects all applets in my browser. That is, if I have other applets on the same web page, or open other applets in other browser windows WITHOUT closing my applet window, they all use myLAF.
    To me it looks like all applets run in the same VM and therefore share the same static variable storing the current LAF. This is different in applications, because they all run in a separate VM.
    Is there a way to make each applet use a different LAF, while still running in the same browser or even on the same Web page?
    Thanks in advance,
    Viktor

    Can anyone say something on this topic? I'm really frustrated!
    I've been struggling to solve this problem with no luck. All I found is that it only happens on MS VM. It's Ok with the Sun VM.
    Does anyone know how to solve it on MS VM?

  • Interesting behavior with XP LaF

    Hello,
    I am seeing an interesting behaviour with the 1.4.2 Look an Feel.
    I am developing on XP Pro and am invoking
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\
    before showing a JFrame.
    But, the LaF is defaulting to Metal. The frame contains a few splitpanes and panels, nothing fancy. However, if I create a test frame with one of my panels and set the LaF to the System LaF, it uses the XP LaF just fine.
    Anyone know why this might be happening? Am I missing something blindly obvious?
    Thanks for your 2 cents....
    --Bill                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    hey,
    The reason why is because for Sun on Windows Metal is the default look and feel. You need to manualy set it. I use the following code:
    * LookAndFeel.java
    public class LookAndFeel {
        public static final String MAC_CLASS = "com.sun.java.swing.plaf.mac.MacLookAndFeel";
        public static final String METAL_CLASS = "javax.swing.plaf.metal.MetalLookAndFeel";
        public static final String MOTIF_CLASS = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
        public static final String WINDOWS_CLASS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
        public static final String GTK_CLASS = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
        public static final String KUNSTSTOFF_CLASS = "com.incors.plaf.kunststoff.KunststoffLookAndFeel";
        public static boolean isAvailableLookAndFeel(String laf) {
            boolean isSupported = false;
            try {
                Class lnfClass = Class.forName(laf);
                javax.swing.LookAndFeel newLAF = (javax.swing.LookAndFeel)(lnfClass.newInstance());
                isSupported = newLAF.isSupportedLookAndFeel();
            } catch(java.lang.Exception e) {
                // If ANYTHING weird happens, return false
                System.out.println(e.toString());
                isSupported = false;
            if(laf.equals(MOTIF_CLASS)) {
                // problem with the desktop pane using motif, get a null pointer
                // appears to work fine with all other LNF's but is a low priority
                // to resolve.
                isSupported = false;
            return isSupported;
        public static boolean updateLookAndFeel(String currentLookAndFeel, java.awt.Component parent) {
         try {
             javax.swing.UIManager.setLookAndFeel(currentLookAndFeel);
                if(parent != null) {
                    javax.swing.SwingUtilities.updateComponentTreeUI(parent);
         } catch(Exception ex) {
             System.out.println(ex);
                return false;
            return true;
    }To set it you just need to pass the appropriate info. For example:
    public class Test extends javax.swing.JFrame {
        private javax.swing.JButton printButton;
        public Test() {
            LookAndFeel.updateLookAndFeel(LookAndFeel.WINDOWS_CLASS, this);
            getContentPane().setLayout(new java.awt.FlowLayout());
            setTitle("Test");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    System.exit(0);
            testButton = new javax.swing.JButton();
            testButton.setText("Test");
            getContentPane().add(testButton);
            pack();
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setSize(new java.awt.Dimension(562, 386));
            setLocation((screenSize.width-562)/2,(screenSize.height-386)/2);
        public static void main(String args[]) {
            new Test().show();
    }I have removed some code, but the above should work fine. Btw, I store the selected LnF in the registry and just load the info in at runtime. As its just a string you can store it however you wish.
    James.

  • DataOutputStream appears to be buffering and then overflowing?? 10 Duke Pts

    Hi folks,
    Hope someone can help. I am trying to put together a file upload applet (yes I know....security this and signing that and so on...). It "works" (erm...kind of) using the JFileChooser and JProgressMonitorInputStream to carry out an HTTP post to a server side CGI script.
    I have it "working" in so far as with small files it does actually complete although usually some time after the progress bar shows it completed.
    With larger files though the progress bar still rushes through too quickly but then it crashes with an OutOfMemory exception (at around 40MB).
    It looks to me almost as if the DataOutputStream is buffering and returning (not blocking) before the data has actually been sent. I have tried including a .flush() after the write but it made no difference.
    Why does the DataOutputStream return from write before the data has actually been sent?
    If anyone can help in any way it will be massively appreciated! I have included code below its not neat since I have been bashing it around trying to make it work.
    What I am looking for is to have the progress bar show the progress as the contents of the file is uploaded to the server via the HTTP post.
    package videoupload;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class VideoUpload extends JApplet implements ActionListener
      class HTTPPoster extends SwingWorker {
        String sBoundary="2db8c22f75474a58cd13fa2d3425017015d392ce";
        URL u;
        public URLConnection postConnect(URL urlTarget)
          URLConnection c = null;
          try {
            c = urlTarget.openConnection();
            // post multipart data
            c.setDoOutput(true);
            c.setDoInput(true);
            c.setUseCaches(false);
          } catch (Exception ex)
             ex.printStackTrace();
          return c;
        public void postHeaders(URLConnection pCon)
          // set some request headers
          pCon.setRequestProperty("Connection", "Keep-Alive");
          pCon.setRequestProperty("HTTP_REFERER", "http://www.<THEWEBSITE>.com/");
          pCon.setRequestProperty("Content-Type",
                                  "multipart/form-data; boundary="+sBoundary);
        public DataOutputStream getFormBodyOutput(URLConnection pCon)
          DataOutputStream dos = null;
          try
            dos = new DataOutputStream(pCon.getOutputStream());
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
          return dos;
        public void sendBoundary(DataOutputStream dos)
          try
            dos.writeBytes("--"+sBoundary+"\r\n");
          } catch (Exception ex)
            ex.printStackTrace();
        public void postFile(DataOutputStream dos, String name, File f)
          try
            dos.writeBytes(
                "Content-Disposition: form-data; name=\"" + name +
                "\"; filename=\"" + f.getName() +
                "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            System.out.println("Opening - "+f.getAbsoluteFile());
            FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                content, f.getName(), fis);
            ProgressMonitor pm = pmis.getProgressMonitor();
            pm.setMillisToDecideToPopup(500);
            byte[] bt = new byte[1024];
            int cnt = pmis.read(bt);
            while (cnt == bt.length)
              dos.write(bt, 0, cnt);
              cnt = pmis.read(bt);
            // send the last bit to the server
            dos.write(bt, 0, cnt);
            // now close the file and let the web server know this is the end of this form part
            pmis.close();
            fis.close();
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
        public void endPost(DataOutputStream dos)
          try
            dos.writeBytes(
                "\r\n--" + sBoundary + "--\r\n\r\n");
            dos.flush();
            dos.close();
          } catch (Exception ex)
            ex.printStackTrace();
        public void getResponse(URLConnection pCon)
          try
            DataInputStream dis =
                new DataInputStream(
                    new BufferedInputStream(pCon.getInputStream()));
            String sIn = dis.readLine();
            while (sIn != null)
              if (sIn != null)
                System.out.println(sIn);
              sIn = dis.readLine();
          } catch (Exception ex)
            ex.printStackTrace();
        public Object construct()
          try
              u = new URL("http://www.<THEWEBSITE>.com/cgi-bin/upload.cgi");
              // System.out's here for debugging only...
              System.out.println("Connect");
              URLConnection pCon = postConnect(u);
              System.out.println("Send headers");
              postHeaders(pCon);
              System.out.println("Begin body");
              DataOutputStream dos = getFormBodyOutput(pCon);
              System.out.println("Send file");
              this.postFile(dos, "file", f);
              System.out.println("End body");
              endPost(dos);
              System.out.println("Get response");
              getResponse(pCon);
              System.out.println("Done");
            catch (Exception ex)
              ex.printStackTrace();
          return null;
      Container content;
      File f;
      protected boolean isStandalone = false;
      protected BorderLayout borderLayout1 = new BorderLayout();
      String uploadPath;
      //Get a parameter value
      public String getParameter(String key, String def)
        return isStandalone ? System.getProperty(key, def) :
            (getParameter(key) != null ? getParameter(key) : def);
      //Construct the applet
      public VideoUpload()
      //Initialize the applet
      public void init()
        try
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e)
          System.err.println("Error setting native LAF: " + e);
        content = getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        // Come back to this later
        JTextField txtFileName = new JTextField();
        txtFileName.addActionListener(this);
        content.add(txtFileName);
        JButton btnUpload = new JButton("Upload");
        btnUpload.setMnemonic('u');
        btnUpload.addActionListener(this);
        content.add(btnUpload);
        //Create a file chooser
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(content);
        f=fc.getSelectedFile();
        try
          uploadPath = this.getParameter("uploadPath", "/");
        catch (Exception e)
          e.printStackTrace();
      public void actionPerformed(ActionEvent e){
        HTTPPoster worker = new HTTPPoster();
        worker.start();
      //Start the applet
      public void start()
      //Stop the applet
      public void stop()
      //Destroy the applet
      public void destroy()
      //Get Applet information
      public String getAppletInfo()
        return "Applet Information";
      //Get parameter info
      public String[][] getParameterInfo()
        java.lang.String[][] pinfo =
            {"uploadPath", "String", ""},
        return pinfo;
      //Main method
      public static void main(String[] args)
        VideoUpload applet = new VideoUpload();
        applet.isStandalone = true;
        Frame frame;
        frame = new Frame();
        frame.setTitle("Applet Frame");
        frame.add(applet, BorderLayout.CENTER);
        applet.init();
        applet.start();
        frame.setSize(400, 320);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation( (d.width - frame.getSize().width) / 2,
                          (d.height - frame.getSize().height) / 2);
        frame.setVisible(true);
    }

    Well after much ploughing through internet I have found much to my dismay that URLConnection is not as great as it may appear as it does buffer all output prior to sending.
    This is fine for everything but file transfers, especially large ones as memory can be an issue.
    Answered own question, doh!

  • Jbutton is not showing the on down behaviour in JApplet.

    Hi All,
    When I am opening the applet with appletviewer it showing "on down" behaviour on button when mouse click happend. It is not happening in the same way when I opend the applet in the browser. Here I am giving the small code to test in your environment.
    =================TestApplet.htm==========
    <html>
    <applet code = "TestApplet.class" height="345" width="600">
    <PARAM name ="code" value = "TestApplet.class">
    <PARAM name ="codebase" value = "D:/checkout">
    </applet>
    </html>
    =================
    Applet code starts from here:
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    public class TestApplet extends JApplet
    JRadioButton RadioTop = new JRadioButton();
    JRadioButton RadioBtm = new JRadioButton();
    JButton BtnGo = new JButton();
    public void init()
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
    System.out.println("Error setting native LAF: " + e);
    getContentPane().setLayout(null);
    getContentPane().setBackground(java.awt.Color.white);
    setSize(676,400); //576,397
    RadioTop.setText("Top");
    RadioTop.setActionCommand("Top");
    RadioTop.setBackground(java.awt.Color.white);
    RadioTop.setForeground(new java.awt.Color(0,0,102));
    RadioTop.setFont(new Font("Dialog", Font.BOLD, 12));
    RadioTop.setBounds(60,19,72,24); //84,19,72,24
    RadioTop.setBounds(new Rectangle(55, 6, 50, 20));//43
    RadioBtm.setText("Bottom");
    RadioBtm.setBackground(java.awt.Color.white);
    RadioBtm.setForeground(new java.awt.Color(0,0,102));
    RadioBtm.setFont(new Font("Dialog", Font.BOLD, 12));
    RadioBtm.setBounds(60,43,72,24);
    RadioBtm.setBounds(new Rectangle(54, 25, 72, 24));
    ButtonGroup groupTopBtm = new ButtonGroup();
    groupTopBtm.add(RadioTop);
    groupTopBtm.add(RadioBtm);
    BtnGo.setText("Go >>");
    BtnGo.setActionCommand("Go>>");
    BtnGo.setFont(new Font("Dialog", Font.BOLD, 12));
    BtnGo.setBounds(468,24,68,23);
    BtnGo.setBounds(new Rectangle(300, 5, 68, 23));
    BtnGo.setBackground(new java.awt.Color(51,102,153));//00,66,115
    BtnGo.setForeground(java.awt.Color.white);
    BtnGo.setBorder(BorderFactory.createBevelBorder(0,java.awt.Color.white,java.awt.Color.gray));
    this.getContentPane().add(RadioTop);
    this.getContentPane().add(RadioBtm);
    this.getContentPane().add(BtnGo);
    ******************TestApplet.java******
    Copy the applet,compile and invoke the applet with the above .htm after changing the code base and see is there any "on down" behaviour when you press the go button.
    Run the same applet using the appletviwer and test the same thing to notice difference.
    Please let me know how to enable the "on down" behaviour on buttons without adding much code.
    Thanks in advance.

    I am also suffering from this. It is happening with every account (four) on the computer. I can't get the CD out, either. I've tried re-setting the Finder prefs re: CDs and DVDs, and the Sys Prefs re: what to do with a blank disk. The disk does not come out upon restart and holding the mouse button.
    This is relatively recent, past four months or so, and it seems to be it's been since I installed 10.5.7.
    Any ideas above and beyond what is in this thread? I'd love it to be a software problem and not have to take this thing in for replacing a drive.
    Thanks tons,
    Carlos Alden

  • Webutil Open File Dialog look and feel

    Webutil all revisions?, Windows NT 4.0/XP.
    The open/save file dialog boxes in webutil are always the same style (Oracle/Motif?) when either the LookandFeel is set to Generic/Windows or Oracle/Motif.
    Is there anyway to change it to always look like Windows Look and Feel?

    Hello,
    One possible way would be to write your own Java Bean component that call the standard openfile dialog, then set the LAF yourself:
       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
       ...but, I know, this represents some extra work.
    Francois

  • Netbeans and setDefaultLookAndFeelDecorated

    I have recently started using the Netbeans 5.0 IDE to make my GUI's because its easier than typing it all myself...
    The problem I am having is when I create a new JFrame and set it visible it doesn't look like my original windows. i have tried using the setDefaultLookAndFeelDecorated method but to no avail.
    Any one know how I can change the look and feel withing netbeans?
    Thanks

    because its easier than typing it all myself...apparently its not easier if Netbeans is doing something strange to your GUI.
    Any one know how I can change the look and feel withing netbeans?The LAF is not controlled by the IDE, but by Java code. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html]How to Set the LAF.

  • JTree expand programatically is not working

    jTree1.fireTreeExpanded(curTreePath);
    expandAll(jTree1, curTreePath, true);
    jTree1.expandPath(curTreePath);
    jTree1.scrollPathToVisible(curTreePath);
    jTree1.updateUI();
    jTree1.setExpandsSelectedPaths(true);
    jTree1.expandPath(curTreePath);
    expandAll(jTree1, curTreePath, true);
    for (int i = 0; i < jTree1.getRowCount(); i++)
    jTree1.expandRow(i);
    jTree1.validate();
    jTree1.repaint();
    Any help ?

    package so;
    ToDo list
    * Log timestamp and line number of at every exception.
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    import java.util.Enumeration;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    public class SCM extends javax.swing.JFrame implements javax.swing.event.TreeExpansionListener, javax.swing.event.TreeModelListener, javax.swing.event.TreeWillExpandListener
        Connection con = null;
        java.sql.Statement stmt = null;
        ResultSet rs = null;
        PrintStream log = null;// File creation at local system, to record events, actions, errors and traces
        javax.swing.tree.TreePath curTreePath = null;
        /** Creates new form SCM */
        public SCM()
            //---------------------- Native LookandFeel Windows is expected.-------------------//
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception e)
                System.out.println("Error setting native LAF: " + e);
            //******************** Native LookandFeel Windows is expected.*******************//
            // initialising GUI containers and controls
            initComponents();
            TableCellRenderer defaultRenderer;
            defaultRenderer = jTable1.getDefaultRenderer(JLabel.class);
            jTable1.setDefaultRenderer(JLabel.class, new Label_cell(defaultRenderer));
            setState(javax.swing.JFrame.HIDE_ON_CLOSE);
            jfc.setEnabled(false);
            this.setSize(1024, 740);
            jTree1.setSize(400, this.getWidth() / 4);
            jTree1.setRootVisible(false);
            jTree1.addTreeWillExpandListener(this); // Registering jTree1 to Expand listener.
            jTree1.setCellRenderer(new TreeIconRenderer());
            try
                //-------Preparing Logger----------------//
                FileOutputStream fos = new FileOutputStream(new File(System.getProperties().getProperty("user.home") + System.getProperties().getProperty("file.separator") + "SCM-Log_" + System.currentTimeMillis()));
                log = new PrintStream(fos);
                log.println("Started Time\t\t:" + new java.util.Date().getTime());
                //*******Preparing Logger****************//
                // Initialising jTree1 with the userid and preparing the xml and loading jTree1 with xml content,
                // and expected to repeat the same while refreshing.
                //----- Rendering images for the folders and files i.e. nodes and leaves of this tree
                jTree1 = new XMLTree("215");
                //******** Rendering images for the folders and files i.e. nodes and leaves of this tree
                //Selection can only contain one path at a time, i.e. user is confined to reffere to only one node
                //or leaf at a time
                //jTree1.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.SINGLE_TREE_SELECTION);
                this.setTitle("ZIIC-ITG SCM");// Title can be changed at any time.
            catch (IOException ioe)
                ioe.printStackTrace(log);   //logging Exception.
                //This is first level action and to be decided to go further or not by exit(0);.
        public boolean prepareCon() throws ClassNotFoundException
            try
                if (con != null && !con.isClosed())
                    return true;
                else
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                    java.sql.DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                    con = java.sql.DriverManager.getConnection("jdbc:oracle:thin:@172.16.1.31:1521:soadb", "dms", "dms");
                    if (con != null && !con.isClosed())
                        return true;
            catch (java.lang.ClassNotFoundException cnfe)
                cnfe.printStackTrace(log);
            catch (SQLException se)
                se.printStackTrace(log);
            if (con != null)
                return true;
            else
                return true;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents()
            jPopupMenu1 = new javax.swing.JPopupMenu();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPane1 = new javax.swing.JScrollPane();
            try
                jTree1 = new XMLTree("215");
                jScrollPane2 = new javax.swing.JScrollPane();
                jTable1 = new javax.swing.JTable();
                menuBar = new javax.swing.JMenuBar();
                fileMenu = new javax.swing.JMenu();
                openMenuItem = new javax.swing.JMenuItem();
                saveMenuItem = new javax.swing.JMenuItem();
                saveAsMenuItem = new javax.swing.JMenuItem();
                exitMenuItem = new javax.swing.JMenuItem();
                editMenu = new javax.swing.JMenu();
                cutMenuItem = new javax.swing.JMenuItem();
                copyMenuItem = new javax.swing.JMenuItem();
                pasteMenuItem = new javax.swing.JMenuItem();
                deleteMenuItem = new javax.swing.JMenuItem();
                helpMenu = new javax.swing.JMenu();
                contentsMenuItem = new javax.swing.JMenuItem();
                aboutMenuItem = new javax.swing.JMenuItem();
                //setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            }catch(Exception e){}
            jTree1.setDoubleBuffered(true);
            jTree1.setDragEnabled(true);
            jTree1.setEditable(true);
            jTree1.setFocusTraversalPolicyProvider(true);
            jTree1.setInheritsPopupMenu(true);
            jTree1.setInvokesStopCellEditing(true);
            jTree1.setLargeModel(true);
            jTree1.setMaximumSize(new java.awt.Dimension(250, 64));
            jTree1.setPreferredSize(new java.awt.Dimension(200, 64));
            jTree1.setVerifyInputWhenFocusTarget(false);
            jTree1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTree1MouseClicked(evt);
            jTree1.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener()
                public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeCollapsed(evt);
                public void treeExpanded(javax.swing.event.TreeExpansionEvent evt)
                    jTree1TreeExpanded(evt);
            jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener()
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt)
                    jTree1ValueChanged(evt);
            jScrollPane1.setViewportView(jTree1);
            jSplitPane1.setLeftComponent(jScrollPane1);
            jScrollPane2.setAutoscrolls(true);
            jScrollPane2.setDoubleBuffered(true);
            jScrollPane2.setFocusCycleRoot(true);
            jScrollPane2.setFocusTraversalPolicyProvider(true);
            jScrollPane2.setInheritsPopupMenu(true);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][]
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String []
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jTable1.addMouseListener(new java.awt.event.MouseAdapter()
                public void mouseClicked(java.awt.event.MouseEvent evt)
                    jTable1MouseClicked(evt);
            jScrollPane2.setViewportView(jTable1);
            jSplitPane1.setRightComponent(jScrollPane2);
            fileMenu.setText("File");
            openMenuItem.setText("Open");
            fileMenu.add(openMenuItem);
            saveMenuItem.setText("Save");
            fileMenu.add(saveMenuItem);
            saveAsMenuItem.setText("Save As ...");
            fileMenu.add(saveAsMenuItem);
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new java.awt.event.ActionListener()
                public void actionPerformed(java.awt.event.ActionEvent evt)
                    exitMenuItemActionPerformed(evt);
            fileMenu.add(exitMenuItem);
            menuBar.add(fileMenu);
            editMenu.setText("Edit");
            cutMenuItem.setText("Cut");
            editMenu.add(cutMenuItem);
            copyMenuItem.setText("Copy");
            editMenu.add(copyMenuItem);
            pasteMenuItem.setText("Paste");
            editMenu.add(pasteMenuItem);
            deleteMenuItem.setText("Delete");
            editMenu.add(deleteMenuItem);
            menuBar.add(editMenu);
            helpMenu.setText("Help");
            contentsMenuItem.setText("Contents");
            helpMenu.add(contentsMenuItem);
            aboutMenuItem.setText("About");
            helpMenu.add(aboutMenuItem);
            menuBar.add(helpMenu);
            setJMenuBar(menuBar);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt)
        try
            curTreePath = evt.getPath();
            //curTreePath.getPathCount();
            //selectedNode = stPath.getPathComponent(stCount - 1);
            //TODO add your handling code here:
            if (prepareCon())
                javax.swing.tree.TreePath path = evt.getPath();
                DMETreeNode node = (DMETreeNode) path.getLastPathComponent();
                try
                    if (node != null && (node.getSerial() + "").length() > 0)
                        //stmt = con.createStatement();
                        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                        rs = stmt.executeQuery("select serial, description, file_location, status, sheet,  part, approvedby, locked, location, created_by from dms_files where owner=" + node.getSerial());
                        SCM_Tbl_model model = new SCM_Tbl_model();
                        model.setRs(rs);
                        //jTable1.setColumnModel(columnModel);
                        jTable1.setModel(model);
                        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
                        jTable1.setRowSorter(sorter);
                catch (Exception e)
                    e.printStackTrace();
            catch (ClassNotFoundException ex)
                ex.printStackTrace(log);
                Logger.getLogger(SCM.class.getName()).log(Level.SEVERE, null, ex);
        private void jTree1MouseClicked(java.awt.event.MouseEvent evt)
        // TODO add your handling code here:   
        if (evt.getButton() == evt.BUTTON3)
            jPopupMenu1.removeAll();
            javax.swing.JMenuItem expandMI = new javax.swing.JMenuItem("Expand");
            javax.swing.JMenuItem expandAllMI = new javax.swing.JMenuItem("Expand All");
            javax.swing.JMenuItem find_folderMI = new javax.swing.JMenuItem("Find Folder");
            final javax.swing.JMenuItem new_folderMI = new javax.swing.JMenuItem("New Folder");
            javax.swing.JSeparator separator1 = new javax.swing.JSeparator();
            jPopupMenu1.setSize(100, 200);
            jPopupMenu1.add(expandMI);
            jPopupMenu1.add(expandAllMI);
            jPopupMenu1.add(separator1);
            jPopupMenu1.add(find_folderMI);
            jPopupMenu1.add(new_folderMI);
            jPopupMenu1.setVisible(true);
            jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
            //expandToLast(jTree1);
            //jTree1.scrollPathToVisible(curTreePath);
            //jTree1.fireTreeExpanded(curTreePath);       
            ActionListener menuOnTree = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            if (e.getSource().equals(new_folderMI))
                                    DMETreeNode ch=new DMETreeNode("Child of "+((DMETreeNode)curTreePath.getLastPathComponent()).toString());   
                                    ((DMETreeNode) curTreePath.getLastPathComponent()).add(ch);
                                    jTree1.fireTreeExpanded(curTreePath);
                                    expandAll(jTree1, curTreePath, true);
                                    jTree1.expandPath(curTreePath);
                                    jTree1.scrollPathToVisible(curTreePath);
                                    jTree1.updateUI();
                            if (e.getActionCommand().trim().equalsIgnoreCase("Expand"))
                                jTree1.setExpandsSelectedPaths(true);
                                jTree1.expandPath(curTreePath);
                                expandAll(jTree1, curTreePath, true);
                                for (int i = 0; i < jTree1.getRowCount(); i++)
                                    jTree1.expandRow(i);
                                jTree1.validate();
                                jTree1.repaint();
                                System.out.println(((DMETreeNode) curTreePath.getLastPathComponent()).getSerial());
                                expandToLast(jTree1);
                                System.out.println(jTree1.getModel().getRoot().toString());
                                ((XMLTree)jTree1).expandAll(true);
                                expandToLast(jTree1);
            expandMI.addActionListener(menuOnTree);
            expandAllMI.addActionListener(menuOnTree);
            find_folderMI.addActionListener(menuOnTree);
            new_folderMI.addActionListener(menuOnTree);
    public void expandAll(JTree tree, boolean expand)
            TreeNode root = (TreeNode) tree.getModel().getRoot();
            // Traverse tree from root
            expandAll(tree, new TreePath(root), expand);
        private void expandAll(JTree tree, TreePath parent, boolean expand)
            // Traverse children
            TreeNode node = (TreeNode) parent.getLastPathComponent();
            if (node.getChildCount() >= 0)
                for (Enumeration e = node.children(); e.hasMoreElements();)
                    TreeNode n = (TreeNode) e.nextElement();
                    TreePath path = parent.pathByAddingChild(n);
                    //System.out.println(path.toString());
                    expandAll(tree, path, expand);
            // Expansion or collapse must be done bottom-up
            if (expand)
                tree.expandPath(parent);
            else
                tree.collapsePath(parent);
    public void expandToLast(JTree tree)
            // expand to the last leaf from the root
            DefaultMutableTreeNode root;
            root = (DefaultMutableTreeNode) tree.getModel().getRoot();
            tree.scrollPathToVisible(new TreePath(root.getLastLeaf().getPath()));
            //System.out.println(""+root.getLastLeaf().getPath().toString());
        public void expandToLast(JTree tree)
            TreeModel data = tree.getModel();
            Object node = data.getRoot();
            if (node == null)
                return;
            TreePath p = new TreePath(node);
            while (true)
                int count = data.getChildCount(node);
                if (count == 0)
                    break;
                node = data.getChild(node, count - 1);
                p = p.pathByAddingChild(node);
            tree.scrollPathToVisible(p);
        private void jTree1TreeExpanded(javax.swing.event.TreeExpansionEvent evt)
        // TODO add your handling code here:
            System.out.println("@447");
        private void jTree1TreeCollapsed(javax.swing.event.TreeExpansionEvent evt) {                                    
        // TODO add your handling code here:
        private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
            System.exit(0);
        @SuppressWarnings("static-access")
        private void jTable1MouseClicked(java.awt.event.MouseEvent evt)                                    
            // TODO add your handling code here:
            jPopupMenu1.removeAll();
            jPopupMenu1.setVisible(true);
            //Prepare Menu items based the event and the user, and the item clicked on i.e.
            javax.swing.JMenuItem menuItem = new javax.swing.JMenuItem("Add A doc", KeyEvent.VK_T);
            jPopupMenu1.add(menuItem);
            ActionListener al = new ActionListener()
                        public void actionPerformed(ActionEvent e)
                            jfc.updateUI();
                            jfc.showOpenDialog(jTable1);
                            jTable1.setValueAt(jfc.getSelectedFile().getAbsolutePath(), jTable1.getSelectedRow(), jTable1.getSelectedColumn());
                            jfc.setDialogTitle("Choose only fmx files");
                            try
                                if (jfc.getSelectedFile().getAbsolutePath() != null)
                                    java.io.File f = new java.io.File(jfc.getSelectedFile().getAbsolutePath());
                                    if (f.exists())
                                        // Start FTP process.
                                        SCM_FTP ftp = new SCM_FTP();
                                        ftp.connect("ziicsrv11", 21, "z11902", "ziicit");
                                        ftp.bin();
                                        // Change to a new working directory on the FTP server.
                                        ftp.cwd("bin");
                                        // Upload some files.
                                        log.println("FTP Start: " + System.currentTimeMillis());
                                        ftp.stor(f);
                                        ftp.disconnect();
                                        log.println("FTP Done: " + System.currentTimeMillis());
                            catch (java.io.IOException ioe)
                                log.println("File is not Found");
                                ioe.printStackTrace(log);
            menuItem.addActionListener(al);
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
            jPopupMenu1.setSize(100, 200);
            if (evt.getButton() == evt.BUTTON3)//evt.isPopupTrigger()
                jPopupMenu1.show(evt.getComponent(), evt.getX(), evt.getY());
         * @param args the command line arguments
        public static void main(String args[])
            java.awt.EventQueue.invokeLater(new Runnable()
                        public void run()
                            SCM s = new SCM();
                            s.setVisible(true);
                            //s.setState(s.HIDE_ON_CLOSE);
                            s.setAlwaysOnTop(true);
                            SystemTrayTest st = new SystemTrayTest();
                            st.setControl(s);
                            st.showFrame();
        // Variables declaration - do not modify                    
        private javax.swing.JMenuItem aboutMenuItem;
        private javax.swing.JMenuItem contentsMenuItem;
        private javax.swing.JMenuItem copyMenuItem;
        private javax.swing.JMenuItem cutMenuItem;
        private javax.swing.JMenuItem deleteMenuItem;
        private javax.swing.JMenu editMenu;
        private javax.swing.JMenuItem exitMenuItem;
        private javax.swing.JMenu fileMenu;
        private javax.swing.JMenu helpMenu;
        private javax.swing.JPopupMenu jPopupMenu1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JSplitPane jSplitPane1;
        private javax.swing.JTable jTable1;
        private javax.swing.JTree jTree1;
        private javax.swing.JMenuBar menuBar;
        private javax.swing.JMenuItem openMenuItem;
        private javax.swing.JMenuItem pasteMenuItem;
        private javax.swing.JMenuItem saveAsMenuItem;
        private javax.swing.JMenuItem saveMenuItem;
        // End of variables declaration                  
        private javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
        public void treeExpanded(TreeExpansionEvent event)
        public void treeCollapsed(TreeExpansionEvent event)
        public void treeNodesChanged(TreeModelEvent e)
        public void treeNodesInserted(TreeModelEvent e)
        public void treeNodesRemoved(TreeModelEvent e)
        public void treeStructureChanged(TreeModelEvent e)
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
    }

  • Where is the NullPointerException coming from?

    The program in question uses the following typical and generic code to set the LAF of the program to that closest to the original OS.
    //Set look and feel.
        String nativeLookAndFeel = UIManager.getSystemLookAndFeelClassName();
        try
          UIManager.setLookAndFeel(nativeLookAndFeel);
          SwingUtilities.updateComponentTreeUI(this); //THIS IS LINE 124: site of "NullPointerException"
        catch (UnsupportedLookAndFeelException ex)
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, "There was an error switching to your system look and feel.  It is either missing or unsupported.", "Unsupported or Missing Look and Feel", JOptionPane.ERROR_MESSAGE);
        catch (ClassNotFoundException ex)
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, "There was an error switching to your system look and feel.  Unable to find the system's look and feel.", "Missing Look and Feel.", JOptionPane.ERROR_MESSAGE);
        catch (InstantiationException ex)
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, "There was an error switching to your system look and feel.  Unable to instantiate the look and feel.", "Unable to Instantiate Look and Feel", JOptionPane.ERROR_MESSAGE);
        catch (IllegalAccessException ex)
          ex.printStackTrace();
          JOptionPane.showMessageDialog(this, "There was an error switching to your system's look and feel.  Unable to Access this property.", "Error Accessing Look and Feel", JOptionPane.ERROR_MESSAGE);
        }Everything works perfectly fine when I run this on my Ubuntu 8.04 computer that I wrote and compiled it on, but when I move the application over to a Ubuntu 9.10 machine, I get the following error message:
    Exception in thread "main" java.lang.NullPointerException
         at javax.swing.JComponent.setBorder(JComponent.java:1768)
         at javax.swing.DefaultListCellRenderer.getListCellRendererComponent(DefaultListCellRenderer.java:159)
         at javax.swing.plaf.basic.BasicComboBoxUI.getDefaultSize(BasicComboBoxUI.java:1248)
         at javax.swing.plaf.basic.BasicComboBoxUI.getDisplaySize(BasicComboBoxUI.java:1319)
         at javax.swing.plaf.basic.BasicComboBoxUI.getMinimumSize(BasicComboBoxUI.java:888)
         at javax.swing.plaf.basic.BasicComboBoxUI.getPreferredSize(BasicComboBoxUI.java:878)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1634)
         at javax.swing.GroupLayout$ComponentSpring.calculateNonlinkedPreferredSize(GroupLayout.java:3015)
         at javax.swing.GroupLayout$ComponentSpring.calculateNonlinkedMinimumSize(GroupLayout.java:3001)
         at javax.swing.GroupLayout$ComponentSpring.calculateMinimumSize(GroupLayout.java:2968)
         at javax.swing.GroupLayout$Spring.getMinimumSize(GroupLayout.java:1332)
         at javax.swing.GroupLayout$ComponentSpring.calculatePreferredSize(GroupLayout.java:2975)
         at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1342)
         at javax.swing.GroupLayout$ComponentSpring.getBaseline(GroupLayout.java:3069)
         at javax.swing.GroupLayout$BaselineGroup.calculateBaselineAndResizeBehavior(GroupLayout.java:2728)
         at javax.swing.GroupLayout$BaselineGroup.calculateSize(GroupLayout.java:2704)
         at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1598)
         at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1342)
         at javax.swing.GroupLayout$Group.getSpringSize(GroupLayout.java:1634)
         at javax.swing.GroupLayout$Group.calculateSize(GroupLayout.java:1620)
         at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1598)
         at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1342)
         at javax.swing.GroupLayout$Group.getSpringSize(GroupLayout.java:1634)
         at javax.swing.GroupLayout$Group.calculateSize(GroupLayout.java:1618)
         at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1598)
         at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1342)
         at javax.swing.GroupLayout$Group.getSpringSize(GroupLayout.java:1634)
         at javax.swing.GroupLayout$Group.calculateSize(GroupLayout.java:1618)
         at javax.swing.GroupLayout$Group.calculatePreferredSize(GroupLayout.java:1598)
         at javax.swing.GroupLayout$Spring.getPreferredSize(GroupLayout.java:1342)
         at javax.swing.GroupLayout$SequentialGroup.setValidSize(GroupLayout.java:2013)
         at javax.swing.GroupLayout$Group.setSize(GroupLayout.java:1583)
         at javax.swing.GroupLayout.calculateAutopadding(GroupLayout.java:1075)
         at javax.swing.GroupLayout.layoutContainer(GroupLayout.java:916)
         at java.awt.Container.layout(Container.java:1481)
         at java.awt.Container.doLayout(Container.java:1470)
         at java.awt.Container.validateTree(Container.java:1568)
         at java.awt.Container.validateTree(Container.java:1575)
         at java.awt.Container.validateTree(Container.java:1575)
         at java.awt.Container.validateTree(Container.java:1575)
         at java.awt.Container.validate(Container.java:1540)
         at javax.swing.SwingUtilities.updateComponentTreeUI(SwingUtilities.java:1221)
         at package.App.start(App.java:124)
         at package.App.<init>(App.java:28)
         at package.Main.main(Main.java:42)
    I get the impression that there is a NullPointerException happening at line 124 (marked above), however I don't see anything that could be causing this kind of behavior, especially considering that it appears to work fine on another machine.
    Does anyone have any ideas, input, or explanations? Any help would be appreciated.

    jta23 wrote:
    When are you setting the look and feel?
    I've only been able to safely do this at launch; any other time is asking for trouble (in my experience).The look and feel is set at the launch, and the only things occurring beforehand are the reading of a properties file and the setting of the current locale...
    Also, by the way, I tested the application on Mac OS X, and received no errors of the kind. This had only problem occurred on 1 computer I have tried it on.
    Edited by: Quytelda on Apr 5, 2010 8:37 PM

  • Button events

    Hi
    Please can anyone help. I put a table button in a GUI and tried to open the table in a separate GUI. The data for this table is stored somewhere but when I click on the table button nothing happens. Some of the other buttons: next exercise, exit are not working either. What am I doing wrong?
    Any help will be most appreciated.
    Thanks
    Sofia
    ExerciseGUI - contains tableGUI button and other buttons
    TableGUI
    TableDBHandler
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.Component;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class ExerciseGUI extends JFrame {
    JTable table = new JTable(5,3); JLabel tableLabel = new JLabel ("Customer Table");
    JTextField exerciseName = new JTextField(40); JLabel
    exerciseNameLabel = new JLabel("Exercise Name");
    JTextField questionNum = new JTextField(10); JLabel questionNumLabel = new JLabel("Question Number");
    Font font = new Font("times new roman", Font.BOLD, 30);
    JTextArea question = new JTextArea(5,36); JLabel questionLabel = new JLabel("Question");
    JTextField answer = new JTextField(36); JLabel answerLabel     = new JLabel("Student Answer");
    JButton accept          = new JButton();
    JButton copy = new JButton(); //JScrollBar scroll = new JScrollBar();
    JButton next = new JButton();
    JButton close = new JButton();
    JButton table = new JButton();
         JPanel questPanel     = new JPanel();
         JPanel answPanel     = new JPanel();
         JPanel mainPanel     = new JPanel();
    JScrollPane scrollPane = new JScrollPane(question);
    JLabel wordsLabel = new JLabel("Select words");
    JTextField wordList = new JTextField();
    TableGUI aTableGUI= new TableGUI();
    JLabel sortWordsLabel = new JLabel(" Sort these items to form the correct SQL query statement in answer.");
    public static final int DISPOSE_ON_CLOSE = 2;
         FlowLayout myLayout = new FlowLayout(FlowLayout.LEFT);
         public ExerciseGUI() {
         try {
    setDisplay();
    setSize(600,500);
    }catch(Exception e) {e.printStackTrace();}
         public static void setNativeLookAndFeel() {
    try {
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         catch(Exception e) {
         System.out.println("Error setting native LAF: " + e);
         private void setQuestionPanel() {
              questPanel.setBorder(BorderFactory.createTitledBorder("QUESTION"));
              questPanel.setLayout(myLayout);
              questPanel.setMinimumSize(new Dimension(450,300));
              questPanel.setPreferredSize(new Dimension(450,300));
              questPanel.setMaximumSize(new Dimension(450,300));
    questPanel.add(exerciseNameLabel);
         questPanel.add(exerciseName);
    questPanel.add(questionNumLabel);
         questPanel.add(questionNum);
    questPanel.add(questionLabel);
    boolean aWrap = true;
    questPanel.add(question);
         questPanel.add(tableLabel);
    questPanel.add(table);
    JButton aButton = new JButton();
         questPanel.add(aButton, null);
    aButton.setText("Table");
    aButton.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    aButton_mouseClicked(e);
    void aButton_mouseClicked(MouseEvent e) {
    tableGUI aTableGUI= new tableGUI();
         private void setAnswerPanel() {
              answPanel.setBorder(BorderFactory.createTitledBorder("ANSWER"));
              answPanel.setLayout(myLayout);
              answPanel.setMinimumSize(new Dimension(400,200));
              answPanel.setPreferredSize(new Dimension(400,200));
              answPanel.setMaximumSize(new Dimension(400,200));
         answPanel.add(sortWordsLabel);
    copy.setText("Select");
              copy.setSize(2,30);
    answPanel.add(copy);
    copy.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
         copy_mouseClicked(e);
    answPanel.add(answerLabel);
              answPanel.add(answer);
    accept.setText("Evaluate Answer");
              accept.setSize(2,30);
    accept.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    accept_mouseClicked(e);
    next.setText("Next Exercise");
    next.setSize(2, 20);
    next.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    next_mouseClicked(e);
    close.setText("Exit Tutorial");
    close.setSize(2, 20);
    close.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    close_mouseClicked(e);
         answPanel.add(accept);
    answPanel.add(next, null);
    answPanel.add(close, null);
         private void setDisplay() throws Exception {
              setNativeLookAndFeel();
              Container content = getContentPane();
              //content.setMiniumSize(new Dimension(400,400));
              //content.setPreferredSize(new dimension(400,400));
              content.setLayout(new GridLayout(0,1));
              content.setFont(font);
              content.setBackground(Color.lightGray);
    this.setTitle("Display Exercise");
    setQuestionPanel();
              setAnswerPanel();
              content.add(questPanel);
              content.add(answPanel);
              setContentPane(content);
    /* exerciseGUI.setDefaultCloseOperation(
    WindowConstants.DISPOSE_ON_CLOSE);
    exerciseGUI.addWindowListener() {
    public void windowClosed(WindowEvent e){
    system.exit(20);
    String studentAnswer;
    void accept_mouseClicked(MouseEvent e) {
    String studentAnswer = answer.getText();
    DBHandler aDBHandler = new DBHandler(questionNum.getText(), studentAnswer);
    void copy_mouseClicked(MouseEvent e) {
    wordList.copy();
    answer.paste();
    answer.append("");
    void next_mouseClicked(MouseEvent e) {
    System.out.println("Starting Search_GUI...");
              ExerciseSelectorGUI aGUI = new ExerciseSelectorGUI();
    aGUI.show();
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.Component;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableGUI extends JFrame {
    JTable table = new JTable(5,3); JLabel tableLabel = new JLabel("Customer Table");
         Font font          = new Font("times new roman", Font.BOLD, 30);
         JPanel tabPanel     = new JPanel();
         JPanel mainPanel     = new JPanel();
    TableDBHandler aTableDBHandler;
         FlowLayout myLayout = new FlowLayout(FlowLayout.LEFT);
         public TableGUI() {
         try {
    setDisplay();
    setSize(500,400);
    }catch(Exception e) {e.printStackTrace();}
         public static void setNativeLookAndFeel() {
    try {
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         catch(Exception e) {
         System.out.println("Error setting native LAF: " + e);
         private void setTablePanel() {
              tabPanel.setBorder(BorderFactory.createTitledBorder("TABLE"));
              tabPanel.setLayout(myLayout);
              tabPanel.setMinimumSize(new Dimension(300,200));
              tabPanel.setPreferredSize(new Dimension(300,200));
              tabPanel.setMaximumSize(new Dimension(300,200));
    tabPanel.add(tableLabel);
    tabPanel.add(table);
    /*copy.setText("Select");
              copy.setSize(2,30);
         copy.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    copy_mouseClicked(e);
         questPanel.add(copy);*/
         private void setDisplay() throws Exception {
              setNativeLookAndFeel();
              Container content = getContentPane();
              //content.setMiniumSize(new Dimension(400,400));
              //content.setPreferredSize(new dimension(400,400));
              content.setLayout(new GridLayout(0,1));
              content.setFont(font);
              content.setBackground(Color.lightGray);
    this.setTitle("Display Table");
    setTablePanel();
              content.add(tabPanel);
              setContentPane(content);
    import java.awt.*;
    import javax.swing.*;
    import java.sql.*;
    import java.lang.*;
    import javax.swing.table.*;
    public class TableDBHandler {
    TableGUI customTable = new TableGUI ();
    public TableDBHandler() {
    try {
    DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
    Connection aConnection = DriverManager.getConnection("jdbc:odbc:SQLDatabase", "", "");
    Statement aStatement = aConnection.createStatement();
    ResultSet aSet = aStatement.executeQuery ("SELECT CustomerNo, Name, Address FROM CustTable"); {
    while (aSet.next());
    customTable.addItem(aSet.get(setText));
    //aGUI.customerNo.setText(k);
    //aGUI.name.setText(l);
    //set text one under another
    //aGUI.address.setText(m);
    customTable.show();
    aConnection.close();
    catch (SQLException e) { System.exit(8);}

    Hi,
    didn't read all of your code, but one problem is that you use the same name for the JTable and the JButton (both are named table. You should avoid this, personnally I often use the first letter(s) of a variable name to explain wich class it come from... for example, bNew (or JbNew) for a NEW JButton, tNames (or jtUsers) for a USERS JTable.
    Hope this helps,
    Regards.

  • Specifying the custom serializers for Webservices

    hi,
    I am passing a custom object through the WebService call. I would like to use a custom marshalling class (for serialization,deserialization) for this particular custom object.
    I am not using the Portal infrastructure.
    Any hints how to specify this in SAP J2EE Engine?
    Kiran

    My apologies.
    The document at http://java.sun.com/developer/JDCTechTips/2004/tt0309.html#1
    titled "WORKING WITH SWING LOOK AND FEEL" explains how to set default LAF from command line and since Swing Metal doesn't provide a way to use a custom theme as we want, you should use another LAF like "NimROD":
    http://www.javootoo.com/plaf/nimrod/index.html
    which supports themes via command line and has a tool (friendly GUI) to build themes!
    []'s

  • How to print JComponent by printer in real specified size

    for example, i want to print JLabel with size 12 cm on paper. What and where should I look for, what do I need to change?
    Thanks for answer.

    Step 1: Create "PrintExample.java" file for displaying frame._
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.geom.*;
    public class PrintExample extends JFrame implements ActionListener {
    public static void main(String[] args) {
    new PrintExample();
    public PrintExample() {
    super("Printing Swing Components");
    WindowShow.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    JButton printButton = new JButton("Print");
    printButton.addActionListener(this);
    JPanel buttonPanel = new JPanel();
    buttonPanel.setBackground(Color.white);
    buttonPanel.add(printButton);
    content.add(buttonPanel, BorderLayout.SOUTH);
    DrawingPane drawingPanel = new DrawingPane();
    content.add(drawingPanel, BorderLayout.CENTER);
    setSize(800,300);
    setVisible(true);
    public void actionPerformed(ActionEvent event) {
    PrintableDocument.printComponent(this);
    class DrawingPane extends JPanel {
    private int fontSize = 90;
    private String message = "Roseindia.net";
    private int messageWidth;
    public DrawingPane() {
    setBackground(Color.white);
    Font font = new Font("Serif", Font.PLAIN, fontSize);
    setFont(font);
    FontMetrics metrics = getFontMetrics(font);
    messageWidth = metrics.stringWidth(message);
    int width = messageWidth*5/3;
    int height = fontSize*3;
    setPreferredSize(new Dimension(width, height));
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D graph = (Graphics2D)g;
    int x = messageWidth/10;
    int y = fontSize*5/2;
    graph.translate(x, y);
    graph.setPaint(Color.lightGray);
    AffineTransform origTransform = graph.getTransform();
    graph.shear(-0.95, 0);
    graph.scale(1, 3);
    graph.drawString(message, 0, 0);
    graph.setTransform(origTransform);
    graph.setPaint(Color.black);
    graph.drawString(message, 0, 0);
    Step 2: Create "PrintableDocument.java" file for print the display value.
    In this step using print() method. This method sets of pages.
    PrinterJob : A PrinterJob object should be created using the static getPrinterJob() method.
    The PrinterJob class is the principal class that controls printing. An application calls method in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.
    Graphic2D:
    This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java platform.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintableDocument implements Printable {
    private Component compent;
    public static void printComponent(Component c) {
    new PrintableDocument(c).print();
    public PrintableDocument(Component compent) {
    this.compent = compent;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if(printJob.printDialog())
    try {
    printJob.print();
    catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    else {
    Graphics2D graph = (Graphics2D)g;
    graph.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    disableBuffering(compent);
    compent.paint(graph);
    enableBuffering(compent);
    return(PAGE_EXISTS);
    public static void disableBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    public static void enableBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    Step 3: Create "WindowShow.java" file for window Look and Feel.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class WindowShow {
    public static void setNativeLookAndFeel() {
    try{
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception e) {
    System.out.println("Error setting native LAF: " + e);
    public static JFrame openInJFrame
    (Container content, int width, int height, String title, Color bgColor) {
    class ExitListener extends WindowAdapter {
    public void windowClosing(WindowEvent event) {
    System.exit(0);
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
    public static JFrame openInJFrame
    (Container content, int width, int height, String title) {
    return(openInJFrame(content, width, height, title, Color.green));
    public static JFrame openInJFrame(Container content, int width, int height) {
    return(openInJFrame(content, width, height,content.getClass().getName(), Color.green));
    }

  • Full screen displays menu even after call to setUndecorated(true)

    I am trying to implement a full screen mode for my application. It still displays the menu in Windows, and in mac if I don't set apple.laf.useScreenMenuBar to true, even if I call setUndecorated(true).
    How do I hide that menu bar? I tried removing it, but then I lose my menu hotkey to toggle out of fullscreen.
    This is my sample code:
    import java.awt.GraphicsDevice;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class FullScreen extends JFrame {
        static JFrame window;
        public static void main(String argv[]) {
            if(System.getProperty("os.name").startsWith("Mac OS X"))
                System.setProperty("apple.laf.useScreenMenuBar", "true");
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    window = new FullScreen();
                    window.setVisible(true);
        private GraphicsDevice graphicsDevice;
        private boolean fullScreenMode;
        private Rectangle previousSize;
        private JMenuBar menus;
        private FullScreen(){
            JButton but= new JButton("switch");
            menus= new JMenuBar();
            JMenu menu = new JMenu("View");
            JMenuItem item = new JMenuItem("full screen");
            item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
            item.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    toggleFullScreen();
            this.setJMenuBar(menus);
            menus.add(menu);
            menu.add(item);
            but.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    toggleFullScreen();
            this.add(but);
            //prep for fullscreen mode
            GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
            graphicsDevice = ge.getDefaultScreenDevice();
            pack();
        public void toggleFullScreen() {
            if (fullScreenMode){
                this.dispose();
                this.setUndecorated(false);
                this.setResizable(true);
                this.setBounds(previousSize);
                graphicsDevice.setFullScreenWindow(null);
                this.setVisible(true);
            }else{
                if(graphicsDevice.isFullScreenSupported()){
                    this.dispose();
                    previousSize=this.getBounds();
                    this.setUndecorated(true);
                    this.setResizable(false);
                    graphicsDevice.setFullScreenWindow(this);
    //                drawingPanel.setPreferredSize(new java.awt.Dimension( this.getBounds().width, this.getBounds().height));
                    this.setVisible(true);
            fullScreenMode = !fullScreenMode;
    }Edited by: jstoner on Jun 14, 2009 10:36 PM

    if (fullScreenMode){
        menus.setPreferredSize(null);
        ...  //exit fullscreen mode
    }else {
        menus.setPreferredSize(new java.awt.Dimension());
        ... //enter fullscreen mode
    }

Maybe you are looking for

  • Why are animated gifs not displaying animations in the preview?

    Why are animated gifs not displaying animations in the preview? My coworkers and I are not seeing a animation in the preview pane in Adobe Bridge CS6 even when clicking the play button in the preview window. However, we do see a graphic of the first

  • Invoice report requirement

    Hello Gurus, In MIR4 we can see invoice lines. I want to display invoice lines with exchange rates. For example : I have a invoice numbered 1234567 This invoice have 2 lines. 1st line amount is 1000$, 2nd line is 1500$ I want to display this invoice

  • ADF 10.1.3.4 Memory Leak

    I can re-produce a ADF memory leak in jdeveloper. The problems seems to be when I am running the application locally in the memory profiler, the memory usage keeps growing until the application halts with a outofmemoryexception. The main problem seem

  • Optimize SQL  query

    Hi All, Please help me to optimize my below SQL  query : delete from BATCH_REQUEST_RESPONSE where (SOState='ResponseReceived' or SOState='Header' or SOState='InvalidSO') and ACKREC='Y' and SourceAgentId=? and BATCH_REQUEST_RESPONSE.TransactionId NOT

  • Is there any Adobe LiveCycle PDF Generator for PS EXPERTS?

    There seems to be a lot of question about this product with no answers. When you call Adobe you get the run around. How is the product supposed to work? When a basic installation is performed it does not do what is expected. If you are suppose to be