JMenuBar setFont problem.

Hi, I'm trying to change font for my menu bar, but it takes no effect.
Actually, my purpose is to set normal(not bold) font for menu.
Code:
JMenuBar menu=new JMenuBar();
menu.setFont(new Font("Serif", Font.PLAIN, 12));
//Adding menu items to the menubar.
I have tried to change font of menu items but it took no effect either.
Can anybody help me?
Thanks.

Setting the font on the individual menu items should hve worked unless you don't have the specified font installed on your sytem.
However, if you want to change the font globally, use
UIManager.put(MenuItem.font, yourFont);
UIManager.put(Menu.font, yourFont);
This will change the fonts for all menus and menu items to whatever font you specify.
Sai Pullabhotla

Similar Messages

  • Urgent : JMenuBar repaint problem

    hello all,
    i'm facing a problem with jmenubar. i have developed an applet which contains a jmenubar, toolbaar & a panel. i'm doing some operation on the panel like rotating it by different angles. these operations are given in the menu. i have given accelerator keys for these menuitems. when i operate with these accelerator keys everything works fine. but when i click on the menuitem then a part of the panel gets panited on the menubar. but when i minimize the window & open it again the extra portion on the menubar disappears. can u suggest me what might be the problem with this. what is happening when we click a menuitem?
    any help is appreciated.
    Thanks in advance

    i solved it by changing repaint() into revalidate() & paintImmediately()
    i didn't get the reason why this works instead of repaint but now the code is working perfectly.
    This was the 1st time i did a cross posting. I had to deliver the solution that day itself that's why i posted it on different forms. i thought some experts will check the forms which they r interested. anyway learned a lesson from this. won't repeat it.

  • Vertical JMenuBar width problem

    When I flip my JMenuBar vertical instead of horizontal by doing
    BoxLayout bl = new BoxLayout(this,BoxLayout.PAGE_AXIS);
    setLayout(bl);
    in a constructor for a class that extends JMenuBar. When I do that only 3 characters of each JMenu in the menubar are show. The button size is also ruffly half the width of the actual window. I am doing pack() on the JFrame that houses the JMenuBar. At the moment nothing else is in the JFrame. If I do not set the layout of my JMenuBar then I get a regular horizontal one and width is fine. It's only when I want the Menus vertical instead of horizontal. Been experimenting with all kinds of stuff and no go so far. Looking for suggestions?

    this produces a menubar, with the screen items vertical, but it takes up too much real estate
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(400,200);
        JMenu file = new JMenu("File");
        JMenuItem newItem = new JMenuItem("New");
        JMenuItem open = new JMenuItem("Open");
        JMenuItem preview = new JMenuItem("Preview");
        JMenuItem print = new JMenuItem("Print");
        JMenuItem exit = new JMenuItem("Exit");
        file.add(newItem);
        file.add(open);
        file.add(new JSeparator());
        file.add(preview);
        file.add(print);
        file.add(new JSeparator());
        file.add(exit);
        JMenu options = new JMenu("Options");
        JMenuItem font = new JMenuItem("Font");
        JMenuItem color = new JMenuItem("Color");
        options.add(font);
        options.add(color);
        JMenuBar menuBar = new JMenuBar();
        menuBar.setLayout(new GridLayout(0,1));
        menuBar.add(file);
        menuBar.add(options);
        setJMenuBar(menuBar);
        getContentPane().add(new JTextArea(5,20));
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Problems getting data from JMenuBar to JInternalFrame

    I have modified an example to show my problem. I am trying to take text input from the menu bar and print it into a JTextArea. I don't know how to reference the data in my ActionListener.
    The ActionListener is incomplete, but this is basically what I am trying to do:
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * InternalFrameDemo.java is a 1.4 application that requires:
    *   MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
                                   implements ActionListener {
        JDesktopPane desktop;
        JTextField memAddrBox;
        JTextArea menuText;
        JTextArea frame;
        String textFieldString = " Input Text: ";
        ActionListener al;
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            frame = createFrame(); //create first "window"
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        protected JMenuBar createMenuBar() {
            JMenuBar menuBar = new JMenuBar();
            JLabel memAddrLabel = new JLabel(textFieldString);
            memAddrLabel.setLabelFor(memAddrBox);
            menuBar.add(memAddrLabel);
            JTextField memAddrBox = new JTextField();
            memAddrBox.addActionListener(this);
            memAddrBox.setActionCommand("chMemAddr");
            menuBar.add(memAddrBox);
            return menuBar;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("chMemAddr".equals(e.getActionCommand())) 
                JMenuBar bar = getJMenuBar();
    //            JTextField memAddrBox = bar.getParent();
                String memStartString = memAddrBox.getText();
                update(memStartString);
        public void update(String temp)
            frame.setText(temp);
        //Create a new internal frame.
        protected JTextArea createFrame() {
            JInternalFrame frame = new JInternalFrame("Memory",true,true,true,true);      
            frame.setSize(650, 500);
            frame.setVisible(true);
            frame.setLocation(200, 0);
            desktop.add(frame);  
            JTextArea textArea = new JTextArea();
            frame.getContentPane().add("Center", textArea);
            textArea.setFont(new Font("SansSerif", Font.PLAIN, 12));
            textArea.setVisible(true);
            textArea.setText("Initial Text");
            return textArea;
        //Quit the application.
        protected void quit() {
            System.exit(0);
        public static void main(String[] args) {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            InternalFrameDemo frame = new InternalFrameDemo();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
    class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 30, yOffset = 30;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I want to take the input from the "memAddrBox" and put it into the "frame" using the update() method. Probably a simple solution, but I have not found a similar problem in the Forums.

    I knew it had to be something simple, here is the fix I found:
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    * InternalFrameDemo.java is a 1.4 application that requires:
    *   MyInternalFrame.java
    public class InternalFrameDemo extends JFrame
                                   implements ActionListener {
        JDesktopPane desktop;
        JTextField memAddrBox;
        JTextArea menuText;
        JTextArea frame;
        String textFieldString = " Input Text: ";
        ActionListener al;
        public InternalFrameDemo() {
            super("InternalFrameDemo");
            //Make the big window be indented 50 pixels from each edge
            //of the screen.
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            //Set up the GUI.
            desktop = new JDesktopPane(); //a specialized layered pane
            frame = createFrame(); //create first "window"
            setContentPane(desktop);
            setJMenuBar(createMenuBar());
            //Make dragging a little faster but perhaps uglier.
            desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        protected JMenuBar createMenuBar() {
            JMenuBar menuBar = new JMenuBar();
            JLabel memAddrLabel = new JLabel(textFieldString);
            memAddrLabel.setLabelFor(memAddrBox);
            menuBar.add(memAddrLabel);
            JTextField memAddrBox = new JTextField();
            memAddrBox.addActionListener(this);
            memAddrBox.setActionCommand("chMemAddr");
            menuBar.add(memAddrBox);
            return menuBar;
        //React to menu selections.
        public void actionPerformed(ActionEvent e) {
            if ("chMemAddr".equals(e.getActionCommand())) 
               JTextField textField =
                 (JTextField)e.getSource();
                String memStartString = textField.getText();
                update(memStartString);
        public void update(String temp)
            frame.setText(temp);
        //Create a new internal frame.
        protected JTextArea createFrame() {
            JInternalFrame frame = new JInternalFrame("Memory",true,true,true,true);      
            frame.setSize(650, 500);
            frame.setVisible(true);
            frame.setLocation(200, 0);
            desktop.add(frame);  
            JTextArea textArea = new JTextArea();
            frame.getContentPane().add("Center", textArea);
            textArea.setFont(new Font("SansSerif", Font.PLAIN, 12));
            textArea.setVisible(true);
            textArea.setText("Initial Text");
            return textArea;
        //Quit the application.
        protected void quit() {
            System.exit(0);
        public static void main(String[] args) {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            InternalFrameDemo frame = new InternalFrameDemo();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display the window.
            frame.setVisible(true);
    class MyInternalFrame extends JInternalFrame {
        static int openFrameCount = 0;
        static final int xOffset = 30, yOffset = 30;
        public MyInternalFrame() {
            super("Document #" + (++openFrameCount),
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  true);//iconifiable
            //...Create the GUI and put it in the window...
            //...Then set the window size or call pack...
            setSize(300,300);
            //Set the window's location.
            setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }Note the e.getSource() change in the ActionListener.

  • AffineTransform problem caused by JMenuBar + JTabbedPane

    Hello everyone.
    I am starting to think that there is a bug in Java, because otherwise what else could cause the problem I am experiencing? Namely: adding a panel with a vertical text (like a Y axis caption) using an AffineTransform (see SSCCE below) causes this text to be misplaced in some cases.
    Variant A
    Panel is added directly to the application frame. This causes no problems and everything is as it should be.
    Variant B
    Panel is placed on a tabbed pane and a menu bar is associated with the frame. The vertical text is now shifted away from the place where it should be by the height of the menu bar plus the height of tabs on the tabbed pane. Why is this happening? Am I doing something wrong?
    Moreover, when one switches to another tab and then back, the text is now shifted only by the height of the tabs. Once the application window is resized at least a bit, the text jumps right back to the position shifted by tab height plus menu bar height... Strange, strange, strange...
    SSCCE
    import java.awt.*;
    import java.awt.font.FontRenderContext;
    import java.awt.geom.*;
    import javax.swing.*;
    class MyPanel extends JPanel {
        MyPanel() {
            this.setPreferredSize(new Dimension(300, 200));
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2D = (Graphics2D)g;
            int g2DWidth = this.getWidth();
            int g2DHeight = this.getHeight();
            // Horizontal line in the middle of the panel (indicates the position
            // where the middle of the vertical label should be)
            g2D.drawLine(30, (int)(g2DHeight / 2), g2DWidth - 10,
                    (int)(g2DHeight / 2));
            // Vertical label
            AffineTransform origTransform = g2D.getTransform();
            AffineTransform rotate = AffineTransform.getRotateInstance(
                    -Math.PI / 2.0, 0, 0);
            g2D.setTransform(rotate);
            String text = "Centered?";
            FontRenderContext frc = g2D.getFontRenderContext();
            Font font = UIManager.getFont("Label.font");
            Rectangle2D bounds = font.getStringBounds(text, frc);
            g2D.drawString(text, -(int)((g2DHeight + bounds.getWidth()) / 2), 20);
            g2D.setTransform(origTransform);
    class Main {
        private static void createAndShowGUI() {
            // Menu bar
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("Menu");
            JMenuItem menuItem = new JMenuItem("Menu Item");
            menu.add(menuItem);
            menuBar.add(menu);
            // Tabbed pane
            JTabbedPane tabbedPane = new JTabbedPane();
            JPanel panel = new MyPanel();
            tabbedPane.add(panel);
            JLabel label = new JLabel("Nothing interesting's going on here...");
            tabbedPane.add(label);
            // Frame
            JFrame frame = new JFrame();
            // TRICKY PART HERE =========================================
            // [(Un)comment lines as necessary]
            // Variant A: the panel only --------------------------------
            //frame.add(panel);
            // Variant B: menu bar + panel on a tabbed pane -------------
            frame.setJMenuBar(menuBar);
            frame.add(tabbedPane);
            // ==========================================================
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Thanks for any help.
    Best regards,
    vt
    Edited by: -vt- on 23-Apr-2010 13:08

    You are ignoring the current transform on the Graphics, use the following instead of setTransform():
    g2D.rotate(-Math.PI / 2.0, 0, 0);

  • JMenuBar and JButton problem

    The problem is a simple one.
    Simply I don't know how to have the two together, every time I try to create a contentPane with the buttons in it I always get errors I would love it if some one could show me how to do this.
    Thanx

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        JMenuBar jmb = new JMenuBar();
        setJMenuBar(jmb);
        JMenu jm = new JMenu("Menu");
        jmb.add(jm);
        for (int i=0; i<5; i++) {
          JMenuItem jmi = new JMenuItem("MenuItem-"+i);
          jm.add(jmi);
          jmi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              System.out.println(((JMenuItem)ae.getSource()).getText());
          JButton jb = new JButton("Button-"+i);
          content.add(jb);
          jb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              System.out.println(((JButton)ae.getSource()).getText());
        setSize(200,400);
        show();
      public static void main(String[] args) { new Test(); }
    }

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • JMenubar inside Tabbedpane problem

    Hi,
    I have a tabbed pane having gridbag layout has following components
    Tab1
    panelmenubar|
    paneltoolbar |
    splitpane |
    |
    |
    panelstatusbar |
    The problem is when I maximize the frame I can see menubar but when I minimize the window it's becomes almost a thin line.
    here is the code i am using,
        jPanelMain.setLayout(new java.awt.GridBagLayout());
        java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();   
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanelMain.add(jPanelMenuBar, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanelMain.add(jPanelToolBar, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanelMain.add(splitPane, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanelMain.add(jPanelStatusBar, gridBagConstraints);   
        jTabbedPaneMain.insertTab(" DIRECT ", null, jPanelMain, "DIRECT", 0);
        jTabbedPaneMain.insertTab(" GLOBAL-US ", null, new JPanel(), "GLOBAL-US", 1);
        jTabbedPaneMain.insertTab(" GLOBAL-CAN ", null, new JPanel(), "GLOBAL-CAN", 2);
        this.getContentPane().add(jTabbedPaneMain, java.awt.BorderLayout.CENTER);
        this.pack();
        refreshScreen();
        this.setVisible(true);
        this.setExtendedState(this.MAXIMIZED_BOTH);Please advise.
    Thanks
    Sat'n

    Sorry to bother I got the answer, somewhere I was setting jpanel size. After removing that it worked.
    Thanks

  • Problem with menu and panel

    hi,
    i m new to java still learning new concepts. When i was working with menu and panel i got this problem and i tried a lot but still i havn't got any success. the problem is i m creating a menu with two menuitem - one for "add item" and another for "modify item". What i want to do that on the same frame i want to create two panel of these two item. when i click "add item" option it should show add window and so with modify option. but the problem is if i click add item it shows the addpanel but when i click modify option (add item panel goes- ok ..) but it doesn't show the modify panel, it shows only the main frame on which menu is there.
    i cannot understant what is happing here plz guide me.
    thanx

    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    public class ajitAutomobile extends JFrame implements ActionListener
         JMenuBar mb;
         JMenu jobmenu;
         JMenuItem newJobCard,modifyJobCard;
         Font ft;
         JPanel pnlnewJobCard,pnlmodifyJobCard;
         Container con;
         ajitAutomobile()
         ft=new Font("Arial",0,12);
         mb=new JMenuBar();
         setJMenuBar(mb);
         jobmenu=new JMenu(" Job Card Form");
         mb.add(jobmenu).setFont(ft);
         newJobCard=new JMenuItem("New Job Card Detail");
         modifyJobCard=new JMenuItem("Modify Job Card Detail");
         jobmenu.add(newJobCard).setFont(ft);     
         jobmenu.add(modifyJobCard).setFont(ft);     
         mb.add(requisition).setFont(ft);
         con=getContentPane();
         // setting panel for new JOb Card Entry
         pnlnewJobCard=new JPanel();
         pnlmodifyJobCard=new JPanel();
         con.add(pnlmodifyJobCard);
         con.add(pnlnewJobCard);
         pnlnewJobCard.setBackground(Color.RED);     
         pnlnewJobCard.setVisible(false);
         pnlmodifyJobCard.setBackground(Color.YELLOW);
         pnlmodifyJobCard.setVisible(false);
         //setting JFrame resources
         setVisible(true);
         setTitle("Ajit Automobile Service Center");
         setSize(750,300);
         setResizable(false);
         newJobCard.addActionListener(this);
         modifyJobCard.addActionListener(this);
         public void actionPerformed(ActionEvent ae)
              if (ae.getSource()==newJobCard)
                   pnlnewJobCard.setVisible(true);
                                                                    pnlmodifyJobCard.setVisible(false);
              if(ae.getSource()==modifyJobCard)
                                                                             pnlnewJobCard.setVisible(false);
                                                                    pnlmodifyJobCard.setVisible(true);
         public static void main(String args[])
         ajitAutomobile objajit=new ajitAutomobile();
         objajit.show();
    }so, this is the code and as i m expecting that when i click on "New Job Card Detail" then it should display pnlnewJobCard and when i will click "Modify Job Card Detail" it should display pnlmodifyJobCard panel but it is not working.It shows only that panel which is clicked first.
    plz help
    thnx, any answer will be appriciated.

  • JCombobox with JMenuBar (as drop down menu)

    Hello, i'm trying to make a new component (as generic as possible) to display a tree structure in a combo-like style.
    So i finally choose a JTextfield to display the current item + a JMenuBar with Menu and MenuItem generated from a TreeModel (i'm not sure this is the better choice to make, but tha's not my present problem).
    2 questions :
    1) am I reinventing the wheel ???
    2) i've got a problem of pack when displaying the compent and i don't find where.
    Thanks. Cyril.
    So, the code... two main classes : TreeComboBox + ArrowMenu
    the TreeComboBox :
    package fr.emanation.util.gui.treeComboBox;
    import javax.swing.*;
    import javax.swing.tree.TreeModel;
    import java.awt.*;
    import java.awt.event.FocusListener;
    public class TreeComboBox<TNode> extends JPanel
      private TNode theSelectedNode;
      private ArrowMenuBar theMenuBar;
      private JTextField theTextField;
      private int theCompactWidth;
      public TreeComboBox(TreeModel aTreeModel)
        new BorderLayout(0, 0);
        theTextField = new JTextField();
        theTextField.setEditable(true);
        theTextField.setBackground(Color.white);
        setFocusable(false);
        add(theTextField, BorderLayout.CENTER);
        MyArrowMenuInvoker anInvoker = new MyArrowMenuInvoker();
        theMenuBar = new ArrowMenuBar<TNode>(anInvoker, aTreeModel);
        JPanel menuBarPanel = new JPanel(new BorderLayout(0, 0));
        menuBarPanel.add(theMenuBar, BorderLayout.CENTER);
        add(menuBarPanel, BorderLayout.EAST);
      public TNode getNode()
        return (TNode) theSelectedNode;
      public void setSelectedNode(TNode aNode)
        theSelectedNode = aNode;
        theTextField.setText(aNode.toString());
      public TreeModel getModel()
        return theMenuBar.getModel();
      public JComponent[] getFocusableComponents()
        return new JComponent[]{theTextField, theMenuBar};
      //-- JComponent overriden methods
      public Dimension getMinimumSize()
        final Dimension minSize = super.getMinimumSize();
        minSize.width = theCompactWidth;
        return minSize;
      public void setCompactWidth(final int aCompactWidth)
        theCompactWidth = aCompactWidth;
      public void setPreferredSize(Dimension aSize)
        super.setPreferredSize(aSize);
        if (theTextField != null)
          theTextField.setPreferredSize(aSize);
      public void setForeground(Color fg)
        super.setForeground(fg);
        if (theMenuBar != null)
          for (int index = 0; index < theMenuBar.getComponentCount(); index++)
            theMenuBar.getComponents()[index].setForeground(fg);
        if (theTextField != null)
          theTextField.setForeground(fg);
      public void setBackground(Color bg)
        super.setBackground(bg);
        if (theMenuBar != null)
          for (int index = 0; index < theMenuBar.getComponentCount(); index++)
            theMenuBar.getComponents()[index].setBackground(bg);
        if (theTextField != null)
          theTextField.setBackground(bg);
      public void setFont(Font aFont)
        super.setFont(aFont);
        if (theMenuBar != null)
          theMenuBar.setFont(aFont);
        if (theTextField != null)
          theTextField.setFont(aFont);
      public void setToolTipText(String aToolTip)
        super.setToolTipText(aToolTip);
        if (theTextField != null)
          theTextField.setToolTipText(aToolTip);
      public void setEnabled(final boolean bEnabled)
        super.setEnabled(bEnabled);
        if (theTextField != null) return;
          theTextField.setEnabled(bEnabled);
          if (bEnabled)
            theTextField.setBackground(Color.WHITE);
          else
            JLabel tmpLabel = new JLabel();
            tmpLabel.setEnabled(false);
            theTextField.setBackground(tmpLabel.getBackground());
        if (theMenuBar != null)
          theMenuBar.setEnabled(bEnabled);
      public synchronized void addFocusListener(FocusListener l)
        super.addFocusListener(l);
        if (theMenuBar != null)
          theMenuBar.addFocusListener(l);
        if (theTextField != null)
          theTextField.addFocusListener(l);
      public synchronized void removeFocusListener(FocusListener l)
        super.removeFocusListener(l);
        if (theMenuBar != null)
          theMenuBar.removeFocusListener(l);
        if (theTextField != null)
          theTextField.removeFocusListener(l);
      public boolean isFocusOwner()
        if (theMenuBar == null || theTextField == null) return super.isFocusOwner();
        boolean bM = (theMenuBar == null) && theMenuBar.isFocusOwner();
        boolean bT = (theTextField == null) && theTextField.isFocusOwner();
        return (bM || bT);
      //-- inner classes
      private class MyArrowMenuInvoker implements IArrowMenuInvoker<TNode>
        public Component getComponent()
          return theTextField;
        public void setNode(TNode aNode)
          setSelectedNode(aNode);
    }the ArrowMenuBar :
    package fr.emanation.util.gui.treeComboBox;
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import javax.swing.plaf.UIResource;
    import javax.swing.tree.TreeModel;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ArrowMenuBar<TNode> extends JMenuBar
      private NodeMenu theMenu;
      private TreeModel theModel;
      private IArrowMenuInvoker<TNode> theInvoker;
      public ArrowMenuBar(IArrowMenuInvoker<TNode> anInvoker, TreeModel aModel)
        super();
        theModel = aModel;
        theInvoker = anInvoker;
        TNode root = (TNode) theModel.getRoot();
        if (!theModel.isLeaf(root))
          theMenu = new ArrowMenu(root);
          theMenu.setBackground(new JPanel().getBackground());
        MenuItemListener listener = new MenuItemListener();
        setListener(theMenu, listener);
        add(theMenu);
      private void setListener(JMenuItem anItem, ActionListener aListener)
        if (anItem instanceof JMenu)
          JMenu menu = (JMenu) anItem;
          int n = menu.getItemCount();
          for (int index = 0; index < n; index++)
            setListener(menu.getItem(index), aListener);
        else if (anItem != null)
          // null means separator
          anItem.addActionListener(aListener);
      public TreeModel getModel()
        return theModel;
      public Action getLaunchArrowMenuBarAction()
        return new LaunchArrowMenuBarAction();
      //-- overrides JComponent
      public Dimension getPreferredSize()
        return theMenu.getPreferredSize();
      private Dimension getItemSize(JMenu aMenu)
        Dimension dimension = new Dimension(0, 0);
        int n = aMenu.getItemCount();
        for (int index = 0; index < n; index++)
          Dimension itemD;
          JMenuItem item = aMenu.getItem(index);
          if (item instanceof JMenu)
            itemD = getItemSize((JMenu) item);
          else if (item != null)
            itemD = item.getPreferredSize();
          else
            itemD = new Dimension(0, 0); // separator
          dimension.width = Math.max(dimension.width, itemD.width);
          dimension.height = Math.max(dimension.height, itemD.height);
        return dimension;
      //--- inner classes
      private class LaunchArrowMenuBarAction extends AbstractAction
        public LaunchArrowMenuBarAction()
          super("...");
        public void actionPerformed(ActionEvent e)
          if (e.getActionCommand() == "Launch")
            System.out.println("Launch");
      private class MenuItemListener implements ActionListener
        public void actionPerformed(ActionEvent anEvent)
          NodeMenuItem item = (NodeMenuItem) anEvent.getSource();
          theInvoker.setNode(item.getNode());
          theMenu.requestFocus();
      private class NodeMenu extends JMenu
        private TNode theNode;
        public NodeMenu(TNode aNode)
          this(aNode.toString(), aNode);
        public NodeMenu(String theText, TNode aNode)
          super(theText);
          theNode = aNode;
          add(new NodeMenuItem("[.]", aNode));
          for (int index = 0; index < theModel.getChildCount(aNode); index++)
            TNode childNode = (TNode) theModel.getChild(aNode, index);
            if (theModel.isLeaf(childNode))
              add(new NodeMenuItem(childNode));
            else
              add(new NodeMenu(childNode));
        public void setNode(TNode aNode)
          theNode = aNode;
        public TNode getNode()
          return theNode;
      private class NodeMenuItem extends JMenuItem
        private TNode theNode;
        public NodeMenuItem(TNode aNode)
          super(aNode.toString());
          theNode = aNode;
        public NodeMenuItem(String aText, TNode aNode)
          super(aText);
          theNode = aNode;
        public TNode getNode()
          return theNode;
      private class ArrowMenu extends NodeMenu
    //    private ArrowIcon theIconRenderer;
        private Color shadow = UIManager.getColor("controlShadow");
        private Color darkShadow = UIManager.getColor("controlDkShadow");
        private Color highlight = UIManager.getColor("controlLtHighlight");
        public ArrowMenu(TNode aNode)
          super("", aNode);
    //      theIconRenderer = new ArrowIcon(SwingConstants.SOUTH, true);
          setBorder(new EtchedBorder());
    //      setIcon(new BlankIcon(null, 11));
          setHorizontalTextPosition(JButton.LEFT);
          setFocusPainted(true);
        public void paint(Graphics g)
          Color origColor;
          boolean isEnabled;
          int w, h, size;
          w = getSize().width;
          h = getSize().height;
          origColor = g.getColor();
          isEnabled = isEnabled();
          g.setColor(getBackground());
          g.fillRect(1, 1, w - 2, h - 2);
          /// Draw the proper Border
          if (getBorder() != null && !(getBorder() instanceof UIResource))
            paintBorder(g);
          else
            // Using the background color set above
            g.drawLine(0, 0, 0, h - 1);
            g.drawLine(1, 0, w - 2, 0);
            g.setColor(highlight);  // inner 3D border
            g.drawLine(1, 1, 1, h - 3);
            g.drawLine(2, 1, w - 3, 1);
            g.setColor(shadow);     // inner 3D border
            g.drawLine(1, h - 2, w - 2, h - 2);
            g.drawLine(w - 2, 1, w - 2, h - 3);
            g.setColor(darkShadow);   // black drop shadow  __|
            g.drawLine(0, h - 1, w - 1, h - 1);
            g.drawLine(w - 1, h - 1, w - 1, 0);
          // If there's no room to draw arrow, bail
          if (h < 5 || w < 5)
            g.setColor(origColor);
            return;
          // Draw the arrow
          size = Math.min((h - 4) / 3, (w - 4) / 3);
          size = Math.max(size, 2);
          paintTriangle(g, (w - size) / 2, (h - size) / 2,
                  size, SwingConstants.SOUTH, isEnabled);
          // Reset the Graphics back to it's original settings
          g.setColor(origColor);
        public Dimension getPreferredSize()
          return new Dimension(16, 16);
        public Dimension getMinimumSize()
          return new Dimension(5, 5);
        public Dimension getMaximumSize()
          return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
        public void paintTriangle(Graphics g, int x, int y, int size,
                      int direction, boolean isEnabled)
          Color oldColor = g.getColor();
          int mid, i, j;
          j = 0;
          size = Math.max(size, 2);
          mid = (size / 2) - 1;
          g.translate(x, y);
          if (isEnabled)
            g.setColor(darkShadow);
          else
            g.setColor(shadow);
          switch (direction)
            case NORTH:
              for (i = 0; i < size; i++)
                g.drawLine(mid - i, i, mid + i, i);
              if (!isEnabled)
                g.setColor(highlight);
                g.drawLine(mid - i + 2, i, mid + i, i);
              break;
            case SOUTH:
              if (!isEnabled)
                g.translate(1, 1);
                g.setColor(highlight);
                for (i = size - 1; i >= 0; i--)
                  g.drawLine(mid - i, j, mid + i, j);
                  j++;
                g.translate(-1, -1);
                g.setColor(shadow);
              j = 0;
              for (i = size - 1; i >= 0; i--)
                g.drawLine(mid - i, j, mid + i, j);
                j++;
              break;
            case WEST:
              for (i = 0; i < size; i++)
                g.drawLine(i, mid - i, i, mid + i);
              if (!isEnabled)
                g.setColor(highlight);
                g.drawLine(i, mid - i + 2, i, mid + i);
              break;
            case EAST:
              if (!isEnabled)
                g.translate(1, 1);
                g.setColor(highlight);
                for (i = size - 1; i >= 0; i--)
                  g.drawLine(j, mid - i, j, mid + i);
                  j++;
                g.translate(-1, -1);
                g.setColor(shadow);
              j = 0;
              for (i = size - 1; i >= 0; i--)
                g.drawLine(j, mid - i, j, mid + i);
                j++;
              break;
          g.translate(-x, -y);
          g.setColor(oldColor);
    }

    Darkness and blindness are away !
    First line of the constructor :
    public TreeComboBox(TreeModel aTreeModel)
        new BorderLayout(0, 0);
    }I will reborn as a pumpkin !

  • Scroll bar problems ..Please help!!!!!!

    This is what the program looks like. topPanel has newItemPanel on top of it. when you click continue newItemPanel becomes invisible and newItemDescriptionPanel becomes visible. When you click continue newItemDescriptionPanel becomes invisible and priceEnterPanel becomes visible.
    I want newItemDescriptionPanel and priceEnterPanel to have a scroll bar. but everything I have tried hasn't worked. I am new. You will see the code is ugly and there is an attempt to add a scrollbar.
    Please help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.lang.System;
    public class MainPanel extends      JFrame implements     ActionListener
         private boolean      firstRun = true;
         private final int     ITEM_PLAIN     =     0;     // Item types
         private final int     ITEM_CHECK     =     1;
         private final int     ITEM_RADIO     =     2;
         private     JPanel          topPanel;
         private JPanel          newItemPanel;
         private JRadioButton onlineAuctionRadio;
         private JRadioButton fixedPriceRadio;
         private ButtonGroup bg;
         private JButton     continueButton;
         private JLabel      blankLabel;       //used to give space between things
         private JPanel           newItemDescriptionPanel;
         private JPanel      takeAdditionalSpacePanelCheckBox;
         private JPanel      takeAdditionalSpacePanel;
         private JPanel          takeAdditionalSpacePanelLabel;
         private JPanel          takeAdditionalSpacePanelLabel2;
         private JPanel      takeAdditionalSpacePanel2;
         private JPanel      takeAdditionalSpacePanel3;
         private JPanel           takeAdditionalSpacePanel4;
         private JPanel           takeAdditionalSpacePanel5;
         JScrollPane displayScroller;
         JEditorPane itemDescriptionTextArea;
         GridBagLayout gridbag;
         GridBagConstraints gbc;
         private JCheckBox   secondCategoryCheckBox;
         private JLabel          itemTitleLabel;
         private JLabel          requiredLabel, requiredLabel2;
         private JLabel      requiredStarLabel;
         private JTextField  itemTitleTextField;
         private JLabel           subtitleLabel;
         private JTextField      subtitleTextField;
         private JLabel          itemDescriptionLabel;
         private JButton     itemDescriptionContinueButton;
         private JLabel          percentageLabel;
         //------- price enter page ----------------
         private JLabel          startingPriceLabel;
         private JLabel           dollarSignLabel;
         private JTextField     startingPriceTextField;
         private JPanel          fillUpSpacePanel;
         private JPanel          fillUpSpacePanel1;
         private JPanel          fillUpSpacePanel2;
         private JLabel          buyItNowLabel;
         private JPanel          fillUpSpacePanel3;
         private JLabel          dollarSignLabel2;
         private JTextField     buyItNowTextField;
         private JPanel          fillUpSpacePanel4;
         private JPanel          fillUpSpacePanel5;
         private JPanel          fillUpSpacePanel6;
         private JPanel          fillUpSpacePanel7;
         private JPanel          fillUpSpacePanel8;
         private JPanel          fillUpSpacePanel9;
         private JPanel          fillUpSpacePanel10;
         private JPanel          fillUpSpacePanel11;
         private JPanel          fillUpSpacePanel12;
         private JPanel          fillUpSpacePanel13;
         private JPanel          fillUpSpacePanel14;
         private JPanel          fillUpSpacePanel15;
         private JPanel          fillUpSpacePanel16;
         private JPanel          fillUpSpacePanel17;
         private JPanel          fillUpSpacePanel18;
         private JLabel          donatePercentageLabel;
         private JTextField     donatePercentageTextField;
         private JPanel          fSp; // fill space panel
         private JPanel          fSp1;
         private JPanel          fSp2;
         private JPanel          fSp3;
         private JPanel          fSp4;
         private JPanel          fSp5;
         private JPanel          fSp6;
         private JPanel          fSp7;
         private JPanel          fSp8;
         private JPanel          fSp9;
         private JLabel           numberOfPicturesLabel;
         private JTextField     numberOfPicturesTextField;
         private JCheckBox     superSizePicturesCheckBox;
         private JLabel          superSizePicturesLabel;
         private JRadioButton standardPictureRadioButton;
         private JRadioButton picturePackRadioButton;
         private JCheckBox     listingDesignerCheckBox;
         private ButtonGroup bgPictures;
         private JCheckBox      valuePackCheckBox;
         private JCheckBox     galleryPictureCheckBox;
         private JCheckBox     subtitleCheckBox;
         private JCheckBox     boldCheckBox;
         private JCheckBox     borderCheckBox;
         private JCheckBox     highlightCheckBox;
         private JCheckBox     featuredPlusCheckBox;
         private JCheckBox     galleryFeaturedCheckBox;
         private JLabel          homePageFeaturedLabel;
         private JComboBox     homePageFeaturedComboBox;
         private JCheckBox     giftCheckBox;
         JScrollPane priceEnterPanelScroll;
         private JButton          backToRadioButton;
         private JButton          backToItemDescriptionButton;
         private JPanel           priceEnterPanel;
         private final static String RADIOPANEL = "JPanel with radios";
         private final static String DESCRIPTIONPANEL = "JPanel with description";
         private final static String PRICEENTERPANEL = "JPanel with price entering";
         private JPanel           cards;
         private     JMenuBar     menuBar;
         private     JMenu          menuFile;
         private     JMenu          menuEdit;
         private     JMenu          menuProperty;
         private     JMenuItem     menuPropertySystem;
         private     JMenuItem     menuPropertyEditor;
         private     JMenuItem     menuPropertyDisplay;
         private     JMenu        menuFileNew;
         private JMenuItem   menuFileNewAccount;
         private JMenuItem   menuFileNewItem;
         private     JMenuItem     menuFileOpen;
         private     JMenuItem     menuFileSave;
         private     JMenuItem     menuFileSaveAs;
         private     JMenuItem     menuFileExit;
         private     JMenuItem     menuEditCopy;
         private     JMenuItem     menuEditCut;
         private     JMenuItem     menuEditPaste;
         public MainPanel()
              requiredLabel = new JLabel ("* Required");
              requiredLabel.setForeground (Color.red);
              requiredLabel2 = new JLabel ("* Required");
              requiredLabel2.setForeground (Color.red);
              requiredStarLabel = new JLabel ("*");
              requiredStarLabel.setForeground (Color.green);
              setTitle( "photo galleries" );
              setSize( 310, 130 );
              topPanel = new JPanel();
              topPanel.setLayout( new BorderLayout() );
              topPanel.setBorder (BorderFactory.createTitledBorder ("TopPanel"));
              //topPanel.setPreferredSize(new Dimension (300,300));
              getContentPane().add( topPanel );
              topPanel.setVisible (false);
              //     For New Item Panel
              ButtonListener ears = new ButtonListener();
              blankLabel = new JLabel ("  ");  // used to give space between radio buttons and continue button
              continueButton = new JButton ("Continue >");
              continueButton.addActionListener (ears);
              backToRadioButton = new JButton ("< back");
              backToRadioButton.addActionListener (ears);
              itemDescriptionContinueButton = new JButton ("Continue >");
              itemDescriptionContinueButton.addActionListener (ears);
              backToItemDescriptionButton = new JButton ("< back");
              backToItemDescriptionButton.addActionListener (ears);
              newItemPanel = new JPanel();
              newItemPanel.setLayout (new BoxLayout(newItemPanel, BoxLayout.Y_AXIS));
              //topPanel.add (newItemPanel, BorderLayout.NORTH);
              newItemPanel.setBorder (BorderFactory.createTitledBorder ("NewItemPanel"));
              newItemPanel.setVisible (false);
              onlineAuctionRadio = new JRadioButton ("Sold item at online Auction"     );
              fixedPriceRadio = new JRadioButton ("Sold at a Fixed Price");
              bg = new ButtonGroup();
              bg.add(onlineAuctionRadio);
              bg.add(fixedPriceRadio);
              onlineAuctionRadio.addActionListener (ears);
              fixedPriceRadio.addActionListener (ears);
              newItemPanel.add (onlineAuctionRadio);
              newItemPanel.add (fixedPriceRadio);
              newItemPanel.add (blankLabel);
              newItemPanel.add (continueButton);
              // ------ After continue pressed ---------
              newItemDescriptionPanel = new JPanel();
              newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
              newItemPanel.add (newItemDescriptionPanel, BorderLayout.NORTH);
              newItemDescriptionPanel.setBorder (BorderFactory.createTitledBorder ("newItemDescriptionPanel"));
              secondCategoryCheckBox = new JCheckBox ("The item was listed in a second category");
              newItemDescriptionPanel.setVisible (false);
              itemTitleLabel = new JLabel ("Item title");
              itemTitleTextField = new JTextField (30);
              subtitleLabel = new JLabel ("Subtitle ($0.50)");
              subtitleTextField = new JTextField (30);
              itemDescriptionLabel = new JLabel ("Item description");
              itemDescriptionTextArea = new JEditorPane();
              itemDescriptionTextArea.setContentType( "text/html" );
              itemDescriptionTextArea.setEditable( false );
              itemDescriptionTextArea.setPreferredSize(new Dimension (500,250));
              itemDescriptionTextArea.setFont(new Font( "Serif", Font.PLAIN, 12 ));
              itemDescriptionTextArea.setForeground( Color.black );
              gbc = new GridBagConstraints();
              gbc.gridx = 0;
              gbc.gridy = 4;
              displayScroller = new JScrollPane( itemDescriptionTextArea );
              gridbag = new GridBagLayout ();
              gridbag.setConstraints( displayScroller, gbc );
              itemDescriptionTextArea.setEditable( true );
              takeAdditionalSpacePanelCheckBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
              takeAdditionalSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanelLabel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanelLabel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
              takeAdditionalSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              takeAdditionalSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              //takeAdditionalSpacePanel2.setBorder (BorderFactory.createTitledBorder ("Additonal 2"));
              takeAdditionalSpacePanelCheckBox.add (secondCategoryCheckBox);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelCheckBox);
              //newItemDescriptionPanel.add (blankLabel);
              takeAdditionalSpacePanelLabel.add (itemTitleLabel);
              takeAdditionalSpacePanelLabel.add (requiredLabel);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel);
              //newItemDescriptionPanel.add (itemTitleTextField);
              takeAdditionalSpacePanel.add(itemTitleTextField);//<--add textfield to panel
              newItemDescriptionPanel.add (takeAdditionalSpacePanel);//<--add panel to boxlayout panel
              takeAdditionalSpacePanelLabel2.add (subtitleLabel);
              newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel2);
              takeAdditionalSpacePanel2.add (subtitleTextField);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel2);
              takeAdditionalSpacePanel4.add (itemDescriptionLabel);
              //takeAdditionalSpacePanel4.add (requiredLabel2);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel4);
              takeAdditionalSpacePanel3.add (displayScroller);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel3);
              takeAdditionalSpacePanel5.add (backToRadioButton);
              takeAdditionalSpacePanel5.add (itemDescriptionContinueButton);
              newItemDescriptionPanel.add (takeAdditionalSpacePanel5);
              //newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
              //----------- Price Enter Page ----------------
              priceEnterPanel = new JPanel();
              priceEnterPanel.setLayout (new BoxLayout(priceEnterPanel, BoxLayout.Y_AXIS));
              newItemDescriptionPanel.add (priceEnterPanel, BorderLayout.NORTH);
              priceEnterPanel.setBorder (BorderFactory.createTitledBorder ("Price enter Panel"));
              priceEnterPanel.setVisible (false);
              priceEnterPanelScroll = new JScrollPane (priceEnterPanel);
              topPanel.add (priceEnterPanelScroll);
              standardPictureRadioButton = new JRadioButton ("Standard");
              picturePackRadioButton = new JRadioButton ("Picture Pack ($1.00 for up to 6 pictures or $1.50 for 7 to 12 pictures)");
              bgPictures = new ButtonGroup();
              bgPictures.add(standardPictureRadioButton);
              bgPictures.add(picturePackRadioButton);
              standardPictureRadioButton.addActionListener (ears);
              picturePackRadioButton.addActionListener (ears);
              superSizePicturesCheckBox = new JCheckBox ("Supersize Pictures ($0.75)");
              listingDesignerCheckBox = new JCheckBox ("Listing designer $0.10");
              valuePackCheckBox = new JCheckBox ("Get the Essentials for less! Gallery, Subtitle, Listing Designer. $0.65 (save $0.30)");
              superSizePicturesCheckBox.setEnabled (false);
              superSizePicturesCheckBox.addActionListener (ears);
              listingDesignerCheckBox.addActionListener (ears);
              valuePackCheckBox.addActionListener (ears);
              startingPriceLabel = new JLabel ("Starting Price");
              dollarSignLabel = new JLabel ("$");
              startingPriceTextField = new JTextField (10);
              buyItNowLabel = new JLabel ("Buy It Now");
              dollarSignLabel2 = new JLabel ("$");
              buyItNowTextField = new JTextField (10);
              donatePercentageLabel = new JLabel ("Donate percentage of sale");
              donatePercentageTextField = new JTextField (2);
              donatePercentageTextField.setText ("0");
              percentageLabel = new JLabel ("%");
              // Right-justify the text
             donatePercentageTextField.setHorizontalAlignment(JTextField.RIGHT);
              numberOfPicturesLabel = new JLabel ("Number of pictures used");
              numberOfPicturesTextField = new JTextField (1);
              numberOfPicturesTextField.setText ("0");
              galleryPictureCheckBox = new JCheckBox ("Gallery ($0.35) [Requires a picture]");
              subtitleCheckBox = new JCheckBox ("Subtitle ($0.50)");
              boldCheckBox = new JCheckBox ("Bold ($1.00)");
              borderCheckBox = new JCheckBox ("Border ($3.00)");
              highlightCheckBox = new JCheckBox ("Highlight ($5.00)");
              featuredPlusCheckBox = new JCheckBox ("Featured Plus! ($19.95)");
              galleryFeaturedCheckBox = new JCheckBox ("Gallery Featured ($19.95) [Requires a picture]");
              homePageFeaturedLabel = new JLabel ("Home Page Featured ($39.95 for 1 item, $79.95 for 2 or more items)");
              homePageFeaturedComboBox = new JComboBox ();
              homePageFeaturedComboBox.addItem (("None..."));
              homePageFeaturedComboBox.addItem (("1 item"));
              homePageFeaturedComboBox.addItem (("2 or more items"));
              giftCheckBox = new JCheckBox ("Show as a gift ($0.25)");
              fillUpSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel10 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel11 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel12 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel13 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel14 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel15 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel16 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel17 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel18 = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp1     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp2     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp3     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp4     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp5     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp6     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp7     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp8     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fSp9     = new JPanel(new FlowLayout(FlowLayout.LEFT));
              fillUpSpacePanel.add (startingPriceLabel);
              fillUpSpacePanel.add (requiredLabel2);
              priceEnterPanel.add (fillUpSpacePanel);
              fillUpSpacePanel2.add (dollarSignLabel);
              fillUpSpacePanel2.add (startingPriceTextField);
              priceEnterPanel.add (fillUpSpacePanel2);     
         //     fillUpSpacePanel1.add (backToItemDescriptionButton);
         //     priceEnterPanel.add (fillUpSpacePanel1);
              fillUpSpacePanel3.add (buyItNowLabel);
              priceEnterPanel.add (fillUpSpacePanel3);
              fillUpSpacePanel4.add (dollarSignLabel2);
              fillUpSpacePanel4.add (buyItNowTextField);
              priceEnterPanel.add (fillUpSpacePanel4);
              fillUpSpacePanel1.add (donatePercentageLabel);
              priceEnterPanel.add (fillUpSpacePanel1);
              fillUpSpacePanel5.add (donatePercentageTextField);
              fillUpSpacePanel5.add (percentageLabel);
              priceEnterPanel.add (fillUpSpacePanel5);
              fillUpSpacePanel6.add (numberOfPicturesLabel);
              priceEnterPanel.add (fillUpSpacePanel6);
              fillUpSpacePanel7.add (numberOfPicturesTextField);
              priceEnterPanel.add (fillUpSpacePanel7);
              fillUpSpacePanel8.add (standardPictureRadioButton);
              priceEnterPanel.add (fillUpSpacePanel8);
              fillUpSpacePanel10.add (blankLabel);
              fillUpSpacePanel10.add (superSizePicturesCheckBox);
              priceEnterPanel.add (fillUpSpacePanel10);
              fillUpSpacePanel9.add (picturePackRadioButton);
              priceEnterPanel.add (fillUpSpacePanel10);
              fillUpSpacePanel11.add (picturePackRadioButton);
              priceEnterPanel.add (fillUpSpacePanel11);
              fillUpSpacePanel12.add (listingDesignerCheckBox);
              priceEnterPanel.add (fillUpSpacePanel12);
              fillUpSpacePanel13.add (valuePackCheckBox);
              priceEnterPanel.add (fillUpSpacePanel13);
              fSp.add (galleryPictureCheckBox);
              priceEnterPanel.add (fSp);
              fSp1.add (subtitleCheckBox);
              priceEnterPanel.add (fSp1);
              fSp2.add (boldCheckBox);
              priceEnterPanel.add (fSp2);
              fSp3.add (borderCheckBox);
              priceEnterPanel.add (fSp3);
              fSp4.add (highlightCheckBox);
              priceEnterPanel.add (fSp4);
              fSp5.add (featuredPlusCheckBox);
              priceEnterPanel.add (fSp5);
              fSp6.add (galleryFeaturedCheckBox);
              priceEnterPanel.add (fSp6);
              fSp7.add (homePageFeaturedLabel);
              priceEnterPanel.add (fSp7);
              fSp8.add (homePageFeaturedComboBox);
              priceEnterPanel.add (fSp8);
              fSp9.add (giftCheckBox);
              priceEnterPanel.add (fSp9);
              newItemDescriptionPanel.add (priceEnterPanelScroll);
              //Create the panel that contains the "cards".
              cards = new JPanel(new CardLayout());
              cards.add(newItemPanel, RADIOPANEL);
              cards.add(newItemDescriptionPanel, DESCRIPTIONPANEL);
              cards.add(priceEnterPanel, PRICEENTERPANEL);
              topPanel.add(cards, BorderLayout.NORTH);
              // Create the menu bar
              menuBar = new JMenuBar();
              // Set this instance as the application's menu bar
              setJMenuBar( menuBar );
              // Build the property sub-menu
              menuProperty = new JMenu( "Properties" );
              menuProperty.setMnemonic( 'P' );
              // Create property items
              menuPropertySystem = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "System...", null, 'S', null );
              menuPropertyEditor = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "Editor...", null, 'E', null );
              menuPropertyDisplay = CreateMenuItem( menuProperty, ITEM_PLAIN,
                                            "Display...", null, 'D', null );
              //Build the File-New sub-menu
              menuFileNew = new JMenu ("New");
              menuFileNew.setMnemonic ('N');
              //Create File-New items
              menuFileNewItem = CreateMenuItem( menuFileNew, ITEM_PLAIN,
                                            "Item", null, 'A', null );
              menuFileNewAccount = CreateMenuItem( menuFileNew, ITEM_PLAIN,
                                            "Account", null, 'A', null );
              // Create the file menu
              menuFile = new JMenu( "File" );
              menuFile.setMnemonic( 'F' );
              menuBar.add( menuFile );
              //Add the File-New menu
              menuFile.add( menuFileNew );
              // Create the file menu
              // Build a file menu items
              menuFileOpen = CreateMenuItem( menuFile, ITEM_PLAIN, "Open...",
                                            new ImageIcon( "open.gif" ), 'O',
                                            "Open a new file" );
              menuFileSave = CreateMenuItem( menuFile, ITEM_PLAIN, "Save",
                                            new ImageIcon( "save.gif" ), 'S',
                                            " Save this file" );
              menuFileSaveAs = CreateMenuItem( menuFile, ITEM_PLAIN,
                                            "Save As...", null, 'A',
                                            "Save this data to a new file" );
              // Add the property menu     
              menuFile.addSeparator();
              menuFile.add( menuProperty );
              menuFile.addSeparator();
              menuFileExit = CreateMenuItem( menuFile, ITEM_PLAIN,
                                            "Exit", null, 'X',
                                            "Exit the program" );
              //menuFileExit.addActionListener(this);
              // Create the file menu
              menuEdit = new JMenu( "Edit" );
              menuEdit.setMnemonic( 'E' );
              menuBar.add( menuEdit );
              // Create edit menu options
              menuEditCut = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Cut", null, 'T',
                                            "Cut data to the clipboard" );
              menuEditCopy = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Copy", null, 'C',
                                            "Copy data to the clipboard" );
              menuEditPaste = CreateMenuItem( menuEdit, ITEM_PLAIN,
                                            "Paste", null, 'P',
                                            "Paste data from the clipboard" );
         public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
                                            ImageIcon image, int acceleratorKey,
                                            String sToolTip )
              // Create the item
              JMenuItem menuItem;
              switch( iType )
                   case ITEM_RADIO:
                        menuItem = new JRadioButtonMenuItem();
                        break;
                   case ITEM_CHECK:
                        menuItem = new JCheckBoxMenuItem();
                        break;
                   default:
                        menuItem = new JMenuItem();
                        break;
              // Add the item test
              menuItem.setText( sText );
              // Add the optional icon
              if( image != null )
                   menuItem.setIcon( image );
              // Add the accelerator key
              if( acceleratorKey > 0 )
                   menuItem.setMnemonic( acceleratorKey );
              // Add the optional tool tip text
              if( sToolTip != null )
                   menuItem.setToolTipText( sToolTip );
              // Add an action handler to this menu item
              menuItem.addActionListener( this );
              menu.add( menuItem );
              return menuItem;
         public void actionPerformed( ActionEvent event )
              CardLayout cl = (CardLayout)(cards.getLayout());
              if (event.getSource() == menuFileExit)
                   System.exit(0);
              if (event.getSource() == menuFileNewAccount)
                   System.out.println ("hlkadflkajfalkdjfalksfj");
              if (event.getSource() == menuFileNewItem){
                   if (firstRun){
                        newItemPanel.setVisible (true);
                        topPanel.setVisible (true);
                   cl.show(cards,RADIOPANEL);
                   firstRun = false;
              //System.out.println( event );
         private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                   CardLayout cl = (CardLayout)(cards.getLayout());
             //     cl.show(cards, (String)evt.getItem());
                   if (event.getSource() == continueButton){
                        if (!(onlineAuctionRadio.isSelected()) && !(fixedPriceRadio.isSelected()))
                             JOptionPane.showMessageDialog(null, "You must select at least one.", "Error", JOptionPane.ERROR_MESSAGE);
                        else{
                             if (onlineAuctionRadio.isSelected()){
                                  cl.show (cards, DESCRIPTIONPANEL);
                                  //newItemPanel.setVisible (false);
                                  //newItemDescriptionPanel.setVisible (true);
                   if (event.getSource() == itemDescriptionContinueButton){
                       if (itemTitleTextField.getText().trim().equalsIgnoreCase(""))
                            JOptionPane.showMessageDialog(null, "You must enter a title.", "Error", JOptionPane.ERROR_MESSAGE);
                        else
                             cl.show (cards, PRICEENTERPANEL);
                   if (event.getSource() == backToRadioButton){
                        cl.show (cards, RADIOPANEL);
                   if (event.getSource() == backToItemDescriptionButton){
                        cl.show(cards, DESCRIPTIONPANEL);
                   if (standardPictureRadioButton.isSelected()){
                        superSizePicturesCheckBox.setEnabled (true);
                   if (picturePackRadioButton.isSelected()){
                        superSizePicturesCheckBox.setEnabled (false);
              } //end of action performed
    }

    Mostly I see there is about 100 times as much code as I care to look at.
    So you don't know how to get a panel in a scroll pane, and then get that scroll pane into your GUI? Then try doing that by itself, not encumbered with 10000 lines of irrelevant code. Once you have it working, plug it into the big lump of code. Or if you can't get it working, ask about the small problem here.

  • Attachment Problem in JavaMail API

    Can anybody help me...
    when 'm trying to attach a file to a mailing aplication(sending attachment),
    an flurry of exceptions are occuring...
    'm using win98 and JDK1.4
    here is the code..can anybody provide a viable solution that works?
    thanks in advance
    * main1.java
    * Created on August 20, 2002, 2:55 PM
    * @author Shamik Ghosh
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class main1 extends javax.swing.JFrame implements ActionListener,ItemListener {
    JMenuBar mbar;
    JMenu file,other,help;
    JMenuItem open,save,read_mail;
    JFrame frame_f;
    FileReader fr;
    BufferedReader br;
    boolean check;
    String from_m,smtp_m,from_m1,smtp_m1,result,
    s1,s2,from_server,from_host,to_file,which_file,attach_text;
    File f;
    /** Creates new form main1 */
    public main1() {
    initComponents();
    setSize(550,500);
    setResizable(false);
    // ------------------------centering the display
    int width=550; // note that "width" & "height" are keywords and
    int height=500; // JAVA defined variables.
    Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
    int x=(screen.width-width)/2;
    int y=(screen.height-height)/2;
    setBounds(x,y,width,height);
    try{
    fr=new FileReader("address.txt");
    br=new BufferedReader(fr);
    String s;
    while((s=br.readLine()) !=null)
    {jComboBox1.addItem(s);}
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    check_info();//calling the method to check the info
    //jTextField1.setText(from_m);
    //jTextField3.setText(smtp_m);
    /** 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.
    private void initComponents() {//GEN-BEGIN:initComponents
    buttonGroup1 = new javax.swing.ButtonGroup();
    buttonGroup2 = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    jRadioButton3 = new javax.swing.JRadioButton();
    jRadioButton4 = new javax.swing.JRadioButton();
    jButton4 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jTextField4 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel10 = new javax.swing.JLabel();
    //actionlisteners
    jButton1.addActionListener(this);
    jButton2.addActionListener(this);
    jButton3.addActionListener(this);
    jButton4.addActionListener(this);
    jButton5.addActionListener(this);
    jButton6.addActionListener(this);
    mbar=new JMenuBar();
    setJMenuBar(mbar);
    file=new JMenu("File");
    other=new JMenu("Other");
    help=new JMenu("Help");
    mbar.add(file);
    mbar.add(other);
    mbar.add(help);
    getContentPane().setLayout(null);
    setTitle("MailMan :Designed and Programmed by Shamik Ghosh");
    //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    jLabel1.setText("From:");
    getContentPane().add(jLabel1);
    jLabel1.setBounds(30, 20, 32, 17);
    jLabel2.setText("To:");
    getContentPane().add(jLabel2);
    jLabel2.setBounds(30, 60, 17, 17);
    getContentPane().add(jTextField1);
    jTextField1.setBounds(110, 20, 240, 21);
    getContentPane().add(jTextField2);
    jTextField2.setBounds(110, 60, 240, 21);
    jLabel3.setText("Smtp Server:");
    getContentPane().add(jLabel3);
    jLabel3.setBounds(10, 100, 74, 17);
    getContentPane().add(jTextField3);
    jTextField3.setBounds(110, 100, 240, 21);
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {  }));
    jComboBox1.setToolTipText("Mail Addresses");
    jComboBox1.setAutoscrolls(true);
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jComboBox1ActionPerformed(evt);
    getContentPane().add(jComboBox1);
    jComboBox1.setBounds(110, 150, 240, 20);
    jComboBox1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setToolTipText("Send the message you have typed");
    jButton1.setMnemonic('m');
    jButton1.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton1.setText("Send Mail");
    getContentPane().add(jButton1);
    jButton1.setBounds(370, 300, 160, 25);
    //jButton2.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 12));
    jButton2.setText("Save Info");
    jButton2.setToolTipText("Save Settings for more mails");
    jButton2.setMnemonic('I');
    getContentPane().add(jButton2);
    jButton2.setBounds(370, 340, 160, 25);
    jButton3.setText("Clear ");
    jButton3.setMnemonic('C');
    jButton3.setToolTipText("Clear all text");
    getContentPane().add(jButton3);
    jButton3.setBounds(370, 380, 160, 27);
    jLabel4.setText("Your Contact Addresses");
    jLabel4.setFont(new java.awt.Font("Arial Narrow", 0, 12));
    getContentPane().add(jLabel4);
    jLabel4.setBounds(110, 130, 200, 15);
    jRadioButton3.setText("Use Log File");
    jRadioButton3.setMnemonic('L');
    getContentPane().add(jRadioButton3);
    jRadioButton3.setBounds(260, 310, 90, 25);
    jRadioButton4.setText("No Log File");
    //jRadioButton4.setMnemonic('N');
    //getContentPane().add(jRadioButton4);
    //jRadioButton4.setBounds(260, 340, 86, 25);
    jButton4.setText("Undo Info");
    jButton4.setMnemonic('U');
    jButton4.setToolTipText("Undo settings");
    getContentPane().add(jButton4);
    jButton4.setBounds(260, 380, 87, 27);
    getContentPane().add(jTextField4);
    jTextField4.setBounds(20, 380, 210, 21);
    jLabel5.setText("Attachment");
    jLabel5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel5);
    jLabel5.setBounds(70, 360, 70, 15);
    jButton5.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    jButton5.setText("Browse");
    jButton5.setMnemonic('B');
    jButton5.setToolTipText("Browse files for Attachment");
    getContentPane().add(jButton5);
    jButton5.setBounds(150, 350, 80, 25);
    jButton6.setText("Attach & Send");
    jButton6.setMnemonic('A');
    jButton6.setToolTipText("Attach File & Send Mail");
    getContentPane().add(jButton6);
    jButton6.setBounds(260, 340, 86, 25);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(370, 20, 160, 270);
    jLabel10.setText("Type your mail:");
    jLabel10.setFont(new java.awt.Font("Abadi MT Condensed Light", 1, 12));
    getContentPane().add(jLabel10);
    jLabel10.setBounds(370, 5, 125, 10);
    jScrollPane2.setViewportView(jTextArea2);
    getContentPane().add(jScrollPane2);
    jScrollPane2.setBounds(20, 200, 340, 90);
    jLabel6.setText("(your ISP smtp)");
    jLabel6.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel6);
    jLabel6.setBounds(10, 120, 70, 12);
    jLabel7.setText("porgrammed and designed by : Shamik Ghosh");
    jLabel7.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel7);
    jLabel7.setBounds(260, 410, 160, 12);
    jLabel8.setText("[email protected]");
    jLabel8.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel8);
    jLabel8.setBounds(420, 410, 80, 12);
    jLabel9.setText("Msg.for the Mail Sent:");
    jLabel9.setForeground(java.awt.Color.black);
    jLabel9.setFont(new java.awt.Font("Abadi MT Condensed Light", 0, 10));
    getContentPane().add(jLabel9);
    jLabel9.setBounds(20, 180, 80, 12);
    file.add(open=new JMenuItem("Open"));
    open.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK,true));
    file.addSeparator();
    file.add(save=new JMenuItem("Save"));
    save.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK,true));
    file.addSeparator();
    other.add(read_mail=new JMenuItem("Add Address"));
    read_mail.setAccelerator(KeyStroke.getKeyStroke('A',Event.CTRL_MASK,true));
    other.addSeparator();
    //adding actionListener to menuitems
    open.addActionListener(this);
    save.addActionListener(this);
    read_mail.addActionListener(this);
    jComboBox1.addItemListener(this);
    pack();
    }//GEN-END:initComponents
    public void itemStateChanged(ItemEvent ie)
    String add_list;
    add_list=String.valueOf(jComboBox1.getSelectedItem());
    jTextField2.setText(add_list);
    } // for item event source
    public void actionPerformed(ActionEvent ae)
    if(ae.getSource()==jButton1)
    if(ae.getSource()==jButton1) {
    SwingUtilities.invokeLater(new Runnable()
    {  public void run()
    sendMail();
    if(ae.getSource()==jButton2) //save info
    from_m =jTextField1.getText();
    smtp_m =jTextField3.getText();
    from_m1 =from_m+"\n";
    smtp_m1 =jTextField3.getText();
    result =from_m1+smtp_m1;
    try{
    byte buf[]=result.getBytes();
    OutputStream fo=new FileOutputStream("info.txt");
    for(int i=0;i<buf.length; i++ )
    fo.write(buf);
    fo.close();
    }catch(Exception e){ System.out.println(e);}
    jTextField1.setEditable(false);
    jTextField3.setEditable(false);
    if(ae.getSource()==jButton3) //clear
    jTextArea1.setText(" ");
    jTextArea2.setText(" ");
    if(ae.getSource()==jButton4)//undo info
    jTextField1.setEditable(true);
    jTextField3.setEditable(true);
    if(ae.getSource()==jButton5)//browse for attachment
    try {
    FileDialog file = new FileDialog (main1.this, "Load File", FileDialog.LOAD);
    file.setFile ("*.*"); // Set initial filename filter
    file.show(); // Blocks
    String curFile;
    if ((curFile = file.getFile()) != null) {
    String filename = file.getDirectory() + curFile;
    char[] data;
    setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    f = new File (filename);
    try {
    System.out.println("INSIDE TRY");
    FileReader fin = new FileReader (f);
    int filesize = (int)f.length();
    data = new char[filesize];
    fin.read (data, 0, filesize);
    setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    } catch (Exception exc) {}
    jTextField4.setText(filename);
    } catch(Exception e){}
    if(ae.getSource()==jButton6)//send attachment & Mail
    try{
    sendmail2();
    }catch(Exception e){}
    if(ae.getSource()==open)//menu open
    if(ae.getSource()==save)//menu save
    if(ae.getSource()==read_mail)//menu read_mail
    address_add();
    } //actionperformed
    public void sendmail2()
    try {
    //which_file,attach_text
    from_server=jTextField3.getText();
    from_host=jTextField1.getText();
    to_file=jTextField2.getText();
    which_file=jTextField4.getText();
    attach_text=jTextArea1.getText();
    //getting system property
    Properties props=System.getProperties();
    //setup mail server
    props.put("mail.smtp.host",from_server);
    //get session
    Session session=Session.getInstance(props,null);
    // Define message
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from_host));
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to_file));
    message.setSubject("Hello JavaMail Attachment");
    //define message part
    BodyPart messageBodyPart=new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText(attach_text);
    // Create a Multipart
    Multipart multipart = new MimeMultipart();
    // Add part one
    multipart.addBodyPart(messageBodyPart);
    //attaching**********************************secon Part Attachment
    //creating second body part
    messageBodyPart=new MimeBodyPart();
    DataSource source=new FileDataSource(which_file); //was filename
    //setting data handler to the attachment
    messageBodyPart.setDataHandler(new DataHandler(source));
    //setting the filename
    messageBodyPart.setFileName(which_file);
    //adding part two
    multipart.addBodyPart(messageBodyPart);
    //put parts in the message
    message.setContent(multipart);
    //Sending msg
    Transport.send(message);
    }catch(Exception e){}
    } //sendmail2
    public void address_add()
    addr=jTextField2.getText();
    str_addr=addr+"\n";
    //jComboBox1.addItem(" ");
    jComboBox1.addItem(addr);
    System.out.println("INSIDE WRITING METHOD");
    try{
    byte buf[]=str_addr.getBytes();
    OutputStream f0=new FileOutputStream("address.txt",true);
    for(int i=0;i<buf.length; i++ )
    f0.write(buf[i]);
    f0.close();
    }catch(Exception e){ System.out.println(e);}
    public void check_info()
    try{
    fr=new FileReader("info.txt");
    br=new BufferedReader(fr);
    while((s1=br.readLine()) !=null && (s2=br.readLine()) !=null)
    jTextField1.setText(s1);
    jTextField3.setText(s2);
    break;
    fr.close();
    }catch(Exception e){ System.out.println(e);}
    public void sendMail()
    {  try
    Socket s = new Socket(jTextField3.getText(), 25);
    out = new PrintWriter(s.getOutputStream());
    in = new BufferedReader(new
    InputStreamReader(s.getInputStream()));
    String hostName
    = InetAddress.getLocalHost().getHostName();
    send(null);
    send("Host " + hostName);
    send("Mail FROM: " + jTextField1.getText());
    send("Rcpt TO: " + jTextField2.getText());
    send("Data");
    out.println(jTextArea1.getText());
    send(".");
    s.close();
    catch (IOException exception)
    {  jTextArea2.append("Error: " + exception);
    String err="Message cannot be sent!"+"\n"
    +"Please verify the setting(s)."+
    "\n"+"Else there may be a NetWork Problem."+
    "\n"+"Please verify and Try Again.";
    JOptionPane.showMessageDialog(frame_f,err,"Message Transmission Failure",JOptionPane.ERROR_MESSAGE);
    public void send(String s) throws IOException
    {  if (s != null)
    {  jTextArea2.append(s + "\n");
    out.println(s);
    out.flush();
    String line;
    if ((line = in.readLine()) != null)
    jTextArea2.append(line + "\n");
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
    // Add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
    System.exit(0);
    }//GEN-LAST:event_exitForm
    * @param args the command line arguments
    public static void main(String args[]) {
    new main1().show();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JButton jButton4;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabel10;
    private BufferedReader in;
    private PrintWriter out;
    private String addr,str_addr;
    // End of variables declaration//GEN-END:variables

    Hi I have this problem which I believe you can help me resolve:
    In my code, there are two lines:
    message.setContent(messageBody, "text/html"); // this sets body of message
    message.setContent(bodyPartObject); // this attaches a file
    but it turns out that the second "setContent" statement over-writes the first one, so that I get no message in the body of the mail.
    What can I do about it, shamik1? Thanks!

  • Problem in layout, please help in correcting code

    Hello Friends,
    I am facing a very strange problem. I have 1 DespktopPane, say DT in which I have created two InternalFrames, say IF1 and IF2. Also there are two JPanels, say P1 and P2. P1 contains various controls and IF1s ContentPane is set to P1 and P2 contains nothing. There two MenuItems, say M1 and M2. On M1s click I displayed IF1 and on M2s click I displayed IF2. Before adding IF2 everything is working fine, i.e. all the controls are able to display on IF1 but after adding IF2 allthe controls are transferred from IF1 to IF2 and now IF1 displays as a blank screen and IF2 contains allthe controls which are added in JPanel p2 whereas IF2s ContenPane is set to P2 and no control is added in P2.
    For your reference, here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MDILayout extends JFrame implements ActionListener
        private static JFrame frame = null;
        private static JDesktopPane desktop = null;
        private static JInternalFrame intframe = null;
        private static JInternalFrame rangeframe = null;
        private static JPanel panel = null;
        private static Image img = null;
        private static JMenuBar menubar = null;
        private static JMenu mfile = null;
        private static JMenuItem bexit = null;
        private static JMenuItem borders = null;
        private static JMenuItem boption = null;
        JButton bcancel,bquery,bexecute,bupdate,bnext,bprev;
        JLabel lheader,lheader1,lheader2,lheader3,lline,lline1,
        lodate,lquality,ltype,lparty,lindent,lsize,lmul,lgsm,lquantity,ldest,lorderno;
        JTextField todate,tquality,ttype,tparty,tindent,tlength,twidth,tgsm,tquantity,tdest,torderno;
        JComboBox cbotype;
        Font bigfont,bigfont1;
        static String ltext="",ltext1="",ltext2="",ltext3="";
        Panel p; Graphics g;
        MDILayout()
            frame = new JFrame("Deckle Suite (Board)");
            desktop = new JDesktopPane();
            intframe = new JInternalFrame("Orders",true,true,true,true);          
            rangeframe = new JInternalFrame("Machine - Deckle Range",true,true,true,true);           
            frame.setSize(1024,738);
            frame.setResizable(false);
            intframe.setSize(1000,680);
            rangeframe.setSize(500,350);
            JPanel p1=(JPanel)getContentPane();
            p1.setLayout(null);
            JPanel p2=(JPanel)getContentPane();
            p2.setLayout(null);
            intframe.setContentPane(p1);
            rangeframe.setContentPane(p2);
            frame.setContentPane(desktop);
            desktop.add(intframe);
            desktop.add(rangeframe);
            intframe.setMaximizable(true);
            intframe.setResizable(false);
            rangeframe.setMaximizable(true);
            rangeframe.setResizable(false);
            intframe.setContentPane(p1);
            intframe.setDefaultCloseOperation(HIDE_ON_CLOSE);
            rangeframe.setContentPane(p2);
            rangeframe.setDefaultCloseOperation(HIDE_ON_CLOSE);
            menubar = new JMenuBar();
            mfile = new JMenu("File");
            bexit = new JMenuItem("Exit");
            borders = new JMenuItem("Orders");
            boption=new JMenuItem("Options");
            menubar.add(mfile);
            mfile.add(borders);
            mfile.add(boption);
            mfile.add(bexit);
            frame.setJMenuBar(menubar);
            ltext="==========";
            for(int i=0;i<6;i++)
                    ltext1=ltext+ltext1;
                    ltext=ltext1;
            ltext2="----------";
            for(int j=0;j<6;j++)
                    ltext3=ltext2+ltext3;
                    ltext2=ltext3;
            bigfont=new Font("Monotype Corsiva",Font.BOLD,35);
            bigfont1=new Font("Times New Roman",Font.PLAIN,20);
            lheader=new JLabel("Deckle Suite (Board)");
            lheader1=new JLabel("Khanna  Paper  Mill (Pvt.) Ltd.");
            lheader2=new JLabel("Fatehgarh Road");
            lheader3=new JLabel("Amritsar");
            lline=new JLabel(ltext1);
            lline1=new JLabel(ltext3);
            lodate=new JLabel("Order Date");
            lquality=new JLabel("Quality");
            ltype=new JLabel("Sheet/Reel");
            lparty=new JLabel("Party");
            lindent=new JLabel("Indent No.");
            lsize=new JLabel("Size");
            lmul=new JLabel("x");
            lgsm=new JLabel("GSM");
            lquantity=new JLabel("Quantity");
            ldest=new JLabel("Destination");
            lorderno=new JLabel("Line No.");
            todate=new JTextField(50);
            tquality=new JTextField(50);
            ttype=new JTextField(20);
            cbotype=new JComboBox();
            tparty=new JTextField(200);
            tindent=new JTextField(50);
            tlength=new JTextField(35);
            twidth=new JTextField(35);
            tgsm=new JTextField(20);
            tquantity=new JTextField(35);
            tdest=new JTextField(200);
            torderno=new JTextField(200);
            lheader.setBounds(350,50,500,50);
            lheader1.setBounds(370,100,500,30);
            lheader2.setBounds(430,130,200,30);
            lheader3.setBounds(460,160,200,30);
            lline.setBounds(0,200,3000,30);
            lline1.setBounds(0,350,3000,30);
            lorderno.setBounds(40,240,100,20);
            lodate.setBounds(40,270,100,20);
            lquality.setBounds(320,270,100,20);
            ltype.setBounds(40,400,70,20);
            lparty.setBounds(40,300,70,20);
            lindent.setBounds(40,430,100,20);
            lsize.setBounds(450,430,50,20);
            lmul.setBounds(560,430,50,20);
            lgsm.setBounds(40,460,50,20);
            lquantity.setBounds(320,460,50,20);
            ldest.setBounds(40,490,100,20);
            torderno.setBounds(120,240,100,20);
            todate.setBounds(120,270,100,20);
            tquality.setBounds(380,270,200,20);
            cbotype.setBounds(120,400,90,20);
            tparty.setBounds(120,300,700,20);
            tindent.setBounds(120,430,200,20);
            tlength.setBounds(490,430,60,20);
            twidth.setBounds(580,430,60,20);
            tgsm.setBounds(120,460,80,20);
            tquantity.setBounds(380,460,80,20);
            tdest.setBounds(120,490,500,20);
            cbotype.addItem("SHEET");
            cbotype.addItem("REEL");
            p1.add(lheader);
            p1.add(lheader1);
            p1.add(lheader2);
            p1.add(lheader3);
            p1.add(lline);
            p1.add(lline1);
            p1.add(lodate);
            p1.add(todate);
            p1.add(lquality);
            p1.add(tquality);
            p1.add(lparty);
            p1.add(tparty);
            p1.add(ltype);
            p1.add(cbotype);
            p1.add(lindent);
            p1.add(tindent);
            p1.add(lsize);
            p1.add(tlength);
            p1.add(lmul);
            p1.add(twidth);
            p1.add(lgsm);
            p1.add(tgsm);
            p1.add(lquantity);
            p1.add(tquantity);
            p1.add(ldest);
            p1.add(tdest);
            p1.add(lorderno);
            p1.add(torderno);
            lheader.setFont(bigfont);
            lheader1.setFont(bigfont1);
            lheader2.setFont(bigfont1);
            lheader3.setFont(bigfont1);
            lheader.setForeground(Color.blue);
            lheader1.setForeground(Color.gray);
            lheader2.setForeground(Color.gray);
            lheader3.setForeground(Color.gray);
            bcancel=new JButton("Refresh");
            bquery=new JButton("Query");
            bexecute=new JButton("Execute");
            bupdate=new JButton("Update");
            bnext=new JButton("Next");
            bprev=new JButton("Previous");
            bcancel.addActionListener(this);
            bquery.addActionListener(this);
            bexecute.addActionListener(this);
            bupdate.addActionListener(this);
            bnext.addActionListener(this);
            bprev.addActionListener(this);
            borders.addActionListener(this);
            boption.addActionListener(this);;
            bexit.addActionListener(this);
            bcancel.setBounds(250,550,200,25);
            p1.add(bcancel);
            bquery.setBounds(450,550,200,25);
            p1.add(bquery);
            bexecute.setBounds(650,550,200,25);
            p1.add(bexecute);
            bupdate.setBounds(250,575,200,25);
            p1.add(bupdate);
            bprev.setBounds(450,575,200,25);
            p1.add(bprev);
            bnext.setBounds(650,575,200,25);
            p1.add(bnext);
            torderno.setEnabled(false);
            todate.setEnabled(false);
            bcancel.setEnabled(true);
            bexecute.setEnabled(false);
            bquery.setEnabled(false);
            bprev.setEnabled(false);
            bnext.setEnabled(false);
            bupdate.setEnabled(false);
            frame.show();
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        public static void main(String args[])
            MDILayout layout=new MDILayout();
        public void actionPerformed(ActionEvent ae)
            if (ae.getSource()==borders)
              intframe.show();
              intframe.repaint();
            if (ae.getSource()==boption)
              rangeframe.show();
              rangeframe.repaint();
    }Please provide me the solution so that P1 appears in IF1 and P2 appears in P2.
    Thanks in advance,
    Ankur

    all the controls are able to display on IF1 but after adding IF2 allthe controls are transferred from IF1 to IF2 and now IF1 displays as a blank screen
    You can't have components at more than one place in the hierarchy. If you add a component to something it is removed from its existing parent if there is one.
    I'm not sure how much that helps you - I took one look at your code and ran away screaming.

  • Repaint problem while clicking the popup menuitem

    Hi all,
    iam facing repainting problem in my application. User can initiate a single action from different options such as JButton, double-click of mouse and clicking the menu item form the JPopupMenu.
    All these will execute the same code. But when iam using the first two ways, the repainting is properly working and aim getting the required UI and opening the JInternalFrame.
    When the last case is being used(ie., clicking the menu item form the JPopupMenu), then the repaint is not working and the window being opened is coming in pieces and then finally i could see the window after some time, which is not the case with the first two cases.
    Please help me how to solve and get the window at once. Iam attaching the code.
    MainFrame.java
    package com.swing;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseWheelEvent;
    import java.awt.event.MouseWheelListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MainFrame extends JFrame implements ActionListener{
         static final long serialVersionUID = 3345648L;
         public MainFrame() {
              setSize(1000,750);
              setLayout(null);
              setVisible(true);
              addMenuBar();
              invalidate();
         public void actionPerformed(ActionEvent actionEvent) {
              Object source = actionEvent.getSource();
              if( source == s_mnuItmFirstFrame ) {
                   FirstFrame s_frameFirst = new FirstFrame(this);
                   this.add(s_frameFirst);
          * @param args
         public static void main(String[] args) {
              MainFrame mFrame = new MainFrame();
         JMenuBar s_menuBar = null;
         JMenuItem s_mnuItmFirstFrame = new JMenuItem("Add Internal Frame");
         void addMenuBar(){
              Font fontNormal = new Font("Dialog", Font.PLAIN, 11);
              s_menuBar = new JMenuBar();
              s_menuBar.setDoubleBuffered(true);
              getRootPane().setJMenuBar(s_menuBar);
              s_mnuItmFirstFrame.setFont(fontNormal);
              s_mnuItmFirstFrame.addActionListener(this);
              JMenu s_menuFrames = new JMenu("Frames");
              s_menuFrames.setFont(fontNormal);
              s_menuFrames.add(s_mnuItmFirstFrame);
              s_menuBar.add(s_menuFrames);
    FirstFrame.java
    package com.swing;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseWheelEvent;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTable;
    import javax.swing.event.InternalFrameAdapter;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.table.DefaultTableModel;
    public class FirstFrame extends JInternalFrame implements ActionListener
         static final long serialVersionUID = 2345657L;
         public FirstFrame(JFrame parentFrame) {
              super(" First Frame ", true, true, true, true);
              mainFrame = parentFrame;
              setSize(400, 400);
              setVisible(true);
              setLayout(new FlowLayout());
              try {
                   setMaximum(false);
              } catch (Exception e) {
                   e.printStackTrace();
              DefaultTableModel s_modelFirstTable = new DefaultTableModel();
              Vector tableData = new Vector();
              Vector namesVector = new Vector();
              namesVector.add("OneFirst");
              namesVector.add("OneMiddle");
              namesVector.add("OneLast");
              tableData.add(namesVector);
              namesVector = new Vector();
              namesVector.add("TwoFirst");
              namesVector.add("TwoMiddle");
              namesVector.add("TwoLast");
              tableData.add(namesVector);
              namesVector = new Vector();
              namesVector.add("ThreeFirst");
              namesVector.add("ThreeMiddle");
              namesVector.add("ThreeLast");
              tableData.add(namesVector);
              namesVector = new Vector();
              namesVector.add("FourFirst");
              namesVector.add("FourMiddle");
              namesVector.add("FourLast");
              tableData.add(namesVector);
              namesVector = new Vector();
              namesVector.add("FiveFirst");
              namesVector.add("FiveMiddle");
              namesVector.add("FiveLast");
              tableData.add(namesVector);
              Vector tableHeader = new Vector();
              tableHeader.add("First Name");
              tableHeader.add("Middle Name");
              tableHeader.add("Last Name");
              s_modelFirstTable.setDataVector(tableData, tableHeader);
              s_tblFirst.setModel(s_modelFirstTable);
              add(s_tblFirst);
              add(s_btnSecondButton);
              s_mnuPopupMenu.add(s_mnuItmSecondButton);
              s_mnuPopupMenu.add(s_mnuItmSecondButton1);
              s_mnuPopupMenu.add(s_mnuItmSecondButton2);
              s_mnuPopupMenu.add(s_mnuItmSecondButton3);
              s_mnuPopupMenu.add(s_mnuItmSecondButton4);
              s_tblFirst.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent mouseEvent) {
                        s_mnuPopupMenu.setVisible(true);
                        // if (mouseEvent.isPopupTrigger()) {
                        s_mnuPopupMenu.show(mouseEvent.getComponent(), mouseEvent
                                  .getX(), mouseEvent.getY());
              s_btnSecondButton.addActionListener(this);
              s_mnuItmSecondButton.addActionListener(this);
              this.addInternalFrameListener(new InternalFrameAdapter() {
                   public void internalFrameClosing(InternalFrameEvent ifEvent) {
                        Object object = ifEvent.getSource();
                        if (object == FirstFrame.this) {
                             try {
                                  if (s_frameSecond != null)
                                       s_frameSecond.setClosed(true);
                             } catch (Exception e) {
                                  e.printStackTrace();
         public void actionPerformed(ActionEvent actionEvent) {
              if (s_frameSecond != null) {
                   try {
                        s_frameSecond.setClosed(true);
                   } catch (Exception e) {
                        e.printStackTrace();
              s_frameSecond = new SecondFrame();
              mainFrame.add(s_frameSecond);
              s_frameSecond.moveToFront();
              s_frameSecond.setVisible(true);
         JFrame mainFrame ;
         JTable s_tblFirst = new JTable();
         JButton s_btnSecondButton = new JButton("Second Frame");
         JMenuItem s_mnuItmSecondButton = new JMenuItem("Second Frame");
         JMenuItem s_mnuItmSecondButton1 = new JMenuItem("Second Frame1");
         JMenuItem s_mnuItmSecondButton2 = new JMenuItem("Second Frame2");
         JMenuItem s_mnuItmSecondButton3 = new JMenuItem("Second Frame3");
         JMenuItem s_mnuItmSecondButton4 = new JMenuItem("Second Frame4");
         JPopupMenu s_mnuPopupMenu = new JPopupMenu();
         SecondFrame s_frameSecond;
    SecondFrame.java
    package com.swing;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JInternalFrame;
    public class SecondFrame extends JInternalFrame {
         static final long serialVersionUID = 1345648L;
         public SecondFrame() {
              super(" Second Frame ", true, true, true, true);
              try {
              setLayout(new GridLayout(4, 4));
              setSize(400,400);
              //setVisible(true);
              setMaximizable(true);
              for(int i=0; i<4; i++){
                   for(int j=0; j<4; j++){
                        add(new JButton(""+(i+1)+", "+(j+1)));
              catch(Exception e){
                   e.printStackTrace();
    }

    Don't post an IDE generated code as is. It's a torture for human eye. At least, you should rename
    all the identifiers to some meaningful names.
    You MUST use JDesktopPane when you use JInternalFrames.
    Here's a working code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.util.*;
    public class MainFrame extends JFrame implements ActionListener{
      static final long serialVersionUID = 3345648;
      JFrame frame;
      JDesktopPane jdp;
      public MainFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000,750);
        // setLayout(null); //you MUST use a real LayoutManager
        addMenuBar();
        frame = this;
        jdp = new JDesktopPane();
        frame.add(jdp);
        setVisible(true);
      public void actionPerformed(ActionEvent actionEvent) {
        Object source = actionEvent.getSource();
        if( source == s_mnuItmFirstFrame ) {
          FirstFrame s_frameFirst = new FirstFrame(this);
          jdp.add(s_frameFirst);
          s_frameFirst.setVisible(true);
      public static void main(String[] args) {
        MainFrame mFrame = new MainFrame();
      JMenuBar s_menuBar = null;
      JMenuItem s_mnuItmFirstFrame = new JMenuItem("Add Internal Frame");
      void addMenuBar(){
        Font fontNormal = new Font("Dialog", Font.PLAIN, 11);
        s_menuBar = new JMenuBar();
        s_menuBar.setDoubleBuffered(true);
        getRootPane().setJMenuBar(s_menuBar);
        s_mnuItmFirstFrame.setFont(fontNormal);
        s_mnuItmFirstFrame.addActionListener(this);
        JMenu s_menuFrames = new JMenu("Frames");
        s_menuFrames.setFont(fontNormal);
        s_menuFrames.add(s_mnuItmFirstFrame);
        s_menuBar.add(s_menuFrames);
        setJMenuBar(s_menuBar);
    class FirstFrame extends JInternalFrame implements ActionListener{
      static final long serialVersionUID = 2345657;
      public FirstFrame(MainFrame parentFrame) {
        super(" First Frame ", true, true, true, true);
        mainFrame = parentFrame;
        setSize(400, 400);
        setVisible(true);
        setLayout(new FlowLayout());
        try {
          setMaximum(false);
        } catch (Exception e) {
          e.printStackTrace();
        DefaultTableModel s_modelFirstTable = new DefaultTableModel();
        Vector<Vector> tableData = new Vector<Vector>();
        Vector<String> namesVector = new Vector<String>();
        namesVector.add("OneFirst");
        namesVector.add("OneMiddle");
        namesVector.add("OneLast");
        tableData.add(namesVector);
        namesVector = new Vector<String>();
        namesVector.add("TwoFirst");
        namesVector.add("TwoMiddle");
        namesVector.add("TwoLast");
        tableData.add(namesVector);
        namesVector = new Vector<String>();
        namesVector.add("ThreeFirst");
        namesVector.add("ThreeMiddle");
        namesVector.add("ThreeLast");
        tableData.add(namesVector);
        namesVector = new Vector<String>();
        namesVector.add("FourFirst");
        namesVector.add("FourMiddle");
        namesVector.add("FourLast");
        tableData.add(namesVector);
        namesVector = new Vector<String>();
        namesVector.add("FiveFirst");
        namesVector.add("FiveMiddle");
        namesVector.add("FiveLast");
        tableData.add(namesVector);
        Vector<String> tableHeader = new Vector<String>();
        tableHeader.add("First Name");
        tableHeader.add("Middle Name");
        tableHeader.add("Last Name");
        s_modelFirstTable.setDataVector(tableData, tableHeader);
        s_tblFirst.setModel(s_modelFirstTable);
        add(s_tblFirst);
        add(s_btnSecondButton);
        s_mnuPopupMenu.add(s_mnuItmSecondButton);
        s_mnuPopupMenu.add(s_mnuItmSecondButton1);
        s_mnuPopupMenu.add(s_mnuItmSecondButton2);
        s_mnuPopupMenu.add(s_mnuItmSecondButton3);
        s_mnuPopupMenu.add(s_mnuItmSecondButton4);
        s_tblFirst.addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent mouseEvent){
            if (mouseEvent.isPopupTrigger()) {
              s_mnuPopupMenu.show(mouseEvent.getComponent(),
               mouseEvent.getX(), mouseEvent.getY());
          public void mouseReleased(MouseEvent mouseEvent) {
            if (mouseEvent.isPopupTrigger()) {
              s_mnuPopupMenu.show(mouseEvent.getComponent(),
               mouseEvent.getX(), mouseEvent.getY());
        s_btnSecondButton.addActionListener(this);
        s_mnuItmSecondButton.addActionListener(this);
        addInternalFrameListener(new InternalFrameAdapter() {
          public void internalFrameClosing(InternalFrameEvent ifEvent) {
            Object object = ifEvent.getSource();
            if (object == this) {
              try {
                if (s_frameSecond != null){
                  s_frameSecond.setClosed(true);
              } catch (Exception e) {
                e.printStackTrace();
      } // FirstFrame constructor
      public void actionPerformed(ActionEvent actionEvent) {
        if (s_frameSecond != null) {
          try {
            s_frameSecond.setClosed(true);
          } catch (Exception e) {
            e.printStackTrace();
        s_frameSecond = new SecondFrame();
        mainFrame.jdp.add(s_frameSecond);
        s_frameSecond.moveToFront();
        s_frameSecond.setVisible(true);
      MainFrame mainFrame ;
      JTable s_tblFirst = new JTable();
      JButton s_btnSecondButton = new JButton("Second Frame");
      JMenuItem s_mnuItmSecondButton = new JMenuItem("Second Frame");
      JMenuItem s_mnuItmSecondButton1 = new JMenuItem("Second Frame1");
      JMenuItem s_mnuItmSecondButton2 = new JMenuItem("Second Frame2");
      JMenuItem s_mnuItmSecondButton3 = new JMenuItem("Second Frame3");
      JMenuItem s_mnuItmSecondButton4 = new JMenuItem("Second Frame4");
      JPopupMenu s_mnuPopupMenu = new JPopupMenu();
      SecondFrame s_frameSecond;
    class SecondFrame extends JInternalFrame {
      static final long serialVersionUID = 1345648;
      public SecondFrame() {
        super(" Second Frame ", true, true, true, true);
        try {
          setLayout(new GridLayout(4, 4));
          setSize(400, 400);
          setMaximizable(true);
          for(int i=0; i<4; i++){
            for(int j = 0; j < 4; ++j){
              add(new JButton("" + (i + 1) + ", " + (j + 1)));
        catch(Exception e){
          e.printStackTrace();
    }

  • Problem reading .txt-file into JTable

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
    public TeamTable()                {
    super( "Invoermodule - Team Table" );
    setSize( 740, 365 );
              // setting the rownames
    ListModel listModel = new AbstractListModel()                     {
    String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
    "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
    public int getSize() { return headers.length; }
    public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

    My problem is that I�m reading a .txt-file into a J-Table. It all goes okay, the FileChooser opens and the application reads the selected file (line). But then I get a Null Pointer Exception and the JTable does not get updated with the text from the file.
    Here�s my code (I kept it simple, and just want to read the text from the .txt-file to the first cell of the table.
    A MORE READABLE VERSION !
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    public class TeamTable extends JFrame implements ActionListener, ItemListener                {
    static JTable table;
         // constructor
        public TeamTable()                {
            super( "Invoermodule - Team Table" );
            setSize( 740, 365 );
              // setting the rownames
            ListModel listModel = new AbstractListModel()                     {
                String headers[] = {"Team 1", "Team 2", "Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8", "Team 9",
                "Team 10", "Team 11", "Team 12", "Team 13", "Team 14", "Team 15", "Team 16", "Team 17", "Team 18"};
                public int getSize() { return headers.length; }
                public Object getElementAt(int index) { return headers[index]; }
              // add listModel & rownames to the table
              DefaultTableModel defaultModel = new DefaultTableModel(listModel.getSize(),3);
              JTable table = new JTable( defaultModel );
              // setting the columnnames and center alignment of table cells
              int width = 200;
              int[] vColIndex = {0,1,2};
              String[] ColumnName = {"Name Team", "Name Chairman", "Name Manager"};
              TableCellRenderer centerRenderer = new CenterRenderer();          
              for (int i=0; i < vColIndex.length;i++)          {
                             table.getColumnModel().getColumn(vColIndex).setHeaderValue(ColumnName[i]);
                             table.getColumnModel().getColumn(vColIndex[i]).setPreferredWidth(width);
                             table.getColumnModel().getColumn(vColIndex[i]).setCellRenderer(centerRenderer);
              table.setFont(new java.awt.Font("Dialog", Font.ITALIC, 12));
              // force the header to resize and repaint itself
              table.getTableHeader().resizeAndRepaint();
              // create single component to add to scrollpane (rowHeader is JList with argument listModel)
              JList rowHeader = new JList(listModel);
              rowHeader.setFixedCellWidth(100);
              rowHeader.setFixedCellHeight(table.getRowHeight());
              rowHeader.setCellRenderer(new RowHeaderRenderer(table));
              // add to scroll pane:
              JScrollPane scroll = new JScrollPane( table );
              scroll.setRowHeaderView(rowHeader); // Adds row-list left of the table
              getContentPane().add(scroll, BorderLayout.CENTER);
              // add menubar, menu, menuitems with evenlisteners to the frame.
              JMenuBar menubar = new JMenuBar();
              setJMenuBar (menubar);
              JMenu filemenu = new JMenu("File");
              menubar.add(filemenu);
              JMenuItem open = new JMenuItem("Open");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem exit = new JMenuItem("Exit");
              open.addActionListener(this);
              save.addActionListener(this);
              exit.addActionListener(this);
              filemenu.add(open);
              filemenu.add(save);
              filemenu.add(exit);
              filemenu.addItemListener(this);
    // ActionListener for ActionEvents on JMenuItems.
    public void actionPerformed(ActionEvent e) {       
         String open = "Open";
         String save = "Save";
         String exit = "Exit";
              if (e.getSource() instanceof JMenuItem)     {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String x = source.getText();
                        if (x == open)          {
                             System.out.println("open file");
                        // create JFileChooser.
                        String filename = File.separator+"tmp";
                        JFileChooser fc = new JFileChooser(new File(filename));
                        // set default directory.
                        File wrkDir = new File("C:/Documents and Settings/Erwin en G-M/Mijn documenten/Erwin/Match Day");
                        fc.setCurrentDirectory(wrkDir);
                        // show open dialog.
                        int returnVal =     fc.showOpenDialog(null);
                        File selFile = fc.getSelectedFile();
                        if(returnVal == JFileChooser.APPROVE_OPTION) {
                        System.out.println("You chose to open this file: " +
                   fc.getSelectedFile().getName());
                        try          {
                             BufferedReader invoer = new BufferedReader(new FileReader(selFile));
                             String line = invoer.readLine();
                             System.out.println(line);
                             // THIS IS WHERE IT GOES WRONG, I THINK
                             table.setValueAt(line, 1, 1);
                             table.fireTableDataChanged();
                        catch (IOException ioExc){
                        if (x == save)          {
                             System.out.println("save file");
                        if (x == exit)          {
                             System.out.println("exit file");
    // ItemListener for ItemEvents on JMenu.
    public void itemStateChanged(ItemEvent e) {       
              String s = "Item event detected. Event source: " + e.getSource();
              System.out.println(s);
         public static void main(String[] args)                {
              TeamTable frame = new TeamTable();
              frame.setUndecorated(true);
         frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
              frame.addWindowListener( new WindowAdapter()           {
                   public void windowClosing( WindowEvent e )                {
         System.exit(0);
    frame.setVisible(true);
    * Define the look/content for a cell in the row header
    * In this instance uses the JTables header properties
    class RowHeaderRenderer extends JLabel implements ListCellRenderer           {
    * Constructor creates all cells the same
    * To change look for individual cells put code in
    * getListCellRendererComponent method
    RowHeaderRenderer(JTable table)      {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    * Returns the JLabel after setting the text of the cell
         public Component getListCellRendererComponent( JList list,
    Object value, int index, boolean isSelected, boolean cellHasFocus)      {
    setText((value == null) ? "" : value.toString());
    return this;

Maybe you are looking for