Adding a JFrame in JBuilder

Hi,
I'm writing a GUI application with Jbuilder Personal and am wondering how to add a second JFrame to my project which can be displayed by a button click from my original JFrame I created when starting the project through the Wizard. Basically I want to build a multiple window GUI and at the moment and can't add more windows!
Help please!

Deepu M wrote:
Hi all,
I'm trying to add a Jframe in front of Open Script. This is for getting username and password from Jframe to OpenScript. Can any one help me to do this.What have you tried?

Similar Messages

  • How to fix the position of JInternal frames added in JFrame

    Hay Frnds, I am having a problem. I have a JFrame ,in which i have added five JInternalFrames. My problem is that i want to fix the position of thaose Internal frames so that user cant move them from one place to other. Is there any way to fix there position. Plz reply as soon as possible. Its very urgent.
    Thanks.

    In Jframe I added one rootPanelI don't know what a rootPanel is or why you think you need to add one.
    The general code should probably be something like:
    frame.add(userPanel, BorderLayout.CENTER);
    frame.add(buttonPanel, BorderLayout.SOUTH);
    frame.pack();Read the section from the Swing tutorial on [Using Layout Managers|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html] for more information and working examples.
    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • How to fix the position of JInternalFrames added in JFrame.

    Hay Frnds, I am having a problem. I have a JFrame ,in which i have added five JInternalFrames. My problem is that i want to fix the position of thaose Internal frames so that user cant move them from one place to other. Is there any way to fix there position. Plz reply as soon as possible. Its very urgent.
    Thanks.

    import javax.swing.plaf.basic.*;
            BasicInternalFrameUI internalframeUI = (BasicInternalFrameUI)frame1.getUI();
            internalframeUI.getNorthPane().addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent evt) {
                    frame1.setBounds(0, 0, frame1.getWidth(), frame1.getHeight());
            });

  • Multithreaded Pacman: only last animated panel added to JFrame is displaye

    Hello,
    I am making a multithreaded pacman game. Pacman and each of the ghosts run in a separate thread.
    However, only the last item (ie. pacman or one of the ghosts) added to the JFrame is displaying in the maze. (pacman and each of the ghosts are subclasses of JPanel). For example, if I do:
    add(pacman);
    add(orangeGhost);
    add(redGhost);
    only the red ghost animation will appear on the maze(which is also a subclass of JPanel).
    I have tried adding the ghosts to pacman and then adding pacman i.e. pacman.add(redGhost); add(pacman); but this still doesn't work - only pacman is showing in the maze.
    Each thread runs fine on its own, but only the last one added is displaying.
    Any help is much appreciated.

    Hi,
    JFrame uses the BoderLayout layout manager, and when you add a JPanel after the other inside your JFrame they will get put one on top of other. None of the layout manager let you overlap components with transparency as far as I know. Also your JPanels are not transparent but opaque.
    I think what you need is to "paint" your game on a JPanel o canvas, take a look at this tutorial:
    http://javaboutique.internet.com/tutorials/Java_Game_Programming/
    Keep asking around, people with more experience can help you on this forum.
    Regards,

  • Pros & cons of extending jframe or adding it

    Hi i've written a class code that extends jframe (and is my main code for the application) now i see that many code examples (such as the divelog.java posted on java.sun) prefer adding a jframe to the class and .pack & .setvisible
    beside code comfort (either way) is there a real reason to prefer one way over the other ?
    thanks .

    yes. always favour composition over inheritance. class inheritance is one of the most abused features of the language, I have to struggle with inappropriate use of it on a daily basis because we've got a team of morons who think it's ok to extend a class twelve times, just to change the order in which some buttons get displayed on-screen. that's not an exaggeration, at all
    extend classes when the subclass really is an extension of the superclass, really is a kind-of JFrame or whatever. not just to re-use some methods and save some typing. hint: JFrame is a Container,which means it was intended to contain other UI objects. thus, by adding widgets to it, you are making use of it as intended, not making a new kind of JFrame

  • Adding Jtree to Panel

    Hi all,
    I have a JTree in a scrollpane rendered with checkbox on each node. I
    When I try adding to JFrame its displaying with scrollbar as expected. like this
    frame.setContentPane(scrollPane); //working fineBut When I try adding to panel and try to display that its not working
    JPanel panel = new JPanel();
    panel.add(scrollPane);
    frame.setContentPane(panel); // displaying tree without scrollbarsthanks,
    sur

    scrollPane.setPreferredSize(new Dimension(x,y));where x,y can be the width/height of the frame

  • Resizing JFrames and JPanels !!!

    Hi Experts,
    I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
    My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
    My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
    Plese guide me, how should i do this ...
    Thanknig Java Community,
    Dhwanit Shah

    Hey there, thanx for your kind intereset.
    Here is sample code .
    In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
    I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    public class FramePanel extends JFrame {
    JPanel contentPane;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    public FramePanel() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    FramePanel framePanel = new FramePanel();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(gridBagLayout1);
    this.setSize(new Dimension(296, 284));
    this.setTitle("Frame and Panel Together");
    MyPanel myPanel = new MyPanel();
    this.getContentPane().add(myPanel);
    this.setVisible(true);
    class MyPanel extends JPanel {
    public MyPanel() {
    this.setSize(200,200);
    this.setLayout(new FlowLayout());
    this.setBackground(Color.black);
    this.setVisible(true);
    this.add(new JButton("Dhwanit Shah"));
    I think i might explained my problem
    Dhwanit Shah
    [email protected]

  • Urgent, Plz help me...

    I am trying to add JFrames to a main window. I tried to add a frame to another frame using parentFrame.getContentPane().add(childFrame), but generated run time error -> adding a window to a container. How could this be resolved.
    Please help me as soon as possible.
    Thank you,
    Rajesh

    As far as I'm aware, a JFrame is a hevyweight window, and adding a JFrame to another JFrame will not work. A JInternalFrame behave just like a JFrame inside a JFrame, so I don't know why you would want to avoid using them. Is there any reason why they must be JFrames and not JInternalFrames?
    Graeme

  • L&F mapping JTable

    The look and feel values chosen for the JTable under windows do not feel right to me (albeit that I cannot find many examples of tables under windows).
    I am trying to provide some workarounds that follow what most people expect to happen but am a little unclear on what should happen on some key presses for the JTable in windows look and feel
    Space handling
    From one of the MS windows books it suggests that the space key is a selection key, thus when you press space a row in a table should be selected (and when you press again it should deselect the row?)
    The JList has functionality for the space key
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.
    Enter handling
    The enter key press is supposed to activate the default button
    or commit a text field under edit.
    F2 puts a field under edit
    q2) Should the enter key put an editable cell under edit (same mouse action as single or double click to edit)?
    q3) if not should the first enter key stop cell editing and a second press activate the default button, with only a single enter to activate default button if a cell is not under edit
    Escape handling
    The escape key will cancel editing of a cell that is under edit.
    q4) should the event not be passed on when editing has been cancelled so that dialogs with a canel button can be dismissed
    or
    q5) should the first escape cancel editing while the second escape will action the escape action of the window.
    Any links to "highly regarded" useability/look and feel sites would be helpful - sun does not appear to provide much on this subject
    I've read both their l&f and advanced l&f books and they just scratch the surface of look and feel without much realworld appliance to real gui issues.
    Might be useful to others: Some of the code that I was trying to create goes like....
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Event;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyEvent;
    import java.math.BigDecimal;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.CellEditor;
    import javax.swing.InputMap;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.JViewport;
    import javax.swing.KeyStroke;
    import javax.swing.ListSelectionModel;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.table.TableModel;
    /** Provides utility methods for the JTable and JCSortableTable classes
    * @author  */
    public final class JTableUtil
          * Constructor for JCTableUtil.
         private JTableUtil()
              super();
         /** will resize the last column of a table to fill the gap
          * if the width of the columns is narrower than the width of the
          * table
          * @param table to act upon
         static void resizeLastColumn(final JTable table)
              TableColumn lastColumn = getLastVisibleColumn(table);
              if (lastColumn != null)
                   int gap = getLastColumnGap(table);
                   if (gap > 0)
                        int newLastColumnWidth = gap + lastColumn.getWidth();
                        lastColumn.setWidth(newLastColumnWidth);
                        lastColumn.setPreferredWidth(newLastColumnWidth);
                        redrawTable(table);
          * Determines if there is a gap between the last column in a table
          * and the border of the table.
          * Works if the table is drawn on the page or is in the
          * viewport of a scroll pane.
          * @param table to act upon
          * @return the gap in pixels between last column and table edge.
         static int getLastColumnGap(final JTable table)
              int widthTable = getTableWidth(table);
              int lastVisColIndex = getLastVisibleColumnIndex(table);
              TableColumnModel columnModel = table.getColumnModel();
              int widthColumns = columnModel.getTotalColumnWidth();
              final TableColumn lastColumn = columnModel.getColumn(lastVisColIndex);
              // gap is number of pixels from right hand edge of last column
              // to right hand edge of the table
              int gap = widthTable - widthColumns;
              return gap;
          * Determines the width of a table returning the table width if
          * table is painted onto a panel, but if the table is painted
          * into a scroll pane then it is the scroll pane viewport width that is returned
          * This is to capture that the width of the table may be less than the
          * width of the viewport - ie if there is a gap after the last column in a table.
          * @param table to act upon
          * @return the width of the table in pixels
         static int getTableWidth(final JTable table)
              int widthTable = table.getWidth();
              Object tableParent = table.getParent();
              JViewport tableViewPort = null;
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   widthTable = tableViewPort.getWidth();
              return widthTable;
         /** Cause the table to redraw wether table is painted on a panel
          * or in a scroll pane
          * @param table to act upon
         static void redrawTable(final JTable table)
              Component tableRegion = table;
              Component tableParent = table.getParent();
              if (tableParent instanceof JViewport)
                   tableRegion = tableParent;
              tableRegion.invalidate();
              tableRegion.validate();
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return index (0 based) of the last visible column.
         static int getLastVisibleColumnIndex(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              boolean found = false;
              int columnIndex = columnModel.getColumnCount();
              while (!found && columnIndex > 0)
                   columnIndex--;
                   if (columnModel.getColumn(columnIndex).getWidth() != 0)
                        found = true;
              return columnIndex;
         /** Determines the last (right most) column in a table with a width
          * greater than 0
          * @param table to act upon
          * @return TableColumn - the last visible column.
         static TableColumn getLastVisibleColumn(JTable table)
              TableColumnModel columnModel = table.getColumnModel();
              return columnModel.getColumn(getLastVisibleColumnIndex(table));
          * Add the currency symbol to a JCTable/JCListTable column header
          * e.g. 'Salary' becomes 'Salary (�)'
         public static void addCurrencySymbol(JTable table, Object columnKey)
              //@todo - update to work with JTable
              TableColumnModel columnModel = table.getTableHeader().getColumnModel();
              int columnIndex = columnModel.getColumnIndex(columnKey);
              TableColumn column = columnModel.getColumn(columnIndex);
              Object object = column.getHeaderValue();
              if (object instanceof JLabel)
                   JLabel columnLabel = (JLabel) object;
                   SlacCurrency.getInstance().addCurrencySymbol(columnLabel);
              else
                   // @todo log here ???
              // is above correct - need to get the JLabel rendered from the table
              // in the scroll pane?          
         /** Provides a sum of a column of BigDecimals
          * @param tableModel model containing column that you wish to sum
          * @param column the column that you wish to be summed, must contain numeric values and not strings
         public static BigDecimal calculateTotalForColumn(final TableModel tableModel, final int column)
              int numRows = tableModel.getRowCount();
              BigDecimal total = new BigDecimal("0");
              for (int row = 0; row < numRows; row++)
                   Object value = tableModel.getValueAt(row, column);
                   if (value instanceof BigDecimal)
                        BigDecimal decimalValue = (BigDecimal) value;
                        total = total.add(decimalValue);
                   else
                        //Logger.logGeneralFailure("", ErrorCodes.GUI_ERROR, this);
              return total;
          * Provides the swing setting JTable.AUTO_RESIZE_OFF.
          * <p>
          * In this situation if the width of the columns is smaller than the width
          * of the table then there will be a gap after the last column.
          * <p>
          * This method will add a ComponentListener to the table and or
          * scroll pane viewport so that there is no gap after the last column.
          * @param table to act upon
         public static void configureAutoResizeOff(final JTable table)
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              Component tableParent = table.getParent();
              JViewport tableViewPort = null;
              ComponentAdapter gapFiller = new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        super.componentResized(e);
                        JTableUtil.resizeLastColumn(table);
              table.addComponentListener(gapFiller);
              if (tableParent instanceof JViewport)
                   tableViewPort = (JViewport) tableParent;
                   tableViewPort.addComponentListener(gapFiller);
         /** Method provides fixes to provide standard handling for keyboard and mouse usage
          * <ul>
          *    <li> spacebar - selection handling of rows that have focus emphasis see fixSpacebarHandling()
          *    <li> initial focus handling - table should give visual feedback when gaining focus
          *    <li>
          * </ul>
          * @param table - the table to add standards handling to
         public static void setupKeyboardMouseHandling(JTable table)
              fixTableGainsFocusOnFirstEntry(table);
              fixSpacebarHandling(table);
              fixCtrlSpacebarHandling(table);
              fixShiftSpacebarHandling(table);
              fixCtrlUpDownHandling(table);
              fixFocusHighlight();
              fixEscEnter(table);
         /** Add fixes to the look and feel handling for a JTable
          * Enter on a table will do different things depending on the mode of the table
          * <p>
          * if a cell is being edited then
          * Enter will do what normally happens to a field under edit - ie stop the editing and commit
          * Escape will cancel the editing
          * <p>
          * if a cell is not under edit then
          * Enter will activate the default button
          * Escape will activate the default cancel button (see FrameUtil.addEscapeKeyAction())
         static void fixEscEnter(final JTable table)
              final RootPaneContainer root = (RootPaneContainer)SwingUtilities.windowForComponent(table);
              final String escapeKey = "escapeAction";
              Action escapeAction = new AbstractAction(escapeKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.cancelCellEditing();
                        else
                             Window parentWindow = SwingUtilities.windowForComponent(table);
                             Action windowEscapeAction = FrameUtil.getEscapeKeyAction(root);
                             windowEscapeAction.actionPerformed(actionEvent);
              final String enterKey = "enterAction";
              Action enterAction = new AbstractAction(enterKey)
                   public void actionPerformed(ActionEvent actionEvent)
                        if(table.isEditing())
                             CellEditor editor = table.getCellEditor(table.getEditingRow(), table.getEditingColumn());
                             editor.stopCellEditing();
                        else
                             root.getRootPane().getDefaultButton().doClick();
              InputMap inputMap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              table.getActionMap().put(escapeKey, escapeAction);
              table.getActionMap().put(enterKey, enterAction);
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeKey);          
              inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enterKey);          
         static void fixFocusHighlight()
              Border focusCellHighlightBorder = new DashedLineBorder(Color.BLACK);
              UIManager.put("Table.focusCellHighlightBorder", focusCellHighlightBorder);
         /** If you do not setup a table to have a row selected then there is a bug where for example
          * you use an accelerator key to put focus in the table and you get no visual feedback that
          * the table has focus - ie no focus emphasis - dashed box
          * @param table - the table to fix
         static void fixTableGainsFocusOnFirstEntry(JTable table)
              // for first time tabbing to table make sure that first cell has focus
              // don't seem to need this fix under windows XP
              table.getSelectionModel().removeSelectionInterval(0, 0);
         /** fix spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * spacebar - select the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixSpacebarHandling(JTable table)
              KeyStroke ksSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
              final String ACTION_SPACE = "SPACE";
              Action spaceAction = new AbstractAction(ACTION_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksSpace, ACTION_SPACE);
              table.getActionMap().put(ACTION_SPACE, spaceAction);
         /** fix ctrl + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * ctrl + spacebar - toggle selection on the current row without deselecting any others
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlSpacebarHandling(JTable table)
              KeyStroke ksCtrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.CTRL_MASK, true);
              final String ACTION_CTRL_SPACE = "CTRLSPACE";
              Action ctrlSpaceAction = new AbstractAction(ACTION_CTRL_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        boolean isCurrentRowSelected = selectModel.isSelectedIndex(currentRowIndex);
                        if (isCurrentRowSelected)
                             selectModel.removeSelectionInterval(currentRowIndex, currentRowIndex);
                        else
                             selectModel.addSelectionInterval(currentRowIndex, currentRowIndex);
              table.getInputMap().put(ksCtrlSpace, ACTION_CTRL_SPACE);
              table.getActionMap().put(ACTION_CTRL_SPACE, ctrlSpaceAction);
         /** fix shift + spacebar handling
          * java standards does not mention spacebar handling on a JTable but this is a windows
          * standard feature and is also a feature on JList.
          * Without spacebar handling on a JTable there would be no other keyboard handling that
          * would allow you to select the current row.
          * <p>
          * Trying to follow windows standards since java does not list space bar handling for JTable.
          * The following bahaviour can be seen in IBM code in project Java build path - tab libraries
          * and in microsoft code in the administrative tools control panel dialog in windows XP
          * <p>
          * shift + spacebar - extend the selection from the anchor to the lead index.
          * this might still be a bit funny in java 1.4.2 and code may need to be changed slightly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixShiftSpacebarHandling(JTable table)
              KeyStroke ksShiftSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Event.SHIFT_MASK, true);
              final String ACTION_SHIFT_SPACE = "SHIFTSPACE";
              Action shiftSpaceAction = new AbstractAction(ACTION_SHIFT_SPACE)
                   public void actionPerformed(ActionEvent actionEvent)
                        ListSelectionModel selectModel =
                             ((JTable) actionEvent.getSource()).getSelectionModel();
                        int currentRowIndex = selectModel.getAnchorSelectionIndex();
                        int startRowIndex = selectModel.getLeadSelectionIndex();
                        selectModel.setSelectionInterval(startRowIndex, currentRowIndex);
              table.getInputMap().put(ksShiftSpace, ACTION_SHIFT_SPACE);
              table.getActionMap().put(ACTION_SHIFT_SPACE, shiftSpaceAction);
         /** fix ctrl + down or up handling - move focus emphasis up or down accordingly
          * <p>
          * handling should be fixed in merlin release 1.5
          * see bug report http://developer.java.sun.com/developer/bugParade/bugs/4303294.html
         static void fixCtrlUpDownHandling(JTable table)
              final String ACTION_UP = "CTRLUP";
              KeyStroke ksCtrlUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK, true);
              KeyStroke ksCtrlDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK, true);
              Action ctrlUpAction = new CtrlUpDownAction(ACTION_UP, true);
              final String ACTION_DOWN = "CTRLDOWN";
              Action ctrlDownAction = new CtrlUpDownAction(ACTION_DOWN, false);
              table.getInputMap().put(ksCtrlUp, ACTION_UP);
              table.getActionMap().put(ACTION_UP, ctrlUpAction);
              table.getInputMap().put(ksCtrlDown, ACTION_DOWN);
              table.getActionMap().put(ACTION_DOWN, ctrlDownAction);
    * Action for moving focus emphasis up or down
    class CtrlUpDownAction extends AbstractAction
         private boolean m_isUp = true;
         /** Ctor controlling direction of focus emphasis
          * @param name of the action
          * @param isUp - true if dirction of action is up, else false
         public CtrlUpDownAction(String name, boolean isUp)
              super(name);
              m_isUp = isUp;
         /** Moves the focus emphasis
          * @param actionEvent - see javax.swing.AbstractAction class for details
         public void actionPerformed(ActionEvent actionEvent)
              JTable table = (JTable) actionEvent.getSource();
              ListSelectionModel selectModel = table.getSelectionModel();
              int nextRowIndex =
                   getNextRowIndex(table.getRowCount(), selectModel.getAnchorSelectionIndex());
              if (selectModel.isSelectedIndex(nextRowIndex))
                   selectModel.addSelectionInterval(nextRowIndex, nextRowIndex);
              else
                   selectModel.removeSelectionInterval(nextRowIndex, nextRowIndex);
         /** Gets the index of the next row depending on direction up or down
          * @param rowCount - number of rows in the table
          * @param currentRowIndex - index of the row that has focus emphasis
          * @return the index of the next row
         private int getNextRowIndex(int rowCount, int currentRowIndex)
              int nextRowIndex = -1;
              if (m_isUp && currentRowIndex > 0)
                   // emphasis moving up one row
                   nextRowIndex = currentRowIndex - 1;
              else if (!m_isUp && currentRowIndex < (rowCount - 1))
                   // emphasis moving down one row
                   nextRowIndex = currentRowIndex + 1;
              return nextRowIndex;
    /** Draws a dashed line (well more of a dotted line)
    * Used for eg drawing focus emphasis rectangle
    * Class draws a rectangle of chosen colour overlaid with a dashed white line.
    class DashedLineBorder extends LineBorder
         private BasicStroke m_lineStroke = new BasicStroke();
         private BasicStroke m_dashStroke =
              new BasicStroke(
                   m_lineStroke.getLineWidth(),
                   BasicStroke.CAP_BUTT,//m_lineStroke.getEndCap(),
                   m_lineStroke.getLineJoin(),
                   m_lineStroke.getMiterLimit(),
                   new float[] { 1,1,1 },
                   0);
          * Constructor for DashedLineBorder.
          * @param color
         public DashedLineBorder(Color color)
              super(color);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
         public DashedLineBorder(Color color, int thickness)
              super(color, thickness);
          * Constructor for DashedLineBorder.
          * @param color
          * @param thickness
          * @param roundedCorners
         public DashedLineBorder(Color color, int thickness, boolean roundedCorners)
              super(color, thickness, roundedCorners);
         /** Similar to LineBorder's method but draws a line in the chosen colour
          * before drawing a white dashed line on top of it
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
              Color oldColor = g.getColor();
              int i;
              Graphics2D g2 = (Graphics2D) g;
              g2.setStroke(m_lineStroke);
              g.setColor(lineColor);
              drawRect(g, x, y, width, height);
              g2.setStroke(m_dashStroke);
              g.setColor(Color.WHITE);
              drawRect(g, x, y, width, height);
              g.setColor(oldColor);
          * @see javax.swing.border.Border#paintBorder(Component, Graphics, int, int, int, int)
         private void drawRect(Graphics g, int x, int y, int width, int height)
              // extracted from Java LineBorder.paintBorder
              int i;
              /// PENDING(klobad) How/should do we support Roundtangles?
              for (i = 0; i < thickness; i++)
                   if (!roundedCorners)
                        g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1);
                   else
                        g.drawRoundRect(
                             x + i,
                             y + i,
                             width - i - i - 1,
                             height - i - i - 1,
                             thickness,
                             thickness);
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.image.ImageProducer;
    import java.io.IOException;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.RootPaneContainer;
    * Provides static utility methods for JFrames.
    public final class FrameUtil {
        * No instances allowed. Just use the static methods.
       private FrameUtil() {
          super();
        * Sets the button that is "activated" when the escape key is used.
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key button should be set.
        * @param button The button which should be clicked automatically when the escape key is pressed.
       public static void setEscapeKeyButton(final RootPaneContainer jFrame, final JButton button) {
          addEscapeKeyAction(jFrame, new AbstractAction() {
             public void actionPerformed(final ActionEvent evt) {
                button.doClick();
        * Adds an action to the jframe's  action map that is triggered by the Escape key.
        * (If you just want to simulate a button click when the escape key is pressed then
        * use setEscapeKeyButton.)
        * A bit like
        * SwingUtilities.getRootPane(this).setDefaultButton(myButton);
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
        * @param action The action that is executred when the escape key us pressed,
       public static void addEscapeKeyAction(final RootPaneContainer jFrame, final Action action) {
          String actionKey = "escapeAction";
          KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          // using getRootPane rather than getContentPane, content pane doesn't work in all
          // scenarios
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          inputMap.put(escape, actionKey);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          actionMap.put(actionKey, action);
        * Finds the escape action for the given frame or dialog if one was added
        * @param jFrame The JFrame or JDialog for which the escape key action should be set.
       public static Action getEscapeKeyAction(final RootPaneContainer jFrame)
          InputMap inputMap = (jFrame.getRootPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
          KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
          ActionMap actionMap = (jFrame.getRootPane()).getActionMap();
          Object actionKey = inputMap.get(escapeKeyStroke);
          Action escapeAction = null;
          if(actionKey != null)
             escapeAction = actionMap.get(actionKey);
          return escapeAction;

    From one of the MS windows books.....Going by the books, eh?
    Well, apparently MS doesn't do so with Excel... Pressing space will simply trigger an edit!
    q1) JTable should have space bar handling out of the box?
    (space, CTRL+space, shift+space)
    I have not seen this raised as a bug.A bug, no... a feature, maybe. Anyway, JTable provides most of the features needed for creating a table -- it's far from perfect..... adding support for CTRL+SPACE and SHIFT+SPACE is not all that hard to do.
    q2) Should the enter key put an editable cell under edit and
    q3) if not should the first enter key stop cell editing and a second press activate the default buttonIMHO, a good answer to your question can be found by running MS Excel and see how it's done.
    The escape key will cancel editing of a cell that is under edit.and q4, q5
    It should, as in Excel. But then, in Lotus 1-2-3, first escape will clear the edit buffer (unless it's empty) and the second escape will cancel editing. Who'is more programmatically correct (I don't know)?
    ;o)
    V.V.

  • Error while attempting to run my JAR file

    I'm very new to Java and I'm currently using Sun Java Studio Enterprise 8. I've created a Java Class Library. In it I wrote a few classes of my own and I've added a JFrame in which I've using some of them. My code compiles without problems. When I finished, I wanted to build the main project. I clicked F11 (Which is the Build hotkey) and it said "BUILD SUCCESSFUL". I then opened the project folder and tried to run my application. I got an error message saying:
    Java Virtual Machine Launcher
    Failed to load Main-Class manifest attribute from
    C:\Documents and Settings\laginimaineb\SC\build\classes\SC.jar
    OK
    What should I do?
    With Thanks,
    laginimaineb.

    Nevermind, I found the mistake.

  • Newbie help: Layout Managers

    Hi,
    as a newbie in Swing I have difficulties with the Layout Managers... I have read the Swing tutorial but it's still a little bit complicated:
    I have a JPanel, I would like to add a JMenuBar, a JToolbar and then 2 additional JPanels at the top and on the left representing rulers like in the "How a Scroll Pane Works" example at
    http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html as well as a JTable on the right.
    How can I do this... BorderLayout containing my main JPanel at CENTER and the two JPanels representing the rulers at PAGE_START and LINE_START and the JTable at LINE_END? Where can I place then my menu- and toolbar? Can I add a BoxLayout to PAGE_START for that?
    In a posting here at the forum I read that the MenuBar should be added to the root Pane. How do I do this? When do I use Content Pane, Layered Pane and Glass Pane?
    Do you know a simple example or good tutorials at the web?
    Thanks a lot!

    Thank you for the link about the rulers.
    The rulers goes inside your custom component. It will be like the example at http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html
    Other stuffs layered like this.
    package tmp;
    import javax.swing.*;
    import java.awt.*;
    public class LayoutExample extends JFrame
        public static void main( String[] args ) throws Exception
            SwingUtilities.invokeAndWait( new Runnable()
                public void run()
                    // All the interaction with GUI do inside the MessageLoop thread!
                    LayoutExample l = new LayoutExample();
                    l.pack();
                    l.setVisible( true );
        protected JMenuBar mainMenu;
        protected JToolBar mainToolBar;
        protected RulesFeaturedScrolPane scrollPane;
        public LayoutExample() throws HeadlessException
            super();
            setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            setTitle( "Layout Example" );
            // -------------- CREATING NECESSARY CONTROLS ----------------
            // Menu
            mainMenu = new JMenuBar();
            JMenu mnuFile = mainMenu.add( new JMenu( "File" ) );
            mnuFile.add( new JMenuItem( "Open" ) );
            // ToolBar
            mainToolBar = new JToolBar();
            mainToolBar.add( new JButton( "Open" ) );
            // Customized JScrollPane (with rulers)
            scrollPane = new RulesFeaturedScrolPane();
            // -------------- END OF CREATING NECESSARY CONTROLS ----------------
            // Settig up the components
            setJMenuBar( mainMenu ); // Menu added to JFrame not to its ContentPane
            getContentPane().setLayout( new BorderLayout() );
            getContentPane().add( mainToolBar, BorderLayout.NORTH ); // ToolBar added to the ContentPane
            getContentPane().add( scrollPane, BorderLayout.CENTER ); // Other components added to ContentPane
        public static class RulesFeaturedScrolPane extends JPanel // <----------- this may extend JScrollPane
            public RulesFeaturedScrolPane()
                add( new JLabel( "TODO: this class should have rulers" ) );
    }Most interesting things starts at getContentPane().setLayout( new BorderLayout() );

  • Video Structure..How to get Frame i? help...

    standard video coding made by a Group of Picture(GOP), GOP it self made by few kind of frame/picture.
    Frame i, Frame p, Frame B, dan Frame D. Frame i is a frame that decode without any reference to another picture, this is the first frame in GOP.All i have is a theory, do anyone know how to get Frame i in JMF?

    Ok.
    I think you have a JFrame and
    a JPanel added to JFrame,
    And this JPanel contains JButton, Am I right?
    Then
    Container parent = button.getParent(); //this will be the JPanel
    Container grandParent = parent.getParent(); //this will be your JFrame
    BR

  • I think another ClassPath problem

    I have a java application (class) called MainClass in package MP1. I want to use an external class in
    it. the class is called kl1.java and here it is.
    package pak1;
    public class kl1 {
    public int k;
    I tried to import that class using JBuilder, Netbeans with no success. I don't want to put that class in my MP1 package (because it is not actually one but many classes, and they are all defined to be part of the pak1.something.something packages). If i put them in my MP1 package i will have to change every class to be part of the MP1.pak1.something.something package which obviously i can't do.
    So the classes i want to use are located at C:\pak1 and my project is located at C:\myProject. How to use those classes. I added the classes with JBuilder somehow and it recognized them i.e. when i started writing import pak.k... it poped up the autofinish dialog with kl1 class showing. so it found the class. but when i compiled it it said couldn't find class.
    the line kl1 k = new kl1(); was an error, it couldn't find kl1.
    Please help. Thanks!

    in the older versions of NetBeans you had to tell your project which folders to include; you used to be able to do it with a right click on resources and browse, but i've not looked how to do the same thing in the new version yet.

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • Compiles but does not execute as expected????

    Here is my code. I can compile and execute but does not perform as expected What do I need to change?
    import java.io.;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.math.*;
    public class CalcTest extends JFrame implements ActionListener, ItemListener
    public JMenuBar createMenuBar()
            JMenuBar mnuBar = new JMenuBar();
            setJMenuBar(mnuBar);
                //Create File & add Exit
            JMenu mnuFile = new JMenu("File", true);
            mnuFile.setMnemonic(KeyEvent.VK_F);
            mnuFile.setDisplayedMnemonicIndex(0);
            mnuBar.add(mnuFile);
            JMenuItem mnuFileExit = new JMenuItem("Exit");
            mnuFileExit.setMnemonic(KeyEvent.VK_F);
            mnuFileExit.setDisplayedMnemonicIndex(1);
            mnuFile.add(mnuFileExit);
            mnuFileExit.setActionCommand("Exit");
            mnuFileExit.addActionListener(this);
            JMenu mnuFunction = new JMenu("Function", true);
            mnuFunction.setMnemonic(KeyEvent.VK_F);
            mnuFunction.setDisplayedMnemonicIndex(0);
            mnuBar.add(mnuFunction);
           JMenuItem mnuFunctionClear = new JMenuItem("Clear");
           mnuFunctionClear.setMnemonic(KeyEvent.VK_F);
           mnuFunctionClear.setDisplayedMnemonicIndex(1);
           mnuFunction.add(mnuFunctionClear);
           mnuFunctionClear.setActionCommand("Clear");
           mnuFunctionClear.addActionListener(this);
            // Fields for Principle 
      JPanel row1 = new JPanel();
      JLabel dollar = new JLabel("How much are you borrowing?"); 
      JTextField money = new JTextField("", 15);
            // Fields for Term and Rate
       JPanel row2 = new JPanel();
       JLabel choice = new JLabel("Select Year & Rate:");
       JCheckBox altchoice = new JCheckBox("Alt. Method");
       JTextField YR = new JTextField("", 4);
       JTextField RT = new JTextField("", 4);
           //Jcombobox R=rate,Y=year
       String[] RY =  {   
            "7 years at 5.35%", "15 years at 5.5 %", "30 years at 5.75%", " "  
      JComboBox mortgage = new JComboBox(RY);
                // Fields for Payment   
        JPanel row3 = new JPanel(); 
        JLabel payment = new JLabel("Your monthly payment will be:");
        JTextField owe = new JTextField(" ", 15); 
              //Scroll Pane and Text Area
       JPanel row4 = new JPanel();
       JLabel amortization = new JLabel("Amortization:");
       JTextArea chart = new JTextArea(" ", 7, 22); 
       JScrollPane scroll = new JScrollPane(chart, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
                                               JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
        StringBuffer amt = new StringBuffer();
        Container pane = getContentPane(); 
        FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
        JButton Cal = new JButton("Calculate"); 
        NumberFormat currency = NumberFormat.getCurrencyInstance();  
      public CalcTest() 
               // Title and Exit of JFrame  
         super("Mortgage and Amortization Calculator"); 
         setSize(475, 328);  
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
                //JFrame layout      
         pane.setLayout(flow);     
               //Input output fields added to JFrame  
         row1.add(dollar);    
         row1.add(money);   
         pane.add(row1);    
         mortgage.setSelectedIndex(3);   
         mortgage.addActionListener(this);    
         mortgage.setActionCommand("mortgage");
         row2.add(altchoice);     
         altchoice.addItemListener(this);  
         row2.add(choice);     
         YR.setEditable(false);    
         RT.setEditable(false);     
         row2.add(YR);     
         row2.add(RT);      
         row2.add(mortgage);    
         pane.add(row2);     
         row3.add(payment);   
         row3.add(owe);       
         pane.add(row3);      
         owe.setEditable(false);  
                 //Scroll Pane added to JFrame     
          row4.add(amortization);      
          chart.setEditable(false); 
          row4.add(scroll);   
          pane.add(row4);     
                //Executable Button- Clear,Exit, Calculate 
          JPanel row5 = new JPanel();
          JButton clear = new JButton("Clear");  
          clear.addActionListener(this);     
          row5.add(clear); 
          pane.add(row5); 
          JButton exit = new JButton("Exit"); 
          exit.addActionListener(this);    
          row5.add(exit);      
          Cal.setEnabled(false);  
          Cal.addActionListener(this); 
          row5.add(Cal);       
          pane.add(row5);   
          setContentPane(pane);   
          setVisible(true); 
      }                    //End of constructor   
        private void calculate()
          String loanAmount = money.getText(); 
             if(loanAmount.equals(""))      
               return;      
               double P = Double.parseDouble(loanAmount);     
               int y;     
               double r;    
             if(altchoice.isSelected())   
              if(YR.getText().equals("") || RT.getText().equals(""))  
                 return;        
               y = Integer.parseInt(YR.getText());     
                r = Double.parseDouble(RT.getText());   
               else     
                  int index = mortgage.getSelectedIndex();  
                  if(index == 3)         
                  return;          
                  int[] terms = { 7, 15, 30 };     
                  double[] rates = { 5.5, 5.35, 5.75 }; 
                  y = terms[index];  
                  r = rates[index];  
                  double In = r / (100 * 12.0);  
                  double M = P * (In / (1 - Math.pow(In + 1, -12.0 * y)));
                  owe.setText(currency.format(M));      
                         //Column Titles for Text Area     
           chart.setText("Pmt#\tPrincipal\tInterest\tBalance\n");  
         for (int i = 0; i < y * 12; i++)     
      {            double interestAccrued = P * In;     
                   double principalPaid = M - interestAccrued;          
                   chart.append(i + 1 + "\t" + currency.format(principalPaid)           
                                    + "\t" + currency.format(interestAccrued)     
                                          + "\t" + currency.format(P) + "\n");      
                    P = P + interestAccrued - M;   
         public void itemStateChanged(ItemEvent ie) 
      {        int status = ie.getStateChange();    
           if (status == ItemEvent.SELECTED)     
               mortgage.setEnabled(false);  
               YR.setEditable(true); 
               RT.setEditable(true);   
               Cal.setEnabled(true);  
            else 
            mortgage.setEnabled(true); 
            YR.setEditable(false);    
            RT.setEditable(false);     
           Cal.setEnabled(false);     
      public void actionPerformed(ActionEvent ae)//Calculations and Button executions
          String command = ae.getActionCommand();  
                  // Exit program      
           if (command.equals("Exit"))   
            System.exit(0);
                  // Cal button 
          if (command.equals("Calculate") || command.equals("mortgage")) 
              calculate();      
                 // Clear fields  
          if (command.equals("Clear")) 
             money.setText(null);
             mortgage.setSelectedIndex(3); 
             owe.setText(null);   
             chart.setText(null); 
    }             //End actionPerformed 
       public static void main(String args[]) throws IOException
               new CalcTest();
    [/Code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Here is the code again
    import java.io.;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.math.*;
    public class CalcTest extends JFrame implements ActionListener, ItemListener
    public JMenuBar createMenuBar()
            JMenuBar mnuBar = new JMenuBar();
            setJMenuBar(mnuBar);
                //Create File & add Exit
            JMenu mnuFile = new JMenu("File", true);
            mnuFile.setMnemonic(KeyEvent.VK_F);
            mnuFile.setDisplayedMnemonicIndex(0);
            mnuBar.add(mnuFile);
            JMenuItem mnuFileExit = new JMenuItem("Exit");
            mnuFileExit.setMnemonic(KeyEvent.VK_F);
            mnuFileExit.setDisplayedMnemonicIndex(1);
            mnuFile.add(mnuFileExit);
            mnuFileExit.setActionCommand("Exit");
            mnuFileExit.addActionListener(this);
            JMenu mnuFunction = new JMenu("Function", true);
            mnuFunction.setMnemonic(KeyEvent.VK_F);
            mnuFunction.setDisplayedMnemonicIndex(0);
            mnuBar.add(mnuFunction);
           JMenuItem mnuFunctionClear = new JMenuItem("Clear");
           mnuFunctionClear.setMnemonic(KeyEvent.VK_F);
           mnuFunctionClear.setDisplayedMnemonicIndex(1);
           mnuFunction.add(mnuFunctionClear);
           mnuFunctionClear.setActionCommand("Clear");
           mnuFunctionClear.addActionListener(this);
            // Fields for Principle 
      JPanel row1 = new JPanel();
      JLabel dollar = new JLabel("How much are you borrowing?"); 
      JTextField money = new JTextField("", 15);
            // Fields for Term and Rate
       JPanel row2 = new JPanel();
       JLabel choice = new JLabel("Select Year & Rate:");
       JCheckBox altchoice = new JCheckBox("Alt. Method");
       JTextField YR = new JTextField("", 4);
       JTextField RT = new JTextField("", 4);
           //Jcombobox R=rate,Y=year
       String[] RY =  {   
            "7 years at 5.35%", "15 years at 5.5 %", "30 years at 5.75%", " "  
      JComboBox mortgage = new JComboBox(RY);
                // Fields for Payment   
        JPanel row3 = new JPanel(); 
        JLabel payment = new JLabel("Your monthly payment will be:");
        JTextField owe = new JTextField(" ", 15); 
              //Scroll Pane and Text Area
       JPanel row4 = new JPanel();
       JLabel amortization = new JLabel("Amortization:");
       JTextArea chart = new JTextArea(" ", 7, 22); 
       JScrollPane scroll = new JScrollPane(chart, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
                                               JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
        StringBuffer amt = new StringBuffer();
        Container pane = getContentPane(); 
        FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
        JButton Cal = new JButton("Calculate"); 
        NumberFormat currency = NumberFormat.getCurrencyInstance();  
      public CalcTest() 
               // Title and Exit of JFrame  
         super("Mortgage and Amortization Calculator"); 
         setSize(475, 328);  
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
                //JFrame layout      
         pane.setLayout(flow);     
               //Input output fields added to JFrame  
         row1.add(dollar);    
         row1.add(money);   
         pane.add(row1);    
         mortgage.setSelectedIndex(3);   
         mortgage.addActionListener(this);    
         mortgage.setActionCommand("mortgage");
         row2.add(altchoice);     
         altchoice.addItemListener(this);  
         row2.add(choice);     
         YR.setEditable(false);    
         RT.setEditable(false);     
         row2.add(YR);     
         row2.add(RT);      
         row2.add(mortgage);    
         pane.add(row2);     
         row3.add(payment);   
         row3.add(owe);       
         pane.add(row3);      
         owe.setEditable(false);  
                 //Scroll Pane added to JFrame     
          row4.add(amortization);      
          chart.setEditable(false); 
          row4.add(scroll);   
          pane.add(row4);     
                //Executable Button- Clear,Exit, Calculate 
          JPanel row5 = new JPanel();
          JButton clear = new JButton("Clear");  
          clear.addActionListener(this);     
          row5.add(clear); 
          pane.add(row5); 
          JButton exit = new JButton("Exit"); 
          exit.addActionListener(this);    
          row5.add(exit);      
          Cal.setEnabled(false);  
          Cal.addActionListener(this); 
          row5.add(Cal);       
          pane.add(row5);   
          setContentPane(pane);   
          setVisible(true); 
      }                    //End of constructor   
        private void calculate()
          String loanAmount = money.getText(); 
             if(loanAmount.equals(""))      
               return;      
               double P = Double.parseDouble(loanAmount);     
               int y;     
               double r;    
             if(altchoice.isSelected())   
              if(YR.getText().equals("") || RT.getText().equals(""))  
                 return;        
               y = Integer.parseInt(YR.getText());     
                r = Double.parseDouble(RT.getText());   
               else     
                  int index = mortgage.getSelectedIndex();  
                  if(index == 3)         
                  return;          
                  int[] terms = { 7, 15, 30 };     
                  double[] rates = { 5.5, 5.35, 5.75 }; 
                  y = terms[index];  
                  r = rates[index];  
                  double In = r / (100 * 12.0);  
                  double M = P * (In / (1 - Math.pow(In + 1, -12.0 * y)));
                  owe.setText(currency.format(M));      
                         //Column Titles for Text Area     
           chart.setText("Pmt#\tPrincipal\tInterest\tBalance\n");  
         for (int i = 0; i < y * 12; i++)     
      {            double interestAccrued = P * In;     
                   double principalPaid = M - interestAccrued;          
                   chart.append(i + 1 + "\t" + currency.format(principalPaid)           
                                    + "\t" + currency.format(interestAccrued)     
                                          + "\t" + currency.format(P) + "\n");      
                    P = P + interestAccrued - M;   
         public void itemStateChanged(ItemEvent ie) 
      {        int status = ie.getStateChange();    
           if (status == ItemEvent.SELECTED)     
               mortgage.setEnabled(false);  
               YR.setEditable(true); 
               RT.setEditable(true);   
               Cal.setEnabled(true);  
            else 
            mortgage.setEnabled(true); 
            YR.setEditable(false);    
            RT.setEditable(false);     
           Cal.setEnabled(false);     
      public void actionPerformed(ActionEvent ae)//Calculations and Button executions
          String command = ae.getActionCommand();  
                  // Exit program      
           if (command.equals("Exit"))   
            System.exit(0);
                  // Cal button 
          if (command.equals("Calculate") || command.equals("mortgage")) 
              calculate();      
                 // Clear fields  
          if (command.equals("Clear")) 
             money.setText(null);
             mortgage.setSelectedIndex(3); 
             owe.setText(null);   
             chart.setText(null); 
    }             //End actionPerformed 
       public static void main(String args[]) throws IOException
               new CalcTest();

Maybe you are looking for

  • Stripping old web pages of font tags : best way?

    I'm converting very old HTML files (we're talking pre-CSS here) for re-publication. These files date back to 1997. Is there some sort of wildcard search expression I can use to strip hundreds of web pages of old HTML font tags (so I can then apply ne

  • Does it have a feature that supports management with accounts, fixed IP, VLAN ?

    I'm not quite familiar with those advanced features if it does exist as the fact that i've been primarily using cheap and unknown AP products for years :D I'm planning on upgrading my APs for personal reasons. Could anyone tell me does it have a feat

  • Component to Firewire

    I am looking for a device that converts Component video and RCA audio to Firewire, so that a movie can be imported into iMovie. I am currently using a Canopus ADVC110 for S-Video but have an HD source with component video and would like to be able to

  • Filesize diminished in iPhoto Library and "!" mark

    Like many others, all of a sudden a lot of my photos are just showing up as exclamation marks in iPhoto although I can see the thumbnails. As suggested by some, I tracked the original files for those photos in the iPhoto Library. My digital camera ta

  • IPhone 5s displays wrong video thumbnails - how to clear cache?

    I have an iphone 5s and in the video app, I see things like Beyonce's video with a picture of the band RUSH, or Blondie's thumbnail for Megadeth.  Anyone know how I might fix this?  I've done a factory reset on settings, and also tried a restore from