Javax.swing.JFrame snapping ?

Hi,
I'll get right to the point.
I would like to make my jFrames "snap" together when they're close to each other and keep snapped together when they do this. A lot like WinAMP does with it's windows. I have tried to write this snapping code by myself using ComponentMoved(ComponentEvent e) but I humble in the dark when it comes to snapping ... and also the code I wrote just snaps (in a bit buggy way) to the edge of the screen, not to other jFrames. I have looked around and found that java Look and Feel (www.lf2prod.com) has something called windowsnapping ... but the documentation is empty, and I'm more then ever confused. Is there a way to do this "snapping"? Are there methods already written that could simplify my task ? If not, any suggestions on how to implement this window snapping feature by scratch ?
Thank you all,
s0gno

I'm looking for the same thing... except for JInternalFrames. I haven't been able to find anything even remotely close to addressing this issue.

Similar Messages

  • Variable textArea not found in class javax.swing.JFrame...

    Making progress on this issue -- but still stuck. Again trying to get the text from a JTextArea on exit:
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
            });User MARSIAN helped me understand the scope fo the variables and now that has been fixed. Unfortunately I cannot access my variable textArea in the above code. If get this error:
    Error: variable textArea not found in class javax.swing.JFrame
    What am I doing wrong?
    import  java.net.*;
    import  javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import FragImpl.*;
    public class Framework extends WindowAdapter {
        public int numWindows = 0;
        private Point lastLocation = null;
        private int maxX = 500;
        private int maxY = 500;
        JFrame frame;
        public Framework() {
            newFrag();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            maxX = screenSize.width - 50;
            maxY = screenSize.height - 50;
            makeNewWindow();
        public void makeNewWindow() {
            frame = new MyFrame(this);  //*
            numWindows++;
            System.out.println("Number of windows: " + numWindows);
            if (lastLocation != null) {
                //Move the window over and down 40 pixels.
                lastLocation.translate(40, 40);
                if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
                    lastLocation.setLocation(0, 0);
                frame.setLocation(lastLocation);
            } else {
                lastLocation = frame.getLocation();
            System.out.println("Frame location: " + lastLocation);
            frame.setVisible(true);
            frame.addWindowListener
           (new WindowAdapter() {
             public void windowClosing(WindowEvent e)
                System.out.println("Why me???" + frame.textArea.getText());
        //This method must be evoked from the event-dispatching thread.
        public void quit(JFrame frame) {
            if (quitConfirmed(frame)) {
                System.exit(0);
            System.out.println("Quit operation not confirmed; staying alive.");
        private boolean quitConfirmed(JFrame frame) {
            String s1 = "Quit";
            String s2 = "Cancel";
            Object[] options = {s1, s2};
            int n = JOptionPane.showOptionDialog(frame,
                    "Windows are still open.\nDo you really want to quit?",
                    "Quit Confirmation",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    s1);
            if (n == JOptionPane.YES_OPTION) {
                return true;
            } else {
                return false;
         private void newFrag()
              Frag frag = new FragImpl();
        public static void main(String[] args) {
            Framework framework = new Framework();
    class MyFrame extends JFrame {
        protected Dimension defaultSize = new Dimension(200, 200);
        protected Framework framework = null;
        private Color color = Color.yellow;
        private Container c;
        JTextArea textArea;
        public MyFrame(Framework controller) {
            super("New Frame");
            framework = controller;
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setSize(defaultSize);
            //Create a text area.
            textArea = new JTextArea(
                    "This is an editable JTextArea " +
                    "that has been initialized with the setText method. " +
                    "A text area is a \"plain\" text component, " +
                    "which means that although it can display text " +
                    "in any font, all of the text is in the same font."
            textArea.setFont(new Font("Serif", Font.ITALIC, 16));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setBackground ( Color.yellow );
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            //Create the status area.
            JPanel statusPane = new JPanel(new GridLayout(1, 1));
            ImageIcon icoOpen = null;
            URL url = null;
            try
                icoOpen = new ImageIcon("post_it0a.gif"); //("doc04d.gif");
            catch(Exception ex)
                ex.printStackTrace();
                System.exit(1);
            setIconImage(icoOpen.getImage());
            c = getContentPane();
            c.setBackground ( Color.yellow );
            c.add ( areaScrollPane, BorderLayout.CENTER )  ;
            c.add ( statusPane, BorderLayout.SOUTH );
            c.repaint ();
    }

    Yeah!!! It works. Turned out to be a combination of DrKlap's and Martisan's suggestions -- had to change var frame's declaration from JFrame to MyFrame:
        MyFrame frame;Next, created the external class -- but again changed JFrame references to MyFrame:
    public class ShowOnExit extends WindowAdapter {
    //   JFrame aFrame;
       MyFrame aFrame;
       public ShowOnExit(MyFrame f) {
          aFrame = f;
       public void windowClosing(WindowEvent e)
          System.out.println("Why me???" + aFrame.textArea.getText()); // aFrame here not frame !!!
    }This worked. So looks like even though the original code added a WindowListener to 'frame', the listener didn't couldn't access frame's methods unless it was explicitly passed in as a parameter. Let me know if that's wrong.
    Thanks again, all.

  • Using setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); ...?

    using setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
    JFrame Window will cover windows toolbar.
    how to create JFrame,make it max size,don't cover windows toolbar.

    import javax.swing.*;
    import java.awt.*;
    class Testing
      public void buildGUI()
        JFrame f = new JFrame();
        f.setExtendedState(JFrame.MAXIMIZED_BOTH);
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        f.setMaximizedBounds(env.getMaximumWindowBounds());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Error "javax.swing.JFrame"  cannot find symbol  frame.getContentPane90.add

    Getting above errror when running the code below.how do I install the Jframe so the program can see it.Looks like JRE and JDK does not have it.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SimpleGui1{
    public static void main(String []args){
    JFrame frame = new JFrame();
    JButton button = new JButton("click me");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane90.add(button);
    frame.setSize(300,300);
    frame.setVisible(true);
    }

    This is the single most amazing thread I have ever+* seen.                                                                                                                                                                                                   

  • Java.lang.ClassNotFoundException: javax.swing.JFrame

    i have developed a program in java and it is working fine in windows xp, but when i try to execute it in redhat linux, the ff errors are generated:
    Exception in thread "main" java.lang.InternalError: Unexpected exception while defining class WESMOMP$1: java.lang.ClassNotFoundException: javax.net.ssl.HostnameVerifier
       at 0x00362ca3: java.lang.Throwable.Throwable(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00355b1e: java.lang.Error.Error(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00363086: java.lang.VirtualMachineError.VirtualMachineError(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003574be: java.lang.InternalError.InternalError(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00354abf: java.lang.ClassLoader.defineClass(java.lang.String, byte[], int, int, java.security.ProtectionDomain) (/usr/lib/./libgcj.so.3)
       at 0x003548a3: java.lang.ClassLoader.defineClass(java.lang.String, byte[], int, int) (/usr/lib/./libgcj.so.3)
       at 0x003ebd96: java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003420f7: gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00354794: java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/./libgcj.so.3)
       at 0x003427fc: _Jv_FindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/./libgcj.so.3)
       at 0x0033ec6d: java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/./libgcj.so.3)
       at 0x0033549f: _Jv_BytecodeVerifier.verify_instructions_0() (/usr/lib/./libgcj.so.3)
       at 0x0032b7c7: _Jv_VerifyMethod(_Jv_InterpMethod) (/usr/lib/./libgcj.so.3)
       at 0x00323a64: _Jv_PrepareClass(java.lang.Class) (/usr/lib/./libgcj.so.3)
       at 0x00341f88: java.lang.ClassLoader.linkClass0(java.lang.Class) (/usr/lib/./libgcj.so.3)
       at 0x00354b43: java.lang.ClassLoader.resolveClass0(java.lang.Class) (/usr/lib/./libgcj.so.3)
       at 0x003403fc: java.lang.Class.initializeClass() (/usr/lib/./libgcj.so.3)
       at 0x0033ec94: java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/./libgcj.so.3)
       at 0x0033ed2f: java.lang.Class.forName(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003a6e81: gnu.gcj.runtime.FirstThread.run() (/usr/lib/./libgcj.so.3)
       at 0x00349aec: _Jv_ThreadRun(java.lang.Thread) (/usr/lib/./libgcj.so.3)
       at 0x0031682c: _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/./libgcj.so.3)
       at 0x08048930: ?? (??:0)
       at 0x006f778a: __libc_start_main (/lib/tls/libc.so.6)
       at 0x080486e1: ?? (??:0)I think that java cannot see the javax package.
    also i tried to execute a java program that uses mysql connector, it generated this error:
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
       at 0x00362ca3: java.lang.Throwable.Throwable(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00355b62: java.lang.Exception.Exception(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x00355218: java.lang.ClassNotFoundException.ClassNotFoundException(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003ebdb9: java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003420f7: gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x003547af: java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/./libgcj.so.3)
       at 0x00342839: _Jv_FindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/./libgcj.so.3)
       at 0x0033ec6d: java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/./libgcj.so.3)
       at 0x0033ed2f: java.lang.Class.forName(java.lang.String) (/usr/lib/./libgcj.so.3)
       at 0x0047d007: ffi_call_SYSV (/usr/lib/./libgcj.so.3)
       at 0x0047cfc7: ffi_raw_call (/usr/lib/./libgcj.so.3)
       at 0x0032a658: _Jv_InterpMethod.continue1(_Jv_InterpMethodInvocation) (/usr/lib/./libgcj.so.3)
       at 0x0032af64: _Jv_InterpMethod.run(ffi_cif, void, ffi_raw, _Jv_InterpMethodInvocation) (/usr/lib/./libgcj.so.3)
       at 0x00328474: _Jv_InterpMethod.run_normal(ffi_cif, void, ffi_raw, void) (/usr/lib/./libgcj.so.3)
       at 0x0047ce7c: ?? (??:0)
       at 0x0033cd68: gnu.gcj.runtime.FirstThread.call_main() (/usr/lib/./libgcj.so.3)
       at 0x003a6e91: gnu.gcj.runtime.FirstThread.run() (/usr/lib/./libgcj.so.3)
       at 0x00349aec: _Jv_ThreadRun(java.lang.Thread) (/usr/lib/./libgcj.so.3)
       at 0x0031682c: _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/./libgcj.so.3)
       at 0x08048930: ?? (??:0)
       at 0x0074c78a: __libc_start_main (/lib/tls/libc.so.6)
       at 0x080486e1: ?? (??:0)how to install the mysql jdbc connector?
    please help...thx

    First: Check java version
    $java -version
    Second: Run your program with explicit classpath declaration
    $java -cp yourjdbcdriver.jar;yourprogram.jar com.you.program.ClassContainingMainMethodI'm not sure what to use for jar's delimeter semicolon, or colon. Try both.

  • Swings-JFrame

    IN my program ,JFrame,JButton1 named VIEW ALL ,JComboBox ,JButton2 by clicking this calender will be displayed select the date ,that selected date will come into JComboBox,JButton3 named BY DATE.
    when click on VIEW ALL button data from the database(oracle 10g) will be retrieved into JTable, that table will be displayed in same JFrame.
    If we click on BY DATE button data will be displayed by that date only in the same JFrame.
    view is like this:
    VIEW ALL JCOmboBox JButton2 BY DATE
    display of JTable resultsin the same frame
    i have written the code for JTable like this;
    package crm;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    * @author rajeshwari
    public class Callbacks extends javax.swing.JFrame {
    JTable table;
         JTableHeader header;
         Vector data = new Vector();
         String colnames[];
    public Callbacks() {
    getConnection();
    /** 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() {
    // jPanel1 = new javax.swing.JPanel();
    // jPanel2 = new javax.swing.JPanel();
    // jButton1 = new javax.swing.JButton();
    // jButton2 = new javax.swing.JButton();
    // jButton3 = new javax.swing.JButton();
    // jButton4 = new javax.swing.JButton();
    // jButton5 = new javax.swing.JButton();
    // jButton6 = new javax.swing.JButton();
    // jButton7 = new javax.swing.JButton();
    // jLabel1 = new javax.swing.JLabel();
    // jTextField1 = new javax.swing.JTextField();
    // jLabel2 = new javax.swing.JLabel();
    // jTextField2 = new javax.swing.JTextField();
    // jLabel3 = new javax.swing.JLabel();
    // jScrollPane1 = new javax.swing.JScrollPane();
    // jTextArea1 = new javax.swing.JTextArea();
    // jLabel4 = new javax.swing.JLabel();
    // jTextField3 = new javax.swing.JTextField();
    // jLabel5 = new javax.swing.JLabel();
    // jTextField4 = new javax.swing.JTextField();
    // jLabel6 = new javax.swing.JLabel();
    // jTextField5 = new javax.swing.JTextField();
    // jLabel7 = new javax.swing.JLabel();
    // jTextField6 = new javax.swing.JTextField();
    // jLabel8 = new javax.swing.JLabel();
    // jTextField7 = new javax.swing.JTextField();
    // jLabel9 = new javax.swing.JLabel();
    // jTextField8 = new javax.swing.JTextField();
    // jLabel10 = new javax.swing.JLabel();
    // jTextField9 = new javax.swing.JTextField();
    // jLabel11 = new javax.swing.JLabel();
    // jTextField10 = new javax.swing.JTextField();
    // jButton8 = new javax.swing.JButton();
    // jButton9 = new javax.swing.JButton();
    // jPanel3 = new javax.swing.JPanel();
    // jLabel12 = new javax.swing.JLabel();
    // jTextField11 = new javax.swing.JTextField();
    // jLabel13 = new javax.swing.JLabel();
    // jTextField12 = new javax.swing.JTextField();
    // jLabel14 = new javax.swing.JLabel();
    // jTextField13 = new javax.swing.JTextField();
    // jLabel15 = new javax.swing.JLabel();
    // jTextField14 = new javax.swing.JTextField();
    // jScrollPane2 = new javax.swing.JScrollPane();
    // jTextPane1 = new javax.swing.JTextPane();
    // jButton10 = new javax.swing.JButton();
    // jScrollPane3 = new javax.swing.JScrollPane();
    // jTextPane2 = new javax.swing.JTextPane();
    // jMenuBar1 = new javax.swing.JMenuBar();
    // jMenu1 = new javax.swing.JMenu();
    // jMenu2 = new javax.swing.JMenu();
    // jMenu3 = new javax.swing.JMenu();
    // jMenu4 = new javax.swing.JMenu();
    // jMenu5 = new javax.swing.JMenu();
    // jMenu6 = new javax.swing.JMenu();
    // jMenu7 = new javax.swing.JMenu();
    // jMenu8 = new javax.swing.JMenu();
    // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // jButton1.setText("Call Back");
    // jButton2.setText("Not Interested");
    // jButton3.setText("Person Not Available\n");
    // jButton4.setText("Answering Machine");
    // jButton5.setText("Person Available");
    // jButton6.setText("Do not Call");
    // jButton7.setText("Next>>...");
    // org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    // jPanel2.setLayout(jPanel2Layout);
    // jPanel2Layout.setHorizontalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)))
    // jPanel2Layout.setVerticalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jButton1)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton2)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton3)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton4)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton5)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton6)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton7)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jLabel1.setText("\nCustomer ID:");
    // jTextField1.setText("852");
    // jLabel2.setText("Customer Name:");
    // jTextField2.setText("Rajeshwari");
    // jLabel3.setText("Address:");
    // jTextArea1.setColumns(20);
    // jTextArea1.setRows(5);
    // jScrollPane1.setViewportView(jTextArea1);
    // jLabel4.setText("City:");
    // jTextField3.setText("HYD");
    // jLabel5.setText("State:");
    // jTextField4.setText("A.P");
    // jLabel6.setText("Zip:");
    // jTextField5.setText("39");
    // jLabel7.setText("Phone:");
    // jTextField6.setText("220288");
    // jLabel8.setText("Mobile:");
    // jTextField7.setText("9949162978");
    // jLabel9.setText("Fax:");
    // jTextField8.setText("2343535");
    // jLabel10.setText("Email:");
    // jTextField9.setText("[email protected]");
    // jLabel11.setText("Call Time:");
    // jTextField10.setText("12:34:23");
    // jButton8.setText("Call Backs");
    // jButton8.addActionListener(new java.awt.event.ActionListener() {
    // public void actionPerformed(java.awt.event.ActionEvent evt) {
    // jButton8ActionPerformed(evt);
    // jButton9.setText("Hang");
    // jLabel12.setText("Call Back Date:");
    // jTextField11.setText("12-03-98");
    // jLabel13.setText("Call Back Time:");
    // jTextField12.setText("12:23:45");
    // jLabel14.setText("Called on:");
    // jTextField13.setText("11:12:99");
    // jLabel15.setText("Called At:");
    // jTextField14.setText("jTextField14");
    // jScrollPane2.setViewportView(jTextPane1);
    // jButton10.setText("ADD");
    // org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    // jPanel3.setLayout(jPanel3Layout);
    // jPanel3Layout.setHorizontalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel12)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel13)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
    // .add(27, 27, 27)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel14)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel15)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField14))))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 187, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(28, 28, 28)
    // .add(jButton10)))
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jPanel3Layout.setVerticalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel12)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel14)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(17, 17, 17)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel13)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel15)
    // .add(jTextField14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
    // .add(jButton10)
    // .add(22, 22, 22))))
    // jScrollPane3.setViewportView(jTextPane2);
    // org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    // jPanel1.setLayout(jPanel1Layout);
    // jPanel1Layout.setHorizontalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(30, 30, 30)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(32, 32, 32)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jLabel2)
    // .add(jLabel1)
    // .add(jLabel3)
    // .add(jLabel4)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 46, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(58, 58, 58))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
    // .add(66, 66, 66))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(66, 66, 66))))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(254, 254, 254)))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jButton8)
    // .add(27, 27, 27)
    // .add(jButton9))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel9))
    // .add(jLabel10)
    // .add(jLabel11))
    // .add(6, 6, 6)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jTextField10)
    // .add(jTextField9)
    // .add(jTextField8)
    // .add(jTextField7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)))
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 212, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(45, 45, 45))
    // jPanel1Layout.setVerticalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(23, 23, 23)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(42, 42, 42)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel1)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(16, 16, 16)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel2)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(25, 25, 25)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel3))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel4)
    // .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(18, 18, 18)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel5)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jButton8)
    // .add(jButton9)
    // .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel8)
    // .add(jTextField7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel9)
    // .add(jTextField8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel10)
    // .add(jTextField9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(34, 34, 34)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel11)
    // .add(jTextField10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))))
    // .add(63, 63, 63)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(44, 44, 44))))
    // jMenu1.setText("start");
    // jMenuBar1.add(jMenu1);
    // jMenu2.setText("Leads");
    // jMenuBar1.add(jMenu2);
    // jMenu3.setText("Campaign");
    // jMenuBar1.add(jMenu3);
    // jMenu4.setText("Reports");
    // jMenuBar1.add(jMenu4);
    // jMenu5.setText("Recordings");
    // jMenuBar1.add(jMenu5);
    // jMenu6.setText("Agents");
    // jMenuBar1.add(jMenu6);
    // jMenu7.setText("Time Zones");
    // jMenuBar1.add(jMenu7);
    // jMenu8.setText("Help");
    // jMenuBar1.add(jMenu8);
    // setJMenuBar(jMenuBar1);
    // 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(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // layout.setVerticalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(78, 78, 78)
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // pack();
    // }// </editor-fold>
    public void getConnection()
    // Object src=evt.getSource();
    String name="";
    String call_back_date="";
    String call_back_time="";
    String called_on="";
    String called_at="";
    String phone="";
    String comments="";
    // if(src==jButton8)
    try{
    colnames=new String[]{"name","call_back_date","call_back_time","called_on","called_at","phone","comments"};
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url="jdbc:oracle:thin:@localhost:1521:oracle";
    Connection con=DriverManager.getConnection(url,"scott","root");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from Callbacks_details");
              while (rs.next())
              name=rs.getString("name");
              call_back_date=rs.getString("call_back_date");
              call_back_time=rs.getString("call_back_time");
    called_on=rs.getString("called_on");
    called_at=rs.getString("called_at");
              phone=rs.getString("phone");
    comments=rs.getString("comments");
    Vector row = new Vector(colnames.length);
    // Vector r=new Vector();
              row.addElement(name);
              row.addElement(call_back_date);
              row.addElement(call_back_time);
    row.addElement(called_on);
    row.addElement(called_at);
              row.addElement(phone);
    row.addElement(comments);
              data.addElement(row);
    // System.out.println(data);
    catch(Exception a)
    a.printStackTrace();
    System.out.println(a);
    table=new JTable(new MyTableModel(colnames,data));
    //int n=table.getColumnCount();
              TableColumn column=null;
              for (int i = 0; i<colnames.length; i++) {
              column = table.getColumnModel().getColumn(i);
         column.setPreferredWidth(100);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
    public class MyTableModel extends AbstractTableModel{
    String[] columnNames;
         Vector d= new Vector(6);
    MyTableModel(String[] columnNames, Vector data){
         this.columnNames = columnNames;
         d = data;
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return d.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         Vector d

    for displaying table on same frame(do not cross post and use code tags just click CODE and paste the code in between)
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    public class TableShow extends JFrame{
        /** Creates a new instance of TableShow */
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        public TableShow() {
            jTable1 = new javax.swing.JTable(5,5);
            jScrollPane1 = new javax.swing.JScrollPane(jTable1);
            jButton1 = new javax.swing.JButton("Show");
            jPanel1 = new javax.swing.JPanel();
            jPanel1.setLayout(new BorderLayout());
            jPanel1.add(jScrollPane1);
            jScrollPane1.setVisible(false);
            getContentPane().add(jButton1, BorderLayout.NORTH);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            setVisible(true);
            setSize(300,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(jScrollPane1.isVisible()) {
                        jScrollPane1.setVisible(false);
                    } else{
                        jScrollPane1.setVisible(true);
                    jPanel1.validate();
        public static void main(String args[]){
            new TableShow();
    }

  • GUI Problem (Swing JFrame/JPanel). HELP!

    Hi,
    I made an small application for calculate some things.
    I download i piece of code for creating bar chart and i icluded in my code. But i have problem when i am trying to show the chart in the Frame. All the buttons, textfields, labels goes to left and half are hiding.
    If i open the chart on a new frame i dont have problem.
    the problem apears when after i put the panel in the frame i try to put the chart in the frame. Look the code:
    add(p);     //Put the panel in the Frame
    this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!that command mades me the problem!
    Here are 2 screenshots
    1. When i put the chart in the Frame (the problem)
    http://www.iweb.gr/images/InFrame.jpg
    2. When i put the chart on new frame (works fine)
    http://www.iweb.gr/images/NewFrame.jpg
    Hopes someone can help. Thanks
    The code List:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    //The main class of the program
    public class PlantFertilizer  extends JFrame{//The main class is a subclass of Frame
         private Label lN, lP,lK;//These show the value of the observable
         public TextField tN, tP, tK;
         private MyData thedata;//The observable we are going to watch
         private double[] values=new double[3];
        private String[] names=new String[3];
        private String title;
    public PlantFertilizer(){
         thedata=new MyData();// create the observable
         addWindowListener(new WindowAdapter(){//if user closes the Frame, quit
              public void windowClosing(WindowEvent e){
                   System.exit(0);
         setSize(400,500);//Set size
         setTitle(getClass().getName()+" By Pantelis Stoumpis");
         JPanel p = new JPanel();    //Make a panel for buttons and output
         //Input Data Area
         p.add(new Label("-------------------------Input Data Area--------------------------",Label.CENTER));
         p.add(new Label("Nitrogen (N)"));
         tN = new TextField();p.add(tN);
         p.add(new Label("Phosphorus (P)"));
         tP = new TextField();p.add(tP);
         p.add(new Label("Potassium (K)"));
         tK = new TextField();p.add(tK);
         lN=new Label("N = %", Label.CENTER);
         p.add(lN);     //Put the N label in the panel
         lP=new Label("P = %", Label.CENTER);
         p.add(lP);          //Put the P label in the panel
         lK=new Label("K = %", Label.CENTER);
         p.add(lK);          //Put the K label in the panel
         addButton(p,"Apply",          //Apply new Values
         new ActionListener(){
         public void actionPerformed(ActionEvent evt){
              int iNt = Integer.parseInt(tN.getText());
              int iPt = Integer.parseInt(tP.getText());
              int iKt = Integer.parseInt(tK.getText());
              thedata.addOne(iNt,iPt,iKt);          //which adds one to the observable
              JFrame f = new JFrame();
             f.setSize(400, 300);
              values[0] = 40;
             names[0] = "N";
             values[1] = 20;
             names[1] = "P";
             values[2] = 30;
             names[2] = "K";
             f.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));
              f.setVisible(true);
         addButton(p,"Close",          //add a close button to quit the program
         new ActionListener(){
         public void actionPerformed(ActionEvent evt){
              System.exit(0);
    add(p);     //Put the panel in the Frame
    this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!
    //A utility function to add a button with a given title and action
    public void addButton(Container c, String title,ActionListener a)
              Button b=new Button(title);
              c.add(b);
              b.addActionListener(a);
    public class ChartPanel extends JPanel {
      private double[] values;
      private String[] names;
      private String title;
      public ChartPanel(double[] v, String[] n, String t) {
        names = n;
        values = v;
        title = t;
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (values == null || values.length == 0)
          return;
        double minValue = 0;
        double maxValue = 0;
        for (int i = 0; i < values.length; i++) {
          if (minValue > values)
    minValue = values[i];
    if (maxValue < values[i])
    maxValue = values[i];
    //Dimension d = getSize();
    //int clientWidth = d.width;
    //int clientHeight = d.height;
    //int barWidth = clientWidth / values.length;
    //Dimension d = 100;
         int clientWidth = 100;
         int clientHeight = 150;
    int barWidth = clientWidth / values.length;
    Font titleFont = new Font("SansSerif", Font.BOLD, 12);
    FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
    Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
    FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
    int titleWidth = titleFontMetrics.stringWidth(title);
    int y = titleFontMetrics.getAscent();
    int x = (clientWidth - titleWidth) / 2;
    g.setFont(titleFont);
    g.drawString(title, 10, 300);
    int top = titleFontMetrics.getHeight();
    int bottom = labelFontMetrics.getHeight();
    if (maxValue == minValue)
    return;
    double scale = (clientHeight - top - bottom) / (maxValue - minValue);
    y = clientHeight - labelFontMetrics.getDescent();
    g.setFont(labelFont);
    for (int i = 0; i < values.length; i++) {
    int valueX = i * barWidth + 1;
    int valueY = top;
    int height = (int) (values[i] * scale);
    if (values[i] >= 0)
    valueY += (int) ((maxValue - values[i]) * scale);
    else {
    valueY += (int) (maxValue * scale);
    height = -height;
    g.setColor(Color.red);
    g.fillRect(valueX, valueY, barWidth - 2, height);
    g.setColor(Color.black);
    g.drawRect(valueX, valueY, barWidth - 2, height);
    int labelWidth = labelFontMetrics.stringWidth(names[i]);
    x = i * barWidth + (barWidth - labelWidth) / 2;
    g.drawString(names[i], x, y);
    //main is called when we start the application
    public static void main(String[]args){
                   PlantFertilizer od = new PlantFertilizer();//make an observationsDemo frame
                   NWatcher watchitN = new NWatcher(od.lN);//make an observer
                   od.thedata.addObserver(watchitN);//register observer with the observable
                   PWatcher watchitP = new PWatcher(od.lP);//make an observer
                   od.thedata.addObserver(watchitP);//register observer with the observable
                   KWatcher watchitK = new KWatcher(od.lK);//make an observer
                   od.thedata.addObserver(watchitK);//register observer with the observable
                   od.setVisible(true);//show the frame on the screen

    Why are you putting Labels and TextFields (heavyweight AWT components) into a lightweight JPanels?
    What's the first rule of Swing? DO NOT MIX heavyweight AWT components and lightweight Swing components. Period. Never.
    There's Swing equivalents for every single AWT component, and then some. There's no excuse for not using them.
    However, if this chart library code is AWT based, then you should make a completely AWT based UI. Or find a different library based on Swing (like JFreeChart).
    And finally:
    add(p);     //Put the panel in the Frame
    this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant")); // <-- The problem!!is wrong....
    add(p);      // <-- The problem!!
    this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"));You don't call add on JFrame or JDialog to add things to it, unless you know what you're doing. And you clearly don't, else you wouldn't have done it. What you probably want to do is this:
    this.getContentPane().add(p, BorderLayout.SOUTH);
    this.getContentPane().add(new ChartPanel(values, names, "Fertilizer Plant"), BorderLayout.CENTER);

  • Javax.swing.KeyStroke

    When i use Swing with PJ i get some errors about javax.swing.KeyStroke:
    java.lang.NoSuchFieldException
    at java.lang.Class.getField()
    at javax.swing.KeyStroke.getKeyStroke()
    at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults()
    at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults()
    at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.initializeDefaultLAF()
    at javax.swing.UIManager.initialize()
    at javax.swing.UIManager.maybeInitialize()
    at javax.swing.UIManager.getUI()
    at javax.swing.JPanel.updateUI()
    at javax.swing.JPanel.<init>()
    at javax.swing.JPanel.<init>()
    at javax.swing.JRootPane.createGlassPane()
    at javax.swing.JRootPane.<init>()
    at javax.swing.JFrame.createRootPane()
    at javax.swing.JFrame.frameInit()
    at javax.swing.JFrame.<init>()
    java.lang.Error: Unrecognized keycode name: VK_KP_LEFT
    at javax.swing.KeyStroke.getKeyStroke()
    at javax.swing.plaf.metal.MetalLookAndFeel.initComponentDefaults()
    at javax.swing.plaf.basic.BasicLookAndFeel.getDefaults()
    at javax.swing.plaf.metal.MetalLookAndFeel.getDefaults()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.setLookAndFeel()
    at javax.swing.UIManager.initializeDefaultLAF()
    at javax.swing.UIManager.initialize()
    at javax.swing.UIManager.maybeInitialize()
    at javax.swing.UIManager.getUI()
    at javax.swing.JPanel.updateUI()
    at javax.swing.JPanel.<init>()
    at javax.swing.JPanel.<init>()
    at javax.swing.JRootPane.createGlassPane()
    at javax.swing.JRootPane.<init>()
    at javax.swing.JFrame.createRootPane()
    at javax.swing.JFrame.frameInit()
    at javax.swing.JFrame.<init>()
    Could someone help me?

    Refer to the bug database (bugid = 4309057)
    http://developer.java.sun.com/developer/bugParade/bugs/4309057.html
    Here the workaround:
    Fix the problem yourself by changing SwingUtilites to test for "Class.getPackage" which is 1.2 specific and has not been introduced to pJava:
    Method m = Class.class.getMethod("getPackage", null);Re-Jar the swingclasses and enjoy your Swing application running on PersonalJava....
    Herbie

  • Cannot Import javax.swing.JOptionPane   Please HELP!!!

    import javax.swing.JOptionPane;
    this line of code returns the error:
    C:\Java Files\BankAccount\BankAccount_Test.java:1: Class javax.swing.JOptionPane not found in import.
    import javax.swing.JOptionPane;
    ^
    1 error
    Process completed.
    Please help, I don't know what the problem could be....

    Swing was not part of any JDK's earlier than 1.2. Swing (or anything with a J in front of it, ie. JFrame, JOptionPane, etc...) was probably the most dramatic (if not largest) modification/addition to the Java language, that's why versions later than, and including, 1.2 are known as "Java 2".

  • Missing classes from the javax.swing package?

    Can anyone throw any light on what appears to be a missing class from the javax.swing package?
    When CelsiusConverter.java from The Swing Tutorial (code fragment shown below) is compiled the JFrame class can't be found.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CelsiusConverter implements ActionListener {
        JFrame converterFrame;Despite the package javax.swing being imported, the compiler does not seem to be be able to find the JFrame class.
    CelsiusConverter.java:14: Class JFrame not found in type declaration.
        JFrame converterFrame;To attempt to solve this issue all the files in jdk1.5.0_02\lib were added to CLASSPATH.
    CLASSPATH was set to C:\Program Files\Java\jdk1.5.0_02\lib\dt.jar;C:\Program Files\Java\jdk1.5.0_02\lib\htmlconverter.jar;C:\Program Files\Java\jdk1.5.0_02\lib\jconsole.jar;C:\Program Files\Java\jdk1.5.0_02\lib\tools.jar;C:\Program Files\Java\jdk1.5.0_02\lib;C:\Program Files\Java\jdk1.5.0_02\lib\ir.idl;C:\Program Files\Java\jdk1.5.0_02\lib\jawt.lib;C:\Program Files\Java\jdk1.5.0_02\lib\jvm.lib;C:\Program Files\Java\jdk1.5.0_02\lib\orb.idl;C:\Program Files\Java\jdk1.5.0_02\demo\jfc\SwingApplet\SwingApplet.jar;.;c:\CoreJavaBook

    This is extremely strange... If you're sure it's not a problem in your code or with your classpath, the only other thing I can think to suggest is re-downloading / installing java

  • [HELP! ] why my program thows a javax.swing.text.ChangedCharSetException?

    there's the source:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.border.*;
    class HTMLMagician extends JFrame
         protected static final String APP_NAME="HTML Magician V1.0 Produced By V Studio";
         protected JTextPane hm_textPane;
         protected StyleSheet hm_styleSheet;
         protected HTMLEditorKit html_kit;
         protected HTMLDocument html_document;
         protected JMenuBar hm_menuBar;
         protected JToolBar hm_toolBar;
         protected JFileChooser hm_fileChooser;
         protected File current_file;
         protected boolean text_changed=false;
         public HTMLMagician()
              super(APP_NAME);
              setSize(800,600);
              getContentPane().setLayout(new BorderLayout());
              produceMenuBar();
              hm_textPane=new JTextPane();
              html_kit=new HTMLEditorKit();
              hm_textPane.setEditorKit(html_kit);
              JScrollPane textPane_scrollPane=new JScrollPane();
              textPane_scrollPane.getViewport().add(hm_textPane);
              getContentPane().add(textPane_scrollPane,BorderLayout.CENTER);
              hm_fileChooser=new JFileChooser();
              javax.swing.filechooser.FileFilter hm_filter=new javax.swing.filechooser.FileFilter()
                   public boolean accept(File pathname)
                        if(pathname.isDirectory())
                             return true;
                        String ext_name=pathname.getName().toLowerCase();
                        if(ext_name.endsWith(".htm"))
                             return true;
                        if(ext_name.endsWith(".html"))
                             return true;
                        if(ext_name.endsWith(".asp"))
                             return true;
                        if(ext_name.endsWith(".jsp"))
                             return true;
                        if(ext_name.endsWith(".css"))
                             return true;
                        if(ext_name.endsWith(".php"))
                             return true;
                        if(ext_name.endsWith(".aspx"))
                             return true;
                        if(ext_name.endsWith(".xml"))
                             return true;
                        if(ext_name.endsWith(".txt"))
                             return true;
                        return false;
                   public String getDescription()
                        return "HTML files(*.htm,*.html,*.asp,*.jsp,*.css,*.php,*.aspx,*.xml)";
              hm_fileChooser.setAcceptAllFileFilterUsed(false);
              hm_fileChooser.setFileFilter(hm_filter);
              try
                   File dir=(new File(".")).getCanonicalFile();
                   hm_fileChooser.setCurrentDirectory(dir);
              }catch(IOException ex)
                   showError(ex,"Error openning current directory");
              newDocument();
              WindowListener action_winClose=new WindowAdapter()
                   public void windowClosing(WindowEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              addWindowListener(action_winClose);
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              setVisible(true);
         protected void produceMenuBar()
              hm_menuBar=new JMenuBar();
              hm_toolBar=new JToolBar();
              JMenu menu_file=new JMenu("File");
              menu_file.setMnemonic('f');
              ImageIcon icon_new=new ImageIcon("imgs/file.gif");
              Action action_new=new AbstractAction("New",icon_new)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        newDocument();
              JMenuItem item_new=new JMenuItem(action_new);
              item_new.setMnemonic('n');
              item_new.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_MASK));
              menu_file.add(item_new);
              JButton button_new=hm_toolBar.add(action_new);
              ImageIcon icon_open=new ImageIcon("imgs/folder_open.gif");
              Action action_open=new AbstractAction("Open...",icon_open)
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        openDocument();
              JMenuItem item_open=new JMenuItem(action_open);
              item_open.setMnemonic('o');
              item_open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
              menu_file.add(item_open);
              JButton button_open=hm_toolBar.add(action_open);
              ImageIcon icon_save=new ImageIcon("imgs/floppy.gif");
              Action action_save=new AbstractAction("Save",icon_save)
                   public void actionPerformed(ActionEvent evt)
                        saveAs(false);
              JMenuItem item_save=new JMenuItem(action_save);
              item_save.setMnemonic('s');
              item_save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
              menu_file.add(item_save);
              JButton button_save=hm_toolBar.add(action_save);
              Action action_saveAs=new AbstractAction("Save As...")
                   public void actionPerformed(ActionEvent evt)
                        saveAs(true);
              JMenuItem item_saveAs=new JMenuItem(action_saveAs);
              item_saveAs.setMnemonic('a');
              item_saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_MASK));
              menu_file.add(item_saveAs);
              menu_file.addSeparator();
              Action action_close=new AbstractAction("Quit")
                   public void actionPerformed(ActionEvent evt)
                        if(!promptToSave())
                             return;
                        System.exit(0);
              JMenuItem item_exit=new JMenuItem(action_close);
              item_exit.setMnemonic('q');
              item_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));
              menu_file.add(item_exit);
              hm_menuBar.add(menu_file);
              setJMenuBar(hm_menuBar);
              getContentPane().add(hm_toolBar,BorderLayout.NORTH);
         protected String getDocumentName()
              return current_file==null ? "Untitled" : current_file.getName();
         protected void newDocument()
              html_document=(HTMLDocument)html_kit.createDefaultDocument();
              hm_styleSheet=html_document.getStyleSheet();
              hm_textPane.setDocument(html_document);
              current_file=null;
              setTitle(getDocumentName()+" - "+APP_NAME);
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected void openDocument()
              if(hm_fileChooser.showOpenDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                   return;
              File f=hm_fileChooser.getSelectedFile();
              if(f==null || !f.isFile())
                   return;
              current_file=f;
              setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   InputStream in=new FileInputStream(current_file);
                   html_document=(HTMLDocument)html_kit.createDefaultDocument();
                   html_kit.read(in,html_document,0);
                   hm_styleSheet=html_document.getStyleSheet();
                   hm_textPane.setDocument(html_document);
                   in.close();
              }catch(Exception ex)
                   showError(ex,"Error openning file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              Runnable runner=new Runnable()
                   public void run()
                        text_changed=false;
                        html_document.addDocumentListener(new action_textChanged());
              SwingUtilities.invokeLater(runner);
         protected boolean saveAs(boolean as)
              if(!as && !text_changed)
                   return true;
              if(as || current_file==null)
                   if(hm_fileChooser.showSaveDialog(HTMLMagician.this)!=JFileChooser.APPROVE_OPTION)
                        return false;
                   File f=hm_fileChooser.getSelectedFile();
                   if(f==null || !f.isFile())
                        return false;
                   current_file=f;
                   setTitle(getDocumentName()+" - "+APP_NAME);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              try
                   OutputStream out=new FileOutputStream(current_file);
                   html_kit.write(out,html_document,0,html_document.getLength());
                   out.close();
              }catch(Exception ex)
                   showError(ex,"Error saving file "+current_file);
              HTMLMagician.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              return true;
         protected boolean promptToSave()
              if(!text_changed)
                   return true;
              int result=JOptionPane.showConfirmDialog(this,"Save change to "+getDocumentName(),APP_NAME,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
              switch(result)
                   case JOptionPane.YES_OPTION:
                        if(!saveAs(false))
                             return false;
                        return true;
                   case JOptionPane.NO_OPTION:
                        return true;
                   case JOptionPane.CANCEL_OPTION:
                        return false;
              return true;
         protected void showError(Exception ex,String message)
              ex.printStackTrace();
              JOptionPane.showMessageDialog(this,message,APP_NAME,JOptionPane.WARNING_MESSAGE);
         public static void main(String[] args)
              new HTMLMagician();
         class action_textChanged implements DocumentListener
              public void changedUpdate(DocumentEvent evt)
                   text_changed=true;
              public void insertUpdate(DocumentEvent evt)
                   text_changed=true;
              public void removeUpdate(DocumentEvent evt)
                   text_changed=true;
    when i open a .html file,the command output :
    javax.swing.text.ChangedCharSetException
         at javax.swing.text.html.parser.DocumentParser.handleEmptyTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.startTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseTag(Unknown Source)
         at javax.swing.text.html.parser.Parser.parseContent(Unknown Source)
         at javax.swing.text.html.parser.Parser.parse(Unknown Source)
         at javax.swing.text.html.parser.DocumentParser.parse(Unknown Source)
         at javax.swing.text.html.parser.ParserDelegator.parse(Unknown Source)
         at javax.swing.text.html.HTMLEditorKit.read(Unknown Source)
         at javax.swing.text.DefaultEditorKit.read(Unknown Source)
         at HTMLMagician.openDocument(HTMLMagician.java:222)
         at HTMLMagician$4.actionPerformed(HTMLMagician.java:128)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    why? what's wrong? thanks

    The DocumentParser seems to throw a ChangedCharSetException if it finds a "http-equiv" meta tag for "content-type" or "charset" and if the parser's "ignoreCharSet" property is set to false on creation.

  • Fix for PENDING in javax.swing.text.html.ParagraphView line #131

    Investigating source of HTMLEditorKit I found many PENDING things. That's fix for one of them - proper minimal necessary span detecting in table cells.
    Hope it will help to somebody else.
    import javax.swing.*;
    import javax.swing.text.html.*;
    import javax.swing.text.html.ParagraphView;
    import javax.swing.text.*;
    import java.awt.*;
    import java.text.*;
    import java.util.ArrayList;
    public class App extends JFrame {
        public static String htmlString="<html>\n" +
                "<body>\n" +
                "<p>The following table is used to illustrate the PENDING in javax.swing.text.html.ParagraphView line #131 fix.</p>\n" +
                "<table cellspacing=\"0\" border=\"1\" width=\"50%\" cellpadding=\"3\">\n" +
                "<tr>\n" +
                "<td>\n" +
                "<p>111111111111111111111111111111111<b>bold</b>22222222222222222222222222222</p>\n" +
                "</td>\n" +
                "<td>\n" +
                "<p>-</p>\n" +
                "</td>\n" +
                "</tr>\n" +
                "</table>\n" +
                "<p></p>\n" +
                "</body>\n" +
                "</html>";
        JEditorPane editor=new JEditorPane();
        JEditorPane editor2=new JEditorPane();
        public static void main(String[] args) {
            App app = new App();
            app.setVisible(true);
        public App() {
            super("HTML span fix example");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JSplitPane split=new JSplitPane(JSplitPane.VERTICAL_SPLIT, createFixedPanel(), createOriginalPanel());
            getContentPane().add(split);
            setSize(700, 500);
            split.setDividerLocation(240);
            setLocationRelativeTo(null);
        JComponent createOriginalPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Original HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new HTMLEditorKit();
            editor2.setEditorKit(kit);
            editor2.setContentType("text/html");
            editor2.setText(htmlString);
            p.add(new JScrollPane(editor2), BorderLayout.CENTER);
            return p;
        JComponent createFixedPanel() {
            JPanel p=new JPanel(new BorderLayout());
            p.add(new JLabel("Fixed HTMLEditorKit"), BorderLayout.NORTH);
            HTMLEditorKit kit=new MyHTMLEditorKit();
            editor.setEditorKit(kit);
            editor.setContentType("text/html");
            editor.setText(htmlString);
            p.add(new JScrollPane(editor), BorderLayout.CENTER);
            return p;
    class MyHTMLEditorKit extends HTMLEditorKit {
        ViewFactory defaultFactory=new MyHTMLFactory();
        public ViewFactory getViewFactory() {
            return defaultFactory;
    class MyHTMLFactory extends HTMLEditorKit.HTMLFactory {
        public View create(Element elem) {
            View v=super.create(elem);
            if (v instanceof ParagraphView) {
                v=new MyParagraphView(elem);
            return v;
    class MyParagraphView extends ParagraphView {
        public MyParagraphView(Element elem) {
            super(elem);
        protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
            r = super.calculateMinorAxisRequirements(axis, r);
            float min=getLongestWordSpan();
            r.minimum = Math.max(r.minimum, (int) min);
            return r;
        public float getLongestWordSpan() {
            if (getContainer()!=null && getContainer() instanceof JTextComponent) {
                try {
                    int offs=0;
                    JTextComponent c=(JTextComponent)getContainer();
                    Document doc=getDocument();
                    int start=getStartOffset();
                    int end=getEndOffset()-1; //don't need the last \n
                    String text=doc.getText(start, end - start);
                    if(text.length() > 1) {
                        BreakIterator words = BreakIterator.getWordInstance(c.getLocale());
                        words.setText(text);
                        ArrayList<Integer> wordBounds=new ArrayList<Integer>();
                        wordBounds.add(offs);
                        int count=1;
                        while (offs<text.length() && words.isBoundary(offs)) {
                            offs=words.next(count);
                            wordBounds.add(offs);
                        float max=0;
                        for (int i=1; i<wordBounds.size(); i++) {
                            int wStart=wordBounds.get(i-1)+start;
                            int wEnd=wordBounds.get(i)+start;
                            float span=getLayoutSpan(wStart,wEnd);
                            if (span>max) {
                                max=span;
                        return max;
                } catch (BadLocationException e) {
                    e.printStackTrace();
            return 0;
        public float getLayoutSpan(int startOffset, int endOffset) {
            float res=0;
            try {
                Rectangle r=new Rectangle(Short.MAX_VALUE, Short.MAX_VALUE);
                int startIndex= layoutPool.getViewIndex(startOffset,Position.Bias.Forward);
                int endIndex= layoutPool.getViewIndex(endOffset,Position.Bias.Forward);
                View startView=layoutPool.getView(startIndex);
                View endView=layoutPool.getView(endIndex);
                int x1=startView.modelToView(startOffset,r,Position.Bias.Forward).getBounds().x;
                int x2=endView.modelToView(endOffset,r,Position.Bias.Forward).getBounds().x;
                res=startView.getPreferredSpan(View.X_AXIS)-x1;
                for (int i=startIndex+1; i<endIndex; i++) {
                    res+=layoutPool.getView(i).getPreferredSpan(View.X_AXIS);
                res+=x2;
            } catch (BadLocationException e) {
                e.printStackTrace();
            return res;
    }Regards,
    Stas

    I'm changing the foreground color with
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, newColor);
    int start=MyJTextPane..getSelectionStart();
    int end=MyJTextPane.getSelectionEnd();
    if (start != end) {
    htmlDoc.setCharacterAttributes(start, end, attr, false);
    else {
    MutableAttributeSet inputAttributes =htmlEditorKit.getInputAttributes();
    inputAttributes.addAttributes(attr);   

  • AAARGH!!! Can't understand javax.swing.text.*

    Good afternoon...
    does anybody understand javax.swing.text classes? i've read a number of
    books, downloaded docs (including those from the javax.swing.text author), and googled everything i could think of. but nothing seems to explain it to me so that i can understand it! maybe i'm just dense, but maybe it really is that difficult.
    i want to create a read-only document, who's source is not necessarily a
    string, but perhaps an ArrayList of objects with a HashMap of attributes. or even something simpler for now, just an object with a fixed number of attributes. i want to display this information in a JTextArea. i tried implementing a Document and passing it to the JTextArea constructor but just got a NullPointerException.
    does anybody know where i can find more information on creating my own
    document types?
    here's the code for my ReadOnlyDocument class if anyone of you are generous (& adventurous) enough to take a look:
    import java.util.ArrayList;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.UndoableEditListener;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.Position;
    import javax.swing.text.Segment;
    public class ReadOnlyDocument implements Document{
        private String myContent = "this is the contents of my document!";
        private ArrayList listeners;
        private ReadOnlyDocument refSelf = this;
        public ReadOnlyDocument() {
         System.out.println("ReadOnlyDocument.<init>");
        public int getLength() {
         System.out.println("ReadOnlyDocument.getLength() = " + myContent.length());
            return myContent.length();
        public void addDocumentListener(DocumentListener listener) {
         System.out.println("ReadOnlyDocument.addDocumentListener(" + listener + ")");
            if (listeners != null) {
                listeners = new ArrayList();
                listeners.add(listener);
            } else {
                listeners = new ArrayList();
                listeners.add(listener);
        public void removeDocumentListener(DocumentListener listener) {
         System.out.println("ReadOnlyDocument.removeDocumentListener(" +
    listener + ")");
            if (listeners != null) {
                listeners.remove(listener);
        public void addUndoableEditListener(UndoableEditListener listener) {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.addUndoableEditListener(" +
    listener + ")");
        public void removeUndoableEditListener(UndoableEditListener listener) {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.removeUndoableEditListener(" +
    listener + ")");
        public Object getProperty(Object key) {
            System.out.println("ReadOnlyDocument.getProperty(" + key + ") =
    null");
            return null;
        public void putProperty(Object key, Object value) {
               System.out.println("ReadOnlyDocument.putProperty(" + key + ")");
        public void remove(int offs, int len) throws BadLocationException {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.remove(" + offs + ", " + len +
        public void insertString(int offset, String str, AttributeSet a) throws
    BadLocationException {
            // Read-only document, nothing to do here
         System.out.println("ReadOnlyDocument.insertString(" + offset + ", " +
    str + ", " + a + ")");
        public String getText(int offset, int length) throws
    BadLocationException {
         System.out.print("ReadOnlyDocument.getText(" + offset + ", " + length +
    ") = ");
            if ((offset >= 0) && (length >= 0) && (offset+length <=
    myContent.length()+1)) {
             System.out.println(myContent.substring(offset, offset+length-1));
                return myContent.substring(offset, offset+length-1);
            } else {
             System.out.println("BadLocationException!");
                throw new BadLocationException("Bad location requested", 0);
        public void getText(int offset, int length, Segment txt) throws
    BadLocationException {
         System.out.print("ReadOnlyDocument.getText(" + offset + ", " + length +
    ", " + txt + ") = ");
            if ((offset >= 0) && (length >= 0) && (offset+length <=
    myContent.length()+1)) {
             System.out.println(myContent.substring(offset, offset+length-1));
                txt = new Segment(myContent.toCharArray(), offset, length);
            } else {
             System.out.println("BadLocationException!");
                throw new BadLocationException("Bad location requested", 0);
        public Position getStartPosition() {
         System.out.println("ReadOnlyDocument.getStartPosition() = 0");
      return new Position() {
       public int getOffset() {
        return 0;
        public Position getEndPosition() {
         System.out.println("ReadOnlyDocument.getEndPosition() = " +
    myContent.length());
      return new Position() {
       public int getOffset() {
        return myContent.length();
        public Position createPosition(int offs) throws BadLocationException {
         System.out.println("ReadOnlyDocument.createPosition(" + offs + ") =
    0");
            if ((offs >= 0) && (offs <= myContent.length()-1)) {
       return new Position() {
        public int getOffset() {
         return 0;
      } else {
       throw new BadLocationException("Bad location requested", 0);
        public Element[] getRootElements() {
         System.out.println("ReadOnlyDocument.getRootElements()");
         Element[] roots = {new Element() {
       public Document getDocument() {
        return refSelf;
       public Element getParentElement() {
        return null;
       public String getName() {
        return "ReadOnlyRoot";
       public AttributeSet getAttributes() {
        return null;
       public int getStartOffset() {
        return 0;
       public int getEndOffset() {
        return myContent.length() - 1;
       public int getElementIndex(int offset) {
        return 0;
       public int getElementCount() {
        return 0;
       public Element getElement(int index) {
        return null;
       public boolean isLeaf() {
        return true;
      return roots;
        public Element getDefaultRootElement() {
         System.out.println("ReadOnlyDocument.getDefaultRootElement()");
      return new Element() {
       public Document getDocument() {
        return refSelf;
       public Element getParentElement() {
        return null;
       public String getName() {
        return "ReadOnlyRoot";
       public AttributeSet getAttributes() {
        return null;
       public int getStartOffset() {
        return 0;
       public int getEndOffset() {
        return myContent.length() - 1;
       public int getElementIndex(int offset) {
        return 0;
       public int getElementCount() {
        return 0;
       public Element getElement(int index) {
        return null;
       public boolean isLeaf() {
        return true;
        public void render(Runnable r) {
            // not sure what to put here
         System.out.println("ReadOnlyDocument.render(" + r + ")");
    }and here's a simple class to display the document/generate the error:
    import java.awt.event.*;
    import javax.swing.*;
    public class ReadOnlyFrame extends JFrame {
    public ReadOnlyFrame() {
      super();
      setTitle("Read Only Document");
      addWindowListener(new WindowAdapter() {
       public void windowClosed(WindowEvent e) {
        System.exit(0);
      getContentPane().add(new JTextArea(new ReadOnlyDocument()));
      setSize(200, 200);
    public static void main(String[] args) {
      ReadOnlyFrame rof = new ReadOnlyFrame();
      rof.setVisible(true);
    Headed for the second star to the right and straight on till morning...
    Eric Schultz
    aka: Storkman
    http://community.webshots.com/user/storky1
    mailto:EricSchultzATcanadaDOTcom

    if you are getting that print before the timer
    starts, then I'd expect it's not blocking. The
    problem with these small snippets of code is that we
    can't really tell what might be going on elsewhere.Yes, I realize that. AAMOF, there isn't anything going on elsewhere, i.e.
    the GestureController object spawns another thread when it gets
    created. That other thread blocks until a 'Mover' object is delivered to
    the GestureController object. The mutex/synchronizing stuff works
    like the textbook version, i.e. no deadlock, no deadly embrace, no
    nothing. When the timer is started, the Mover is supposed to
    call back the 'animate' method, just a method in the GestureController
    object.
    All the System.out.prints show that it gets there. The task (an ActionListener)
    dispatched by that timer doesn't start. As you can see above, I've
    used System.out.prints for that too. It is as if that Timer doesn't start.
    I still haven't found anything ... This is what the 'auto.move' thing is
    supposed to do:     static class DragMover implements Mover {
              DrawableStack from;
              DrawableStack to;
              int position;
              DragMover(DrawableStack from, int position, DrawableStack to) {
                   this.from= from;
                   this.to  = to;
                   this.position= position;
              public void move() {
                   System.out.println("moving the stuff...");
                   GestureController.getGestureController().animate(from, position, to);
              public void undo() { }          
         }... the line "moving stuff ..." isn't displayed either, i.e. the actionPerformed
    method is never called and then ... there's nothing in between there, i.e.
    the Timer is supposed to call that method.
    Thank you for your reply, much appreciated and,
    kind regards,
    Jos
    by that timer (an ActionListener)

  • Javax.swing.DefaultPopupFactory serialization error

    Hi,
    I get a java.io.NotSerializableException for the class javax.swing.DefaultPopupFactory this seems to be a private class, because I cannot find anything about it.
    The only swing components I am using are some JFrames with buttons, textfields, etc. and a few dialog boxes via JOptionPane.showMessageDialog(...);
    How do I get rid of this error?
    TIA,
    ablivian23

    This is the single most amazing thread I have ever+* seen.                                                                                                                                                                                                   

  • Help ! inaccurate time recorded using javax.swing.timer

    Hi All,
    I am currently trying to write a stopwatch for timing application events such as loggon, save, exit ... for this I have created a simple Swing GUI and I am using the javax.swing.timer and updating a the time on a Jlabel. The trouble that I am having is that the time is out by up to 20 seconds over a 10 mins. Is there any way to get a more accruate time ?? The code that I am using is attached below.
    private Timer run = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    timeTaken.setText("<html><font size = 5><b>" + (df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds++)) + "</b></font><html>");
    receordedTimeValue = ((df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
    + (df.format(timeSeconds)));
    if (timeSeconds == 60) {
    timeMins++;
    timeSeconds = 0;
    if (timeMins == 60) {
    timeHours++;
    timeMins = 0;

    To get more accurate time you should use the System.currentTimeMillis() method.
    Try this code :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CountUpLabel extends JLabel{
         javax.swing.Timer timer;
         long startTime, count;
         public CountUpLabel() {
              super(" ", SwingConstants.CENTER);
              timer = new javax.swing.Timer(500, new ActionListener() { // less than or equal to 1000 (1000, 500, 250,200,100) 
                   public void actionPerformed(ActionEvent event) {
                        if (startTime == -1) {          
                             count = 0;               
                             startTime = System.currentTimeMillis();
                        else {
                             count = System.currentTimeMillis()-startTime;
                        setText(getStringTime(count));
         private static final String getStringTime(long millis) {
              int seconds = (int)(millis/1000);
              int minutes = (int)(seconds/60);
              int hours = (int)(minutes/60);
              minutes -= hours*60;
              seconds -= (hours*3600)+(minutes*60);
              return(((hours<10)?"0"+hours:""+hours)+":"+((minutes<10)?"0"+minutes:""+minutes)+":"+((seconds<10)?"0"+seconds:""+seconds));
         public void start() {
              startTime = -1;
              timer.setInitialDelay(0);
              timer.start();
         public long stop() {
              timer.stop();
              return(count);
         public static void main(String[] args) {
              JFrame frame = new JFrame("Countdown");
              CountUpLabel countUp = new CountUpLabel();
              frame.getContentPane().add(countUp, BorderLayout.CENTER);
              frame.setBounds(200,200,200,100);
              frame.setVisible(true);
              countUp.start();
    Denis

Maybe you are looking for

  • Driver to have HP Laserjet C4120A (HP Laserjet 4000n) work with Windows 7

    We just put in 28 new Dell OptiPlex 3030 AIO with Windows 7 Professional in a school computer lab - but the tech guy did not install a printer for it to print to because he says our current printer - an HP Laserjet 4000n (C4120A) - is too old and wil

  • BO WebI Report Issue

    Hi , We are using Greenplum + BO , We can able to connect the BO with greenplum in Universe. While we connect to the Webi we are getting the below attached issue , Please help us to resolve.

  • 6.1.2 update bricked my iPad Mini - White Screen of Death

    I updated to 6.1.2 over wireless.  Shortly after, I noticed the battery was draining extremely fast.  I followed a suggestion I found here to let the battery drain to 0 and to reset my settings under Settings>General.  When the battery was about 50%,

  • Obtain Ip address of hand held terminal

    Hi all.. We are writing an application for hand held terminals. We are using PDT6846. The HHT application runs on a solaris machine from where the requests are routed to the server. Individual users connect to the HHT application through telnet. Ther

  • Photoshop elements plug-in

    After installing the latest upgrade to PS Elements (13.1), the plug-in for Lightroom loads the previous version of the PSE Editor (13.0).  If I load directly, I get the new 13.1 version.  Applications folder shows the new 13.1 folders and the new ver