Adding JScrollPane to CardLayout

public static void panelLayout (String panel)
        cardPanel.add (Rosters.rosterPanel1, "roster1");
        cardPanel.add (Rosters.rosterPanel2, "roster2");
        cardPanel.add (OP300.evalLoadPane1, "op300load1"); // JScrollPane with JPanel inside
        cardPanel.add (mainPanel, "main");
        CardLayout showPanel = (CardLayout)(cardPanel.getLayout ());
        showPanel.show (cardPanel, panel);
    }I'm trying to add a JScrollPane to my CardLayout just like I have with the other JPanels. All of the other JPanels work fine, but adding the JScrollPane is giving me issues. As soon as PanelLayout() is called, even if it isn't calling for the JScrollPane, I'm getting: Exception occurred during event dispatching:
java.lang.NullPointerException
        at java.awt.Container.addImpl(Container.java:1027)
        at java.awt.Container.add(Container.java:903)
        at HubEvals.panelLayout(HubEvals.java:540)
        at Login.b_loginActionPerformed(Login.java:175)
        at Login.access$000(Login.java:18)
        at Login$1.actionPerformed(Login.java:92)
        ...The JScrollPane modifier is public static so it isn't having problems getting access to it. I even tried putting the JScrollPane inside a JPanel so it would be like:
- JPanel
----- JScrollPane
---------- JPanel (panel that is longer than the frame itself, hence why it's in a scroll pane)
I still got the same error.

This time I remembered to initialize it. I added it to my initComponents() method and I was still getting the problem:public HubEvals ()
        initComponents ();
        new Rosters ();
        new OP300 ();
        RegisterLogin intro = new RegisterLogin ();
        intro.showInDialog (this);
    }I had accidentally typed new OP3O0 (); instead of new OP300 ();. What's up with that? The first thing I typed doesn't even exist as a method, class, or variable and it still passed NetBeans validation. I spent well over 50 minutes on a stupid '0' being an 'O' and the 2 characters look exactly the same in the code font.
Anyway, thanks. Problem solved. Heh. You run into stuff like this when you don't leave the computer for hours at a time.

Similar Messages

  • Adding JScrollPane to JInternalFrame

    Hello, I have been having a rather difficult time adding a a jscrollpane to my jinternalframe. I have a panel that I am adding some objects to. I add that panel to a jscrollpane, then add the jscrollpane to the container of the JInternalFrame. I get no errors, but when I run this thing, the panel spills out over the JInternalFrame, the panel is bigger than the internal frame. When I take the jscrollpane off of it and just add the panel directly to the JInternalFrame, it fits jsut fine. However, I need the scrollbar to view all of the material. Any ideas? Here is a piece of my code.
             JInternalFrame internal = new JInternalFrame("New Tree",true,true,true,true);
          Container c = internal.getContentPane();
    //this panel is something I created earlier and have added stuff to it
    //panel is of the type java.awt.panel
            panel.setBackground(Color.white);
            JScrollPane jsp = new JScrollPane();
            jsp.setViewportView(panel);
            c.add(jsp);
            internal.setSize(700,400);
            internal.setOpaque(true);
            internal.setVisible(true);
    //I add it to a desktop pane a little later on

    Here's an example:
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameTest extends JFrame {
         private JInternalFrame internalFrame1;
         private JInternalFrame internalFrame2;
         private JScrollPane scrollPane;
         private JDesktopPane desktopPane;
         public InternalFrameTest() {
              try {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   desktopPane = new JDesktopPane();
                   scrollPane = new JScrollPane(desktopPane);
                   desktopPane.setPreferredSize(new Dimension(350, 250));
                   internalFrame1 = new JInternalFrame();
                   desktopPane.add(internalFrame1);
                   internalFrame1.setBounds(30, 30, 100, 100);
                   internalFrame1.setVisible(true);
                   internalFrame2 = new JInternalFrame();
                   desktopPane.add(internalFrame2);
                   internalFrame2.setBounds(150, 100, 100, 100);
                   internalFrame2.setVisible(true);
                   getContentPane().add(scrollPane, BorderLayout.CENTER);
                   pack();
                   setSize(300, 200);
                   setLocationRelativeTo(null);
                   setVisible(true);
              } catch (Exception e) { e.printStackTrace(); }
         public static void main(String[] args) { new InternalFrameTest(); }
    }

  • Adding JScrollPane on JPanel??Is there any problem.??

    hi,
    I have a JPanel over which i added a JScrollPane on to whose view portvie i added a JTable.
    But the problem is the table is not getting visble.Not only table all the components i add to scrollpane which on a panel is not getting displayed.
    Am i missing something??
    final JScrollPane scrollPane = new JScrollPane();
              panel.add(scrollPane);
              table = new JTable();
              scrollPane.setViewportView(table);

    Make sure to add the panel to the content pane as well.
    If the problem still persists, then please post a simple executable demo program that demonstrates the behavior.

  • Adding JScrollPane to a JList problems

    Hi,
    I am having problem in trying to add a JScrollPane to a JList, it doesnt appear i don't understand what i am doing wrong.
    private String [] mainMenu = {"Phonebook", "Messages", "User Options", "Phone Status"};
    private JList main = new JList(mainMenu);
    private JScrollPane scrolling = new JScrollPane(main);
    public Mobile()
             main.setLocation(60, 110);
             main.setSize(90, 50);
             add(scrolling);
             scrolling.setVisible(true);
    }

    The code to run the app is:
    import java.awt.*;
    import javax.swing.*;
    class MobileGUI {
         public static void main(String[] args) {
              JFrame frame = new JFrame("Mobile Phone Simulation");
              Container pane = frame.getContentPane();
              pane.add(new Mobile());
              frame.setSize(340, 625);
              frame.show();
    }The class that contains the components is:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    class Mobile extends JComponent {
    private String[] mainMenu = {"Phonebook", "Messages", "User Options", "Phone Status"};
    private JList main = new JList(mainMenu);
    private JScrollPane scrolling = new JScrollPane(main);
    public JTextArea display = new JTextArea(6, 30);
    public MobileGUI()
              //Displays
              setLayout(null);
              //Display for messages
              display.setLocation(120, 60);
              display.setSize(90, 50);
              add(display);
              display.setVisible(false);
              //MainMenu Jlist Display
              main.setLocation(120, 60);
              main.setSize(90, 50);
              add(scrolling);
              scrolling.setVisible(true);
         public void paint(Graphics g) {
         g.setColor(Color.gray.brighter());
         g.fillRoundRect(30, 30, 270, 530, 40, 20);
         g.setColor(Color.black);
         g.fillArc(30, 30, 270, 320, 0, 180);
        g.fillArc(30, -180, 270, 740, 180, 180);
         g.setColor(Color.gray);     
         super.paint(g);       
    }The JList does not appear neither does the JScrollPane

  • Adding JScrollPane doesn't work... hmm....

        private void jbInit() throws Exception {
            this.getContentPane().setLayout(null);
            this.setSize(new Dimension(400, 300));
            this.setTitle("All Videos Own By Store");
            ta_show.setBounds(new Rectangle(30, 25, 320, 220));
            ta_show.setEditable(false);
            ta_show.setEnabled(false);
            JScrollPane scrollingArea = new JScrollPane(ta_show);
            getContentPane().add(scrollingArea);
            this.getContentPane().add(ta_show, null);
            //this.getContentPane().add(scrollingArea);
            this.setVisible(true);
        }ta_show is the JTextArea...
    I will load a text file into the JTextArea and it should show the JScrollPane since the text file is quite large... But it doesn't show..
    Any ideas?

    try this for size:
        private void jbInit()
            JPanel p = new JPanel();
            p.setPreferredSize(new Dimension(400, 300));
            p.setLayout(new BorderLayout());
            int eb = 20;
            p.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            ta_show.setPreferredSize(new Dimension(800, 600)); // or however big you want it
            ta_show.setEditable(false);
            //ta_show.setEnabled(false);
            JScrollPane scrollpane = new JScrollPane(ta_show);
            p.add(scrollpane, BorderLayout.CENTER);
            getContentPane().add(p);
        }

  • Adding KeyEvents to cardLayout tabs

    I am upgrading an app that used a cardLayout to create tab functionality. I am trying to add a Tab-Key or Arrow-key functionality to this cardLayout that would allow for me to shift thru the tabs, the tabs are drawn tabs icons, I use a mouseListener to show/select the tab. When I add a keyListener to the class it does not work.
         addKeyListener(new KeyAdapter()
              public void keyPressed(KeyEvent ke)
                   int key = ke.getID();
                   if(ke.getKeyCode() == KeyEvent.VK_TAB)
                        System.out.println("Entered Tab Key Adapter");
                        setSelected((selected+1) % nCards,false);
                        next();
              public void keyReleased(KeyEvent ke)
              public void keyTyped(KeyEvent e)
    This is the listener functions. Also the class is extended from the panel class.
    Does anyone know this solution?
    Thanks

    I would say, for this situation, it would be better to "upgrade" the app to use a JTabbedPane instead of a CardLayout. All the functionality that you'd need is there.

  • Problem on JScrollPane

    I'm trying to put some JLabel to a JPanel and then put it into a JScrollPane but somehow I dont see any JScrollBar appear anywhere...is there something wrong that I did?Or do I have to manually set a scrollbar ?.. I have try manually put in one but still got the same result...I did read some example on it but it works for them, when I try to do the exactly the same thing in my code...it fails....
    JLabel a = new JLabel("a");
    JLabel b = new JLabel("b");
    JLabel c = new JLabel("c");
    JPanel contain = new JPanel(new GridLayout(3,1));
    contain.add(a);
    contain.add(b);
    contain.add(c);
    JScrollPane AScroll = new JScrollPane()
    AScroll.add(contain);thx for the help

    First of all, thank you for your suggetion..
    After I try your method of doing it..I still get the same result...Here is my actual code..
              NewLayout = new GridLayout(2 * NumOfRiding,2);
              NewLayout.setVgap(4);
              InfoTextPanel.setLayout(NewLayout);
              InfoTextPanel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
              for(int i = 0; i < NumOfRiding; i++){
                   CandNameLabel = new JLabel("Canditate " + (i+1) + " Name");
                   InfoTextPanel.add(CandNameLabel);    //first label add into infotextpanel
                   CandNameText = new JTextField(10);     
                   CandVector.add(CandNameText);
                   InfoTextPanel.add(CandNameText);     //a TextField add into infotextpanel
                   PartyLabel = new JLabel("Party");
                   InfoTextPanel.add(PartyLabel);          //another label add into a infotextpanel
                   PartyNameList = new JComboBox(PartyName);
                   CandPartyVector.add(PartyNameList);
                   InfoTextPanel.add(PartyNameList);     //a combobox added into the infotextpanel
                   InfoPanel.add(InfoTextPanel);          //the infoTextPanel is add into InfoPanel so more InfoTexPanel add be added
              JScrollPane AScroll = new JScrollPane();
              AScroll.setViewportView(InfoPanel);And After this.. I have to put this scrollpane into another panel and then into the actual windows...

  • HOW TO: SDI + Default Focus + CardLayout + jdk1.4

    Hi,
    I need some help to solve some focus issues.
    I use jdk 1.4.1_01 and Win2000
    I have a SDI application composed with:
    < = include
    JFrame < JScrollPane < JPanel (CardLayout) < JPanel 1 < JTextField11 *
    | | < JTextField12
    | | < JTextField13
    | < JPanel 2 < JTextField21 *
    | | < JTextField22
    | | < JTextField23
    | | < JTextField24
    | < JPanel 3 < JTextField31 *
    | < JTextField32
    | < JTextField33
    | < JTextField34
    | < JTextField35
    < JToolBar < JButton 1
    < JButton 2
    < JButton 3
    When you push :
    JButton 1 -> JPanel 1 is displayed
    JButton 2 -> JPanel 2 is displayed
    JButton 3 -> JPanel 3 is displayed
    I need to set the focus like this:
    So when you push :
    JButton 1 -> JPanel 1 is displayed AND JTextField11 get the focus
    JButton 2 -> JPanel 2 is displayed AND JTextField21 get the focus
    JButton 3 -> JPanel 3 is displayed AND JTextField31 get the focus
    How can i do that??? I tried several solution find here in the forum but no way... :((
    I need some help.
    JMi

    ok, done with requestFocus()

  • Losing my mind with a scrollpane

    Hello all. I am trying to get a scroll pane to work in an application that I have built for school. I am trying to get an amortization table to scroll through for a mortgage calculator. It isn't recognizing my scrollpane and I am not sure why. Could someone give me a push in the right direction.
    import javax.swing.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    public class MortCalcWeek3 extends JFrame implements ActionListener
         DecimalFormat twoPlaces = new DecimalFormat("#,###.00");//number format
         int L[] = {7, 15, 30};
         double I[] = {5.35, 5.5, 5.75};
         double P, M, J, H, C, Q;
         JPanel panel = new JPanel ();//creates the panel for the GUI
         JLabel title = new JLabel("Mortgage Calculator");
         JLabel PLabel = new JLabel("Enter the mortgage amount: ");
         JTextField PField = new JTextField(10);//field for obtaining user input for mortgage amount
         JLabel choices = new JLabel ("Choose the APR and Term in Years");
         JTextField choicestxt = new JTextField (0);
         JButton calcButton = new JButton("Calculate");
         JTextField payment = new JTextField(10);
         JLabel ILabel = new JLabel("Annual Percentage Rate: choose one");
         String [] IChoice = {I[0] + "", I[1] + "", I[2] + ""};
         JComboBox IBox = new JComboBox(IChoice);
         JLabel LLabel = new JLabel("Term (in years): choose one");
         String [] LChoice = {L[0] + "", L[1] + "", L[2] + ""};
         JComboBox LBox = new JComboBox(LChoice);
         JLabel amortBox = new JLabel("Amortiaztion Table");
         JScrollPane amortScroll = new JScrollPane();
         public MortCalcWeek3 () //creates the GUI window
                        super("Mortgage Calculator");
                        setSize(300, 400);
                        panel.setBackground (Color.white);
                        panel.setLayout(null);
                        panel.setPreferredSize(new Dimension(500, 500));
                        setResizable(false) ;
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        //Creates the container
                        Container contentPane = getContentPane();
                        FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
                        panel.setLayout(fresh);
                        //identifies trigger events
                        calcButton.addActionListener(this);
                        PField.addActionListener(this);
                        IBox.addActionListener(this);
                        LBox.addActionListener(this);
                        panel.add(PLabel);
                        panel.add(PField);
                        panel.add(choices);
                        panel.add(choicestxt);
                        panel.add(ILabel);
                        panel.add(IBox);
                        IBox.setBackground (Color.white);
                        panel.add(LLabel);
                        panel.add(LBox);
                        LBox.setBackground (Color.white);
                        panel.add(calcButton);
                        calcButton.setBackground (Color.white);
                        panel.add(payment);
                        payment.setBackground (Color.white);
                        panel.add(amortBox);
                        payment.setEditable(false);
                        panel.add(amortScroll);
                        setContentPane(panel);
                        setVisible(true);
         }// end of GUI info
              public void actionPerformed(ActionEvent e) {
                   MortCalcWeek3();     //calls the calculations
              public void MortCalcWeek3() {     //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble((String) IBox.getSelectedItem());
                   double L = Double.parseDouble((String) LBox.getSelectedItem());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
         //public void amort() {
                   //int N = (L * 12);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  String showAmort = twoPlaces.format(H + C + Q);
                                amortScroll(showAmort);
              public static void main(String[] args) {
              MortCalcWeek3 app = new MortCalcWeek3();
    }//end main
    }//end the programI am getting an error stating that it cannot resolve the symbol and it is reffering to my "amortScroll(showAmort);" statement. Please help.

    a scrollpane generally contains another component e.g. in this a JTextArea,
    where you can display the output of your while().
    try these changes
    1)
    JLabel amortBox = new JLabel("Amortiaztion Table");
    JTextArea ta = new JTextArea();//<----------------------added
    //JScrollPane amortScroll = new JScrollPane();//<-------changed to below line
    JScrollPane amortScroll = new JScrollPane(ta);
    2)
    panel.add(amortScroll);
    amortScroll.setPreferredSize(new Dimension(275,100));//<----------added
    setContentPane(panel);
    setVisible(true);
    3)
    String showAmort = twoPlaces.format(H + C + Q);
    //amortScroll(showAmort);//<---------------changed to below line
    ta.append(showAmort+"\n");

  • Newbie: How to design layering?

    I am sorry if this question isn�t the clearest but I am pretty new to Java. And please feel free to critic how I ask this question and the program I am going to show, I hope this will help me in the future ask better questions and write better code.
    This program was something I was working on for class that I couldn't finish. It is something I really need to learn because I am taking the second Java class and i am sure this is something I really will need to know.
    Question: I am trying to finish this program and my goal is to click on the order button and have all the panels I have be cleared. ( I change the setVisible to false). But the problem I am facing is when I try to add more panels the panels are being added to the bottom. I am pretty sure this is happening because I am not starting a new frame. But that is the question, how do I clear the first frame and all the panes and start a new one?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    class LowFatBurgerGUI extends JFrame
    //Frame properties
    private static final int FRAME_WIDTH = 575;
    private static final int FRAME_HEIGHT = 500;
    private static final int FRAME_X_ORIGIN = 150;
    private static final int FRAME_Y_ORIGIN = 250;
    //Button properties
    private static final int BUTTON_WIDTH = 150;
    private static final int BUTTON_HEIGHT = 30;
    private int tofuCount = 0;
    private int cajunCount = 0;
    private int buffaloCount = 0;
    private int rainbowCount = 0;
    private int riceCount = 0;
    private int noSaltCount = 0;
    private int zucchiniCount = 0;
    private int brownCount = 0;
    private int mochaCount = 0;
    private int latteCount = 0;
    private int espresCount = 0;
    private int oolongCount = 0;
    private int tofuBurgercount = 0;
    private int cajunChickencount = 0;
    private int buffaloWingscount = 0;
    private int rainbowFilletcount = 0;
    private int riceCrackercount = 0;
    private int noSaltFriescount = 0;
    private int zucchinicount = 0;
    private int brownRicecount = 0;
    private int cafeMochacount = 0;
    private int cafeLattecount = 0;
    private int espressocount = 0;
    private int OolongTeacount = 0;
    private static final double TOFU_BURGER_PRICE = 3.49;
    private static final double CAJUN_CHICKEN_PRICE = 4.59;
    private static final double BUFFALO_WINGS_PRICE = 3.99;
    private static final double RAINBOW_FILLET_PRICE = 2.99;
    private static final double RICE_CRACKER_PRICE = 0.79;
    private static final double NO_SALT_FRIES_PRICE = 0.69;
    private static final double ZUCCHINI_PRICE = 1.09;
    private static final double BROWN_RICE_PRICE = 0.59;
    private static final double CAFE_MOCHA_PRICE = 1.99;
    private static final double CAFE_LATTE_PRICE = 1.99;
    private static final double ESPRESSO_PRICE = 2.49;
    private static final double OOLONG_TEA_PRICE = 0.99;
    //Initalize food buttons
    private JButton tofuBurgerButton;
    private JButton cajunChickenButton;
    private JButton buffaloWingsButton;
    private JButton rainbowFilletButton;
    private JButton riceCrackerButton;
    private JButton noSaltFriesButton;
    private JButton zucchiniButton;
    private JButton brownRiceButton;
    private JButton cafeMochaButton;
    private JButton cafeLatteButton;
    private JButton espressoButton;
    private JButton OolongTeaButton;
    //control buttons
    private JButton orderButton;
    private JButton cancelButton;
    //Subtotal output
    private static final String MESSAGE = " Your subtotal: $ ";
    //BLANK
    private static final String BLANK = "";
    //Initialize subtota
    private double subTotal = 0.0;
    private JLabel countLabel;
    JPanel headerPanel, menuPanel, buttomPanel, orderOutputPanel,
    middleOutputPanel, buttomOutputPanel;
    JFrame lowFatBurgerOrderFrame, lowFatBurgerOutputFrame;
    * Start
    public static void main(String [] args)
    new LowFatBurgerGUI();
    public LowFatBurgerGUI()
    lowFatBurgerMain();
    setVisible(true);
    private void lowFatBurgerMain()
    lowFatBurgerOrderFrame();
    //lowFatBurgerOutputFrame();
    tofuBurgerButton();
    cajunChickenButton();
    buffaloWingsButton();
    rainbowFilletButton();
    riceCrackerButton();
    noSaltFriesButton();
    zucchiniButton();
    brownRiceButton();
    cafeMochaButton();
    cafeLatteButton();
    espressoButton();
    OolongTeaButton();
    orderButton();
    cancelButton();
    lowFatBurgerOrderPanel();
    //lowFatBurgerOutputPanel();
    //Create order frame
    private void lowFatBurgerOrderFrame()
    // set the frame properties
    setSize ( FRAME_WIDTH, FRAME_HEIGHT );
    setResizable ( false );
    setTitle ( "Welcome to Low Fat Bugers ");
    setLocation ( FRAME_X_ORIGIN, FRAME_Y_ORIGIN );
    //Create output frame
    private void lowFatBurgerOutputFrame()
    // set the frame properties
    setSize ( FRAME_WIDTH, FRAME_HEIGHT );
    setResizable ( false );
    setTitle ( "Finalize your order ");
    setLocation ( FRAME_X_ORIGIN, FRAME_Y_ORIGIN );
    lowFatBurgerOutputPanel();
    //Create food buttons
    private void tofuBurgerButton()
    tofuBurgerButton = new JButton("Tofu Burger");
    tofuBurgerButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    tofuBurgerCount(event);
    private void cajunChickenButton()
    cajunChickenButton = new JButton("Cajun Chicken");
    cajunChickenButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    cajunChickenCount(event);
    private void buffaloWingsButton()
    buffaloWingsButton = new JButton("Buffalo Wings");
    buffaloWingsButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    buffaloWingsCount(event);
    private void rainbowFilletButton()
    rainbowFilletButton = new JButton("Rainbow Fillet");
    rainbowFilletButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    rainbowFilletCount(event);
    private void riceCrackerButton()
    riceCrackerButton = new JButton("Rice Cracker");
    riceCrackerButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    riceCrackerCount(event);
    private void noSaltFriesButton()
    noSaltFriesButton = new JButton("No-Salt Fries");
    noSaltFriesButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    noSaltFriesCount(event);
    private void zucchiniButton()
    zucchiniButton = new JButton("Zucchini");
    zucchiniButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    zucchiniCount(event);
    private void brownRiceButton()
    brownRiceButton = new JButton("Brown Rice");
    brownRiceButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    brownRiceCount(event);
    private void cafeMochaButton()
    cafeMochaButton = new JButton("Cafe Mocha");
    cafeMochaButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    cafeMochaCount(event);
    private void cafeLatteButton()
    cafeLatteButton = new JButton("Cafe Latte");
    cafeLatteButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    cafeLatteCount(event);
    private void espressoButton()
    espressoButton = new JButton("Espresso");
    espressoButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    espressoCount(event);
    private void OolongTeaButton()
    OolongTeaButton = new JButton("Oolong Tea");
    OolongTeaButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    OolongTeaCount(event);
    private void orderButton()
    orderButton = new JButton("Order");
    orderButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    OrderButtonAction(event);
    private void cancelButton()
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent event)
    CancelButtonAction(event);
    //Create order panels
    public void lowFatBurgerOrderPanel()
    Container orderPane;
    orderPane = getContentPane();
    orderPane.setLayout (new GridLayout( 3, 1 ));
    //header Panel
    headerPanel = new JPanel();
    headerPanel.setBorder(BorderFactory.createTitledBorder( "Menu"));
    //menu middle
    menuPanel = new JPanel();
    menuPanel.setBorder(BorderFactory.createTitledBorder("Items"));
    menuPanel.setLayout(new GridLayout (4, 3));
    menuPanel.add(tofuBurgerButton);
    menuPanel.add(riceCrackerButton);
    menuPanel.add(cafeMochaButton);
    menuPanel.add(cajunChickenButton);
    menuPanel.add(noSaltFriesButton);
    menuPanel.add(cafeLatteButton);
    menuPanel.add(buffaloWingsButton);
    menuPanel.add(zucchiniButton);
    menuPanel.add(espressoButton);
    menuPanel.add(rainbowFilletButton);
    menuPanel.add(brownRiceButton);
    menuPanel.add(OolongTeaButton);
    //Buttom Panel
    buttomPanel = new JPanel();
    buttomPanel.setBorder(BorderFactory.createTitledBorder("New"));
    buttomPanel.add(countLabel = new JLabel(" Your subtotal: "));
    buttomPanel.setLayout(new GridLayout(0,2));
    buttomPanel.add(orderButton);
    buttomPanel.add(cancelButton);
    //contentPane
    orderPane.add(headerPanel);
    orderPane.add(menuPanel);
    orderPane.add(buttomPanel);
    //Create output panel
    public void lowFatBurgerOutputPanel()
    Container outputPane;
    outputPane = getContentPane();
    outputPane.setLayout (new GridLayout( 3, 1 ));
    orderOutputPanel = new JPanel();
    orderOutputPanel.setBorder(BorderFactory.createTitledBorder("Output"));
    middleOutputPanel = new JPanel();
    middleOutputPanel.setBorder(BorderFactory.createTitledBorder("something"));
    buttomOutputPanel = new JPanel();
    buttomOutputPanel.setBorder(BorderFactory.createTitledBorder("new"));
    outputPane.add(orderOutputPanel);
    outputPane.add(middleOutputPanel);
    outputPane.add(buttomOutputPanel);
    //Craete and count the number of times a button is clicked
    void tofuBurgerCount(ActionEvent event)
    tofuBurgercount++;
    setLableTextSubtotal();
    void cajunChickenCount(ActionEvent event)
    cajunChickencount++;
    setLableTextSubtotal();
    void buffaloWingsCount(ActionEvent event)
    buffaloWingscount++;
    setLableTextSubtotal();
    void rainbowFilletCount(ActionEvent event)
    rainbowFilletcount++;
    setLableTextSubtotal();
    void riceCrackerCount(ActionEvent event)
    riceCrackercount++;
    setLableTextSubtotal();
    void noSaltFriesCount(ActionEvent event)
    noSaltFriescount++;
    setLableTextSubtotal();
    void zucchiniCount(ActionEvent event)
    zucchinicount++;
    setLableTextSubtotal();
    void brownRiceCount(ActionEvent event)
    brownRicecount++;
    setLableTextSubtotal();
    void cafeMochaCount(ActionEvent event)
    cafeMochacount++;
    setLableTextSubtotal();
    void cafeLatteCount(ActionEvent event)
    cafeLattecount++;
    setLableTextSubtotal();
    void espressoCount(ActionEvent event)
    espressocount++;
    setLableTextSubtotal();
    void OolongTeaCount(ActionEvent event)
    OolongTeacount++;
    setLableTextSubtotal();
    void OrderButtonAction(ActionEvent event)
    headerPanel.setVisible(false);
    menuPanel.setVisible (false);
    buttomPanel.setVisible(false);
    lowFatBurgerOutputFrame();
    // Clear order
    void CancelButtonAction(ActionEvent event)
    countLabel.setText(BLANK);
    countLabel.setText(" Cancelled Order");
    tofuBurgercount = 0;
    cajunChickencount = 0;
    buffaloWingscount = 0;
    rainbowFilletcount = 0;
    riceCrackercount = 0;
    noSaltFriescount = 0;
    zucchinicount = 0;
    brownRicecount = 0;
    cafeMochacount = 0;
    cafeLattecount = 0;
    espressocount = 0;
    OolongTeacount = 0;
    private void setLableTextSubtotal()
    DecimalFormat df = new DecimalFormat("0.00");
    countLabel.setText(MESSAGE + df.format((
    TOFU_BURGER_PRICE * tofuBurgercount
    + CAJUN_CHICKEN_PRICE * cajunChickencount
    + BUFFALO_WINGS_PRICE * buffaloWingscount
    + RAINBOW_FILLET_PRICE * rainbowFilletcount
    + RICE_CRACKER_PRICE * riceCrackercount
    + NO_SALT_FRIES_PRICE * noSaltFriescount
    + ZUCCHINI_PRICE * zucchinicount
    + BROWN_RICE_PRICE * brownRicecount
    + CAFE_MOCHA_PRICE * cafeMochacount
    + CAFE_LATTE_PRICE * cafeLattecount
    + ESPRESSO_PRICE * espressocount
    + OOLONG_TEA_PRICE * OolongTeacount)));
    //Create a window closer
    private void addWindowCloseListener()
    this.addWindowListener(new java.awt.event.WindowAdapter()
    public void windowClosing(WindowEvent event)
    quit(event);
    void quit(WindowEvent event)
    System.exit(0);
    }

    And please feel free to critic how I ask this question and the program I am going to show, I hope this will help me in the future ask better questions and write better code.1) Use the "preview" link before posting your question. As you have noticed all your code has lost its formatting and is left justified. I'm sure you don't code like this so don't ask as to read it like this.
    2) So you ask how to I keep the formatting of the posted code? Well, did you notice the buttons at the top of the message box or the "Formatting Tips" link.
    3) Post a small executable version of your code that demonstrates the problem. I hope you don't expect us to read through hundreds of lines of unnecessary code. Most problems can be demonstrated in about 20 lines of code and the side benefit is many times you find your problem while creating the sample code.
    But the problem I am facing is when I try to add more panels the panels are being added to the bottomThis is because of the LayoutManager you are using. Most LayoutManagers just keep displaying the component as it is added to the container. One way around this is to remove(...) the existing component before adding the new component (check out the Container API for more information about the remove(...) methods). Or maybe use a different LayoutManager like a BorderLayout which replaces components that are added or a CardLayout which allow you to display multiple components in the same area.
    I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]Using Layout Managers.

  • JScroller on JTable and table size

    Hi everyone...
    I have a small problem...i added JScrollPane to my JTable...but if i do the following...
    JScrollPane contentScroller= new JScrollPane(myJTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);In this case scroller works great....accept if i have a smaller data set to show...for example only one column...
    Basically what i would like is to be able to set like minimum size of my JTable...is that possible...

    Oh ya...
    sorry i apologize...
    Well basically what i did is the following...
    In the constructor of my sub-class that extends JTable i set the following property:
    this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    /*...........................................................................*/ And then i also added the following code...(i created some additional methods...i dont really know if this is the right way but i didnt find anything more suitable for my problem)
    /*i set JScrollPane onto witch i added my JTable class instance, to a private JscrollPane variable*/
    public void setParentJPanel(JScrollPane parentJScrollPane){
            this.parentJScrollPane = parentJScrollPane;
    /*I only added these 3 methods cos i wanted to get the size of JScrollPane onto witch i added my JTable class instance*/
        public JScrollPane getParentJPanel(){
            return this.parentJScrollPane;
    /*this methods sort of sets all the columns to equal size witch i guess i wanted it to do...*/
        public void setAllColumnsWidth(){
            int parentWidth = this.getParentJPanel().getWidth();
            int columnNumber = this.getColumnNumber();/*method that i wrote to work with another class that works with database*/
            int columnWidth = parentWidth/columnNumber;
            for(int i=0;i < columnNumber;i++)
                this.getColumnModel().getColumn(i).setPreferredWidth(columnWidth);     
        }Hmmm sorry again for not posting my solution...its not really that much impressive thats why i didnt post it the first time...
    Well i hope it helps....(what i needed is basically how to set columns to as equal size as possible...)

  • Problem while setting background color for jsplit pane

    Hi ALL,
    i am using jsplit frame inside jframe.
    i placed jtree inside left jsplit frame.
    I am not able to set background clolr to jsplit frame.
    when i hide(jtree.setvisible(false)) jtree is shows default background color.it is not showing backgroun color which i set.

    In the below code,i am adding jtree inside jscrollpane and i am adding jscrollpane inside jsplitpane.
    whenever i am setting jtree.setvisible(false),it must show background color which is i am setting for jscrollpane .but its showing default background color.
    Please help me.
    * Demo.java
    * Created on August 19, 2008, 1:44 PM
    public class Demo extends javax.swing.JFrame {
    /** Creates new form Demo */
    public Demo() {
    initComponents();
    jTree1.setVisible(false);
    jScrollPane1.setBackground(new java.awt.Color(136, 194, 252));
    jSplitPane1.setBackground(new java.awt.Color(136, 194, 252));    }
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTree1 = new javax.swing.JTree();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(jTree1);
            jSplitPane1.setLeftComponent(jScrollPane1);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            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 Demo().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JSplitPane jSplitPane1;
        private javax.swing.JTree jTree1;
        // End of variables declaration

  • Pie Chart is not visible

    I cannot get my pie chart to show in my JPanel. I am not sure why that is or how to get it to display. Everything compiles fine...I feel like an idiot. Anyway, could you look at this and let me know what I could be doing wrong. My piechart starts on line 302.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    public class MortCalcWeek5p extends JFrame implements ActionListener
         DecimalFormat twoPlaces = new DecimalFormat("#,###.00");//number format
         int L[] = {7, 15, 30};
         double I[] = {5.35, 5.5, 5.75};
         double P, M, J, H, C, Q;
         boolean manual = true;
         JPanel panel = new JPanel ();
         JRadioButton opt1 = new JRadioButton ("Manual Input", true);
         JRadioButton opt2 = new JRadioButton ("Menu Selections", false);
         ButtonGroup radioSelect = new ButtonGroup();
         JLabel PLabel = new JLabel("Enter the mortgage amount: ");
         JTextField PField = new JTextField(10);//field for obtaining user input for mortgage amount
         JLabel LLabel1 = new JLabel("Enter the term in years: ");
         JTextField LField = new JTextField(3);//field for obtaining user input for term in years
         JLabel ILabel1 = new JLabel("Enter the interest rate: ");
         JTextField IField = new JTextField(5);//field for obtaining user input for interest rate
         JLabel choices = new JLabel ("Or Choose the Interest Rate and Term in Years");
         JButton calcButton = new JButton("Calculate");
         JButton clearButton = new JButton("Clear");
         JButton exitButton = new JButton("Exit");
         JTextField payment = new JTextField(10);
         JLabel ILabel2 = new JLabel("Interest Rate: choose one");
         String [] IChoice = {I[0] + "", I[1] + "", I[2] + ""};
         JComboBox IBox = new JComboBox(IChoice);
         JLabel LLabel2 = new JLabel("Term (in years): choose one");
         String [] LChoice = {L[0] + "", L[1] + "", L[2] + ""};
         JComboBox LBox = new JComboBox(LChoice);
         JLabel amortBox = new JLabel("Amortization Table");
         JTextArea ta = new JTextArea();//<----------------------added
         //JScrollPane amortScroll = new JScrollPane();//
         JScrollPane amortScroll = new JScrollPane(ta, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         public MortCalcWeek5p () //creates the GUI window
                        super("Mortgage Calculator Week 5");
                        setSize(500, 400);
                        panel.setBackground (Color.white);
                        panel.setLayout(null);
                        panel.setPreferredSize(new Dimension(900, 500));
                        setResizable(false) ;
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        //Creates the container
                        Container contentPane = getContentPane();
                        FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
                        panel.setLayout(fresh);
                        //identifies trigger events
                        calcButton.addActionListener(this);
                        clearButton.addActionListener(this);
                      exitButton.addActionListener(this);
                        PField.addActionListener(this);
                        LField.addActionListener(this);
                        IField.addActionListener(this);
                        opt1.addActionListener(this);
                        opt2.addActionListener(this);
                        panel.setLayout(fresh);
                        //Options
                        radioSelect.add(opt1);
                        radioSelect.add(opt2);
                        panel.add(opt1);
                        opt1.setBackground (Color.white);
                        panel.add(opt2);
                        opt2.setBackground (Color.white);
                        //Manual Entries
                        panel.add(PLabel);
                        panel.add(PField);
                        panel.add(LLabel1);
                        panel.add(LField);
                        panel.add(ILabel1);
                        panel.add(IField);
                        //Pre-set Entries
                        panel.add(choices);
                        panel.add(ILabel2);
                        panel.add(IBox);
                        IBox.setBackground (Color.white);
                        panel.add(LLabel2);
                        panel.add(LBox);
                        LBox.setBackground (Color.white);
                        //Buttons
                        panel.add(calcButton);
                        calcButton.setBackground (Color.white);
                        panel.add(payment);
                        payment.setBackground (Color.white);
                        panel.add(clearButton);
                        clearButton.setBackground (Color.white);
                        panel.add(exitButton);
                        exitButton.setBackground (Color.white);
                        //Amortization Table
                        panel.add(amortBox);
                        payment.setEditable(false);
                        panel.add(amortScroll);
                        amortScroll.setPreferredSize(new Dimension(600,300));//<----------added
                        setContentPane(panel);
                        //Pie Chart
                        //panel.add(PieChart);
                        setVisible(true);
         }// end of GUI info
              public void actionPerformed(ActionEvent e)
                   Object source = e.getSource();
                   if (source == calcButton)
                        try
                        if (manual)
                             Calculations_manual();
                        else Calculations_menu();
                   catch(NumberFormatException event)
                        JOptionPane.showMessageDialog(null, "You did not enter a number.\n\nYou're not too bright are you?\n\nTry again.", "ERROR", JOptionPane.ERROR_MESSAGE);
                   if (source == clearButton)
                   reset();
                   if (source == exitButton)
                   end();
                   if (source == opt1)
                   IBox.setEnabled(false);
                   LBox.setEnabled(false);
                   LField.setEnabled(true);
                   LField.setEditable(true);
                   IField.setEnabled(true);
                   IField.setEditable(true);
                   manual = true;
                   if (source == opt2)
                   IBox.setEnabled(true);
                   LBox.setEnabled(true);
                   LField.setEnabled(false);
                   LField.setEditable(false);
                   IField.setEnabled(false);
                   IField.setEditable(false);
                   manual = false;
              public void Calculations_menu() //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble((String) IBox.getSelectedItem());
                   double L = Double.parseDouble((String) LBox.getSelectedItem());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  //String showAmort = twoPlaces.format(H + C + Q);
                                  //amortScroll(showAmort);
                                //ta.append("Month " + month);
                                ta.append("Interest Paid: " + twoPlaces.format(H));
                                ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
                                ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");
              public void Calculations_manual() //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble(IField.getText());
                   double L = Double.parseDouble(LField.getText());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  //String showAmort = twoPlaces.format(H + C + Q);
                                  //amortScroll(showAmort);
                                //ta.append("Month " + month);
                                ta.append("Interest Paid: " + twoPlaces.format(H));
                                ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
                                ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");
              // resets GUI for another calculation
              public void reset ()
              PField.setText(null);
              payment.setText(null);
              ta.setText(null);
              LField.setText(null);
              IField.setText(null);
              // ends GUI and exits program
              public void end()
              System.exit(0);
    public class PieChart extends JComponent {
        // Class to hold a value for a slice
        class PieSlice
            //private variables
            double value;
            Color color;
            public PieSlice(double value, Color color)
                this.value = value;
                this.color = color;
            }//end Constructor
           } //end class PieSlice
        //private variable slices are array of PieSlice
        PieSlice[] slices = new PieSlice[2];
        //constructor
        PieChart(double C, double H)
            slices[0] = new PieSlice(C, Color.red);
            slices[1] = new PieSlice(H, Color.green);
            setVisible(true);
        // This method is called whenever the contents needs to be painted
        public void paintComponent(Graphics g) {
            // Draw the pie
            this.drawPie((Graphics2D)g, getBounds(), slices);
         // slices is an array of values that represent the size of each slice.
         public void drawPie(Graphics2D g, Rectangle area, PieSlice[] slices)
                 // Get total value of all slices
                 double total = 0.0;
                 for (int p=0; p<slices.length; p++) {
                     total += slices[p].value;
                 // Draw each pie slice
                 double curValue = 0.0;
                 int startAngle = 0;
                 for (int p=0; p<slices.length; p++)
                     // Compute the start and stop angles
                     startAngle = (int)(curValue * 360 / total);
                     int arcAngle = (int)(slices[p].value * 360 / total);
                     // Ensure that rounding errors do not leave a gap between the first and last slice
                     if (p == slices.length-1) {
                         arcAngle = 360 - startAngle;
                 } //end if
                 // Set the color and draw a filled arc
                 g.setColor(slices[p].color);
                 g.fillArc(area.x, area.y, 200, 200, startAngle, arcAngle);
                 RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                   g.setRenderingHints(renderHints);
                   //int border=10;
                   //Ellipse2D.Double elb = new Ellipse2D.Double(area.x - border/2, area.y - border/2, pieWidth + border, pieHeight + border);
                 //g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
                 curValue += slices[p].value;
                 } //end for
            }//end drawPie
            public void resetPieChart(double capital, double interest)
                             slices[0] = new PieSlice(capital, Color.red);
                             slices[1] = new PieSlice(interest, Color.green);
                             this.repaint();
              }//end resetPieChart
        }//end class PieChart
              public static void main(String[] args)
                   MortCalcWeek5p app = new MortCalcWeek5p();
                   app.pack();
              }//end main
    }//end the programI am sorry for putting all this code here. I just wanted you to see the entire picture. I won't post all of this again unless requested.
    Thanks,
    Seawall

    Did you write this? :)
    Anyways, here you go. You never instantiated the pie chart or added it to gui. I created a separate JFrame and put pie chart in it. Also added PieChart.resetPieChart in actionHandler method. This should get you started.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    public class MortCalcWeek5p extends JFrame implements ActionListener
         DecimalFormat twoPlaces = new DecimalFormat("#,###.00");//number format
         int L[] = {7, 15, 30};
         double I[] = {5.35, 5.5, 5.75};
         double P, M, J, H, C, Q;
         boolean manual = true;
            PieChart pc = null;
         JPanel panel = new JPanel ();
         JRadioButton opt1 = new JRadioButton ("Manual Input", true);
         JRadioButton opt2 = new JRadioButton ("Menu Selections", false);
         ButtonGroup radioSelect = new ButtonGroup();
         JLabel PLabel = new JLabel("Enter the mortgage amount: ");
         JTextField PField = new JTextField(10);//field for obtaining user input for mortgage amount
         JLabel LLabel1 = new JLabel("Enter the term in years: ");
         JTextField LField = new JTextField(3);//field for obtaining user input for term in years
         JLabel ILabel1 = new JLabel("Enter the interest rate: ");
         JTextField IField = new JTextField(5);//field for obtaining user input for interest rate
         JLabel choices = new JLabel ("Or Choose the Interest Rate and Term in Years");
         JButton calcButton = new JButton("Calculate");
         JButton clearButton = new JButton("Clear");
         JButton exitButton = new JButton("Exit");
         JTextField payment = new JTextField(10);
         JLabel ILabel2 = new JLabel("Interest Rate: choose one");
         String [] IChoice = {I[0] + "", I[1] + "", I[2] + ""};
         JComboBox IBox = new JComboBox(IChoice);
         JLabel LLabel2 = new JLabel("Term (in years): choose one");
         String [] LChoice = {L[0] + "", L[1] + "", L[2] + ""};
         JComboBox LBox = new JComboBox(LChoice);
         JLabel amortBox = new JLabel("Amortization Table");
         JTextArea ta = new JTextArea();//<----------------------added
         //JScrollPane amortScroll = new JScrollPane();//
         JScrollPane amortScroll = new JScrollPane(ta, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         public MortCalcWeek5p () //creates the GUI window
                        super("Mortgage Calculator Week 5");
                        setSize(500, 400);
                        panel.setBackground (Color.white);
                        //panel.setLayout(null);
                        panel.setPreferredSize(new Dimension(900, 500));
                        setResizable(false) ;
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        //Creates the container
                        //Container contentPane = getContentPane();
                        FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
                                    BorderLayout bl = new BorderLayout();
                        panel.setLayout(fresh);
                        //identifies trigger events
                        calcButton.addActionListener(this);
                        clearButton.addActionListener(this);
                                    exitButton.addActionListener(this);
                        PField.addActionListener(this);
                        LField.addActionListener(this);
                        IField.addActionListener(this);
                        opt1.addActionListener(this);
                        opt2.addActionListener(this);
                        //panel.setLayout(fresh);
                        //Options
                        radioSelect.add(opt1);
                        radioSelect.add(opt2);
                        panel.add(opt1);
                        opt1.setBackground (Color.white);
                        panel.add(opt2);
                        opt2.setBackground (Color.white);
                        //Manual Entries
                        panel.add(PLabel);
                        panel.add(PField);
                        panel.add(LLabel1);
                        panel.add(LField);
                        panel.add(ILabel1);
                        panel.add(IField);
                        //Pre-set Entries
                        panel.add(choices);
                        panel.add(ILabel2);
                        panel.add(IBox);
                        IBox.setBackground (Color.white);
                        panel.add(LLabel2);
                        panel.add(LBox);
                        LBox.setBackground (Color.white);
                        //Buttons
                        panel.add(calcButton);
                        calcButton.setBackground (Color.white);
                        panel.add(payment);
                        payment.setBackground (Color.white);
                        panel.add(clearButton);
                        clearButton.setBackground (Color.white);
                        panel.add(exitButton);
                        exitButton.setBackground (Color.white);
                        //Amortization Table
                        panel.add(amortBox);
                        payment.setEditable(false);
                        panel.add(amortScroll);
                        amortScroll.setPreferredSize(new Dimension(600,300));//<----------added
                        setContentPane(panel);
                                    setVisible(true);
                        //Pie Chart
                                    pc = new PieChart(C,H);
                        JPanel piePanel = new JPanel();
                                    piePanel.setLayout(new BorderLayout());
                                    piePanel.add(pc);                               
                                    JFrame pieFrame = new JFrame("Pie Chart");
                                    pieFrame.setSize(210,230);
                                    pieFrame.getContentPane().add(piePanel);
                                    pieFrame.setVisible(true);
         }// end of GUI info
              public void actionPerformed(ActionEvent e)
                   Object source = e.getSource();
                   if (source == calcButton)
                                    pc.resetPieChart(C, H);
                        try
                        if (manual)
                             Calculations_manual();
                        else Calculations_menu();
                   catch(NumberFormatException event)
                        JOptionPane.showMessageDialog(null, "You did not enter a number.\n\nYou're not too bright are you?\n\nTry again.", "ERROR", JOptionPane.ERROR_MESSAGE);
                   if (source == clearButton)
                   reset();
                   if (source == exitButton)
                   end();
                   if (source == opt1)
                   IBox.setEnabled(false);
                   LBox.setEnabled(false);
                   LField.setEnabled(true);
                   LField.setEditable(true);
                   IField.setEnabled(true);
                   IField.setEditable(true);
                   manual = true;
                   if (source == opt2)
                   IBox.setEnabled(true);
                   LBox.setEnabled(true);
                   LField.setEnabled(false);
                   LField.setEditable(false);
                   IField.setEnabled(false);
                   IField.setEditable(false);
                   manual = false;
              public void Calculations_menu() //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble((String) IBox.getSelectedItem());
                   double L = Double.parseDouble((String) LBox.getSelectedItem());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  //String showAmort = twoPlaces.format(H + C + Q);
                                  //amortScroll(showAmort);
                                //ta.append("Month " + month);
                                ta.append("Interest Paid: " + twoPlaces.format(H));
                                ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
                                ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");
              public void Calculations_manual() //performs the calculations from user input
                   double P = Double.parseDouble(PField.getText());
                   double I = Double.parseDouble(IField.getText());
                   double L = Double.parseDouble(LField.getText());
                   double J = (I  / (12 * 100));//monthly interest rate
                   double N = (L * 12);//term in months
                   double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
                 String showPayment = twoPlaces.format(M);
                 payment.setText(showPayment);
                   int month = 1;
                             while (month <= N)
                                  //performs the calculations for the amortization
                                  double H = P * J;//current monthly interest
                                  double C = M - H;//monthly payment minus monthly interest
                                  double Q = P - C;//new balance
                                  P = Q;//sets loop
                                  month++;
                                  //String showAmort = twoPlaces.format(H + C + Q);
                                  //amortScroll(showAmort);
                                //ta.append("Month " + month);
                                ta.append("Interest Paid: " + twoPlaces.format(H));
                                ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
                                ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");
              // resets GUI for another calculation
              public void reset ()
              PField.setText(null);
              payment.setText(null);
              ta.setText(null);
              LField.setText(null);
              IField.setText(null);
              // ends GUI and exits program
              public void end()
              System.exit(0);
    public class PieChart extends JComponent {
        // Class to hold a value for a slice
        class PieSlice
            //private variables
            double value;
            Color color;
            public PieSlice(double value, Color color)
                this.value = value;
                this.color = color;
            }//end Constructor
           } //end class PieSlice
        //private variable slices are array of PieSlice
        PieSlice[] slices = new PieSlice[2];
        //constructor
        PieChart(double C, double H)
            slices[0] = new PieSlice(C, Color.red);
            slices[1] = new PieSlice(H, Color.green);
            setVisible(true);
        // This method is called whenever the contents needs to be painted
        public void paintComponent(Graphics g) {
            // Draw the pie
            this.drawPie((Graphics2D)g, getBounds(), slices);
         // slices is an array of values that represent the size of each slice.
         public void drawPie(Graphics2D g, Rectangle area, PieSlice[] slices)
                 // Get total value of all slices
                 double total = 0.0;
                 for (int p=0; p<slices.length; p++) {
                     total += slices[p].value;
                 // Draw each pie slice
                 double curValue = 0.0;
                 int startAngle = 0;
                 for (int p=0; p<slices.length; p++)
                     // Compute the start and stop angles
                     startAngle = (int)(curValue * 360 / total);
                     int arcAngle = (int)(slices[p].value * 360 / total);
                     // Ensure that rounding errors do not leave a gap between the first and last slice
                     if (p == slices.length-1) {
                         arcAngle = 360 - startAngle;
                 } //end if
                 // Set the color and draw a filled arc
                 g.setColor(slices[p].color);
                 g.fillArc(area.x, area.y, 200, 200, startAngle, arcAngle);
                 RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                   g.setRenderingHints(renderHints);
                   //int border=10;
                   //Ellipse2D.Double elb = new Ellipse2D.Double(area.x - border/2, area.y - border/2, pieWidth + border, pieHeight + border);
                 //g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
                 curValue += slices[p].value;
                 } //end for
            }//end drawPie
            public void resetPieChart(double capital, double interest)
                             slices[0] = new PieSlice(capital, Color.red);
                             slices[1] = new PieSlice(interest, Color.green);
                             this.repaint();
              }//end resetPieChart
        }//end class PieChart
              public static void main(String[] args)
                   MortCalcWeek5p app = new MortCalcWeek5p();
                   app.pack();
              }//end main
    }//end the program

  • Swing newbie, where are my button?

    I have these 3 classes, but my button dosn't show, why not?
    Here the classes come, I have cut in them, so you wont se my variable defination, but I guess you will get the picture:
    --- class # 1 ---
    mainFrame = new JFrame("XCom v0.1");
    cardPanel = new JPanel();
    cardLayout = new CardLayout();
    cardPanel.setLayout(cardLayout);
    Enumeration enum = this.loadedModules.keys();
    while(enum.hasMoreElements()) {
      String key = (String)enum.nextElement();
      SuperModule module = (SuperModule)this.loadedModules.get(key);
      cardPanel.add(module,module.getDescriptor("name"));
    cardLayout.show(cardPanel,this.properties.getProperty("modules.currentModule"));
    mainFrame.getContentPane().add(cardPanel,BorderLayout.CENTER);
    mainFrame.pack();
    mainFrame.setVisible(true);--- class #2 ---
    public class SuperModule extends JPanel {
      private Hashtable descriptors = new Hashtable();
      public SuperModule() {
        super();
      public void addDescriptor(String key, String value) {
        descriptors.put(key,value);
      public String getDescriptor(String name) {
        return (String)this.descriptors.get(name);
    }--- class #3 ---
    public class Mail extends SuperModule {
      GridLayout gridLayout;
      JTextArea test;
      public Mail() {
        super();
        addDescriptor("name","Mail");
      public void init() {
        gridLayout = new GridLayout(1,1,10,10);
        this.setLayout(gridLayout);
        JButton button = new JButton("I'm a Swing button!");
        this.add(button);
    }

    Hi,
    I am not able to see where u r creating an instance of the Class Mail (bcoz its there u have buttons ).Without creating instance of the class and adding to the cardlayout I don't see how u expect the buttons to be visible.
    Nagaraj

  • Drag JTabbedPane out of the main Frame and set scroll bars for the tabs

    hi ,
    Iam working on a Swing application . In it i have Six Tabs added to a single JTabbedPane. all the tabs are different class files . is it possible to drag any of the tabs out of the frame.
    how to add scroll bars for the tabs individually. i have tried adding JScrollPane to the main frame and add the JTabbedPane to the Scrollpane . the scroll bar was not visible and i have tried adding
    all the six tabs to the individual JScrollPanes and add the six scrollpanes to the TabbedPane .
    only the scroll arrows are visible , when i minimised or resized the application the scrollbars were not appearing .
    could any one help me to solve the above two problems.

    just trying.....
    public void mouseDragged(MouseMotionEvent e){
    // this event should be activated only when the Drag goes out of scope of the parent JFrame which i dont know how
    Component c=JTab.getComponentAt(JTab.getSelectedIndex());
    JFrameobj.getContentPane().add(c,"Center");
    }

Maybe you are looking for

  • Qty field  value diff from SAP R/3

    hi friends,     i have replicate one table datasource  from  SAP to BW................. in datasouce i m using RFMNG quantity field and in BW mapping it to 0DEL_QTY....... both having datatype lenth 17 and decimal 3................. data loading is d

  • SAPScript: How to combine two text in the same line?

    Dear Gurus, I have a case to combine hard code text and long text in the same line. For example, i need to display following line: 'Project name:' <long_text> How to do it in SAPScript? Can we do it with following code? /: 'Project name: ' INCLUDE Z_

  • Siri can't find Home

    I tried setting a reminder in Siri on my new iPhone 5, like "Remind me to put my pants on when I leave Home".  This used to work on my 4S, but now Siri responds with "Sorry, I don't see 'Home' in your contacts." or "I don't know who 'Home' is."  Howe

  • Soundbooth CS5 Transcription From Speech to Text

    Does anyone know if Soundbooth's transcription accuracy rate can be improved for a single speaker?  If not, is there another Adobe software program that will permit a user to accomplish that function? Thanks, KB Johnson         

  • Noob in Need of Help: Where can I find a 1Ghz Processor?

    Hi, I'm Elaine, I was given a 450Mhz, G4 Gigabit ethernet Tower as payment for some graphics work (yeah, I feel like I got cheated, but that's just me). Anyhoo, I'm rather fond of mac computers, but I'm finding to do the work I do I need to basically