BorderLayout clobbers child layouts.

Smells like a bug to me. If you place child panels with, say GridBagLayouts inside a panel which has a BorderLayout, the parental BorderLayout clobbers the child layouts. So if you have a panel in the CENTER and you want a button anchored to the upper left hand corner with GridBagConstraints.NORTHWEST, you'll find that your GridBag is completely ignored and your component is centered.
Check out the following code:
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Enumeration;
public class Foo3 extends JPanel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Joe's Foo3");
        frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
        // Here's your main panel with BorderLayout
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        // Here's your inner panel with a GridBag...you want the
        // "NorthWest" button to appear in the northwest corner
        // of the center panel.
        JPanel innerPanel = new JPanel(new GridBagLayout());
        innerPanel.setBackground(Color.black);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.BOTH;
        innerPanel.add(new JButton("NorthWest"), gbc);
        // Add a button to each of the layout areas
        mainPanel.add(new JButton("North"), BorderLayout.NORTH);
        mainPanel.add(new JButton("West"), BorderLayout.WEST);
        mainPanel.add(innerPanel, BorderLayout.CENTER);
        mainPanel.add(new JButton("East"), BorderLayout.EAST);
        mainPanel.add(new JButton("South"), BorderLayout.SOUTH);
        // Show
        frame.getContentPane().add("Center", mainPanel);
        frame.pack();
        frame.setSize(new Dimension(300, 300));
        frame.setVisible(true);

Hmmm... I tried a few things with your app and nothing worked so far. Looks like you might not be the first to encounter this, but I haven't found a resolution other than don't use GridBag. :)
http://forum.java.sun.com/thread.jsp?forum=5&thread=238875

Similar Messages

  • [svn:osmf:] 14595: Metadata refactoring revision: having LayoutMetadata return a NullMetadataSynthesizer so that child layout settings do not get copied to their parent .

    Revision: 14595
    Revision: 14595
    Author:   [email protected]
    Date:     2010-03-05 01:25:04 -0800 (Fri, 05 Mar 2010)
    Log Message:
    Metadata refactoring revision: having LayoutMetadata return a NullMetadataSynthesizer so that child layout settings do not get copied to their parent.
    Modified Paths:
        osmf/trunk/framework/OSMF/org/osmf/layout/LayoutMetadata.as

    I've only encountered two instances where the PUT operation failed on certain files. One, the server does not like the particular file type, and two, when the file was open in another program.
    Other than that, I could only guess that it may have something else to do with the web server configuration and not DW.

  • Weird add/remove child layout behavior

    I'm trying to build an an app that allows the user to toggle
    certain panels on and off. These panels are in Divider containers.
    It seems that at startup, when I remove and add a panel flex
    doesn't properly validate layout. For example 2 panels are added to
    a VDivided container. I then call removeChild on the second panel
    (at the bottom of the container), and the first panel then properly
    occupies all the visible space. When I add the second panel back,
    it is re-added but has not retained its original size and is
    instead compressed at the bottom. If I then remove the top panel
    and add it again, then remove the bottom panel and add it,
    everything works as I expect. It's almost like their is a one-time
    initialization not occurring somewhere. Here is the code sample I
    am using to demonstrate the problem:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" width="1000" height="800">
    <mx:VBox height="100%" top="0" left="0" right="0">
    <mx:ApplicationControlBar x="0" y="0" width="100%"
    height="58">
    <mx:CheckBox label="Panel 1" id="panel1CheckBox"
    selected="true" click="modifyViewPanel1()"/>
    <mx:CheckBox label="Panel 2" id="panel2CheckBox"
    selected="true" click="modifyViewPanel2()"/>
    </mx:ApplicationControlBar>
    <mx:VDividedBox x="0" y="0" width="100%" height="90%"
    id="vDivideBox">
    <mx:Panel width="100%" height="50%" layout="vertical"
    title="Panel 1" id="panel1">
    </mx:Panel>
    <mx:Panel width="100%" height="50%" layout="vertical"
    id="panel2" title="Panel 2">
    </mx:Panel>
    </mx:VDividedBox>
    </mx:VBox>
    <mx:Script>
    <![CDATA[
    private function modifyViewPanel1():void {
    trace("modifyView...");
    if (panel1.parent) panel1.parent.removeChild(panel1);
    if (panel1CheckBox.selected) {
    vDivideBox.addChildAt(panel1, 0);
    private function modifyViewPanel2():void {
    trace("modifyView...");
    if (panel2.parent) panel2.parent.removeChild(panel2);
    if (panel2CheckBox.selected) {
    vDivideBox.addChildAt(panel2,
    vDivideBox.getChildren().length);
    ]]>
    </mx:Script>
    </mx:Application>

    The properties you set with MXML tags are the initial values,
    they aren't used to reset the controls. They would have to be
    dynamic properties like width="{comp1.width/2}" for them to change
    as the program runs. Setting a component's width to "50%" just
    means it will initially be calculated to have 50% of the width of
    its parent. As the program runs the component's width can change
    which it what's happened.
    Removing a child only removes the component from the parent's
    display list. The component still exists and adding it back causes
    the parent to recalculate its layout. This means it may change the
    size of the children.
    You have a couple of choices. You can give the Panel a
    minHeight and the Divider will respect that. Or you can calculate
    the Panel's height, set it to that value, then add it back to the
    Divider.

  • Maximum size for JPanel in BorderLayout

    I'am using a BorderLayout in my JFrame. I want to place a JPanel in BorderLayout.CENTER. The problem: It should use the maximum possible space.
    For example, if I place a JButton in CENTER, the JButton will grow very big. I want the same behaviour for a JPanel.
    Using setPreferredSize doesn't seem to be a solution because I want the JPanel to resize dynamically, like a JButton does.
    Any ideas? :-)
    Thanks

    The borderlayout is the layout which resizes the components as and when the frame is resized. So i think you should not have a problem like resizing.
    One more thing when u are adding a panel with a borderlayout, do specify where the components are to be added on the panel. i.e. on north, center or south,etc...
    May be this simple example help u out, just copy paste the code and run it.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class BorderMain extends JFrame {
    Container c;
    JPanel pnl;
    BorderLayout bl;
    public BorderMain()
         setPreferredSize(new Dimension(200,200));
         c = getContentPane();
         bl = new BorderLayout();
         pnl = new JPanel();
         pnl.setLayout(bl);
         pnl.setBackground(Color.GRAY);
         c.add(pnl);
         c.validate();
         setVisible(true);
         pack();
         public static void main(String[] args) {
              new BorderMain();
    now when u add anythin to the panel just say
    pnl.add(new JButton("OK"), BorderLayout.NORTH);
    pnl.add(new JButton("OK"), BorderLayout.CENTER);
    pnl.add(new JButton("OK"), BorderLayout.SOUTH);
    this is just an example.
    if u add anything only to north, then to the panel will occupy all the space given.
    Regards
    Poonam.
    and if ur adding another panel on a panel with the borderlayout then u need to set the same layoutfor the inner panel also.

  • Frame layout changes when button is pressed again...

    Okay so basically I have a button on my frame and when it's pressed it opens up another frame. This is fine, but when the button is pressed again it opens up the frame again but the layout is all over the place.
    Here is the code:
    if (ev.getSource() == seating)
    else
                   seatdisplay = new JFrame("Seating Display");
                   seatdisplay.getContentPane().setBackground(Color.orange);
                   seatdisplay.setLayout(new BorderLayout()); //Define border layout
                   seatdisplay.setVisible(true);
                   seatdisplay.setSize(550,500);
                   seatdisplay.add(panelLeft, BorderLayout.WEST); //Position object to the west
                   seatdisplay.add(panelMiddle, BorderLayout.CENTER);
                   seatdisplay.add(panelRight, BorderLayout.EAST);
                   seatdisplay.add(panelTop, BorderLayout.NORTH);
                   seatdisplay.add(panelBottom, BorderLayout.SOUTH);
                   panelLeft.setLayout(new GridLayout(4,2)); //Define new grid layout
                   panelLeft.setBackground(Color.black);
                   panelLeft.add(a1 = new JButton("A1")); //Add buttons
                   panelLeft.add(a2 = new JButton("A2"));
                   panelLeft.add(a3 = new JButton("A3"));
                   panelLeft.add(a4 = new JButton("A4"));
                   panelLeft.add(a5 = new JButton("A5"));
                   panelLeft.add(a6 = new JButton("A6"));
                   panelLeft.add(a7 = new JButton("A7"));
                   panelLeft.add(a8 = new JButton("A8"));
                   panelMiddle.setLayout(new GridLayout(3,6));
                   panelMiddle.setBackground(Color.orange);
                   panelMiddle.add(empty = new JButton("")); empty.setVisible(false);
                   panelMiddle.add(b1 = new JButton("B1"));
                   panelMiddle.add(b2 = new JButton("B2"));
                   panelMiddle.add(b3 = new JButton("B3"));
                   panelMiddle.add(b4 = new JButton("B4"));
                   panelMiddle.add(empty3 = new JButton("")); empty3.setVisible(false);
                   panelMiddle.add(empty1 = new JButton("")); empty1.setVisible(false);
                   panelMiddle.add(b5 = new JButton("B5"));
                   panelMiddle.add(b6 = new JButton("B6"));
                   panelMiddle.add(b7 = new JButton("B7"));
                   panelMiddle.add(b8 = new JButton("B8"));
                   panelMiddle.add(empty4 = new JButton("")); empty4.setVisible(false);
                   panelMiddle.add(empty2 = new JButton("")); empty2.setVisible(false);
                   panelMiddle.add(b9 = new JButton("B9"));
                   panelMiddle.add(b10 = new JButton("B10"));
                   panelMiddle.add(b11 = new JButton("B11"));
                   panelMiddle.add(b12 = new JButton("B12"));
                   panelRight.setLayout(new GridLayout(4,2));
                   panelRight.setBackground(Color.black);
                   panelRight.add(c1 = new JButton("C1"));
                   panelRight.add(c2 = new JButton("C2"));
                   panelRight.add(c3 = new JButton("C3"));
                   panelRight.add(c4 = new JButton("C4"));
                   panelRight.add(c5 = new JButton("C5"));
                   panelRight.add(c6 = new JButton("C6"));
                   panelRight.add(c7 = new JButton("C7"));
                   panelRight.add(c8 = new JButton("C8"));
    }The seat button is pressed and seatdisplay frame is opened, however, if I press the seat button twice another seatdisplay frame is opened and the layout is all over the place. Do I need to do some sort of refresh?

    Swing related questions should be posted in the Swing forum.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Tax Calulator applet again pls help urgent

    why isn't it possible to pass a string and a double into GetResult below, i get a compilation error and right now i dunno how to proceed. GetRelief is supposed to calculate "relief" from textfields i/p and GetResult is suppose to calculate the "result" (minus "relief" from GetRelief). And is it the correct way to create an object as in calc = new Calculate(); below................any help would be greatly appreciated...
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TaxCal extends Applet implements ActionListener {
         private TextField income, age, child, parent, course, maid, pay;
         private Button b2, b3;
         private Calculate calc;
         public void init() {
                   setBackground(Color.lightGray);
                   /* Create the input boxes, and make sure that the background
                   color is white. (On some platforms, it is automatically.) */
                   income = new TextField(10);
                   Panel incomePanel = new Panel();
                   incomePanel.setLayout(new BorderLayout(2,2));
                   incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
              incomePanel.add(income, BorderLayout.CENTER);
                   age = new TextField(2);
                   Panel agePanel = new Panel();
                   agePanel.setLayout(new BorderLayout(2,2));
                   agePanel.add( new Label("Input your age"), BorderLayout.WEST );
                   agePanel.add(age, BorderLayout.CENTER);
                   child = new TextField(2);
                   Panel childPanel = new Panel();
                   childPanel.setLayout(new BorderLayout(2,2));
                   childPanel.add( new Label("Number of children"), BorderLayout.WEST );
                   childPanel.add(child, BorderLayout.CENTER);
                   parent = new TextField(1);
                   Panel parentPanel = new Panel();
                   parentPanel.setLayout(new BorderLayout(2,2));
                   parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
                   parentPanel.add(parent, BorderLayout.CENTER);
                   course = new TextField(5);
                   Panel coursePanel = new Panel();
                   coursePanel.setLayout(new BorderLayout(2,2));
                   coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
                   coursePanel.add(course, BorderLayout.CENTER);
                   maid = new TextField(5);
                   Panel maidPanel = new Panel();
                   maidPanel.setLayout(new BorderLayout(2,2));
                   maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
                   maidPanel.add(maid, BorderLayout.CENTER);
                   pay = new TextField(10);
                   pay.setEditable(false);
                   Panel payPanel = new Panel();
                   payPanel.setLayout(new BorderLayout(2,2));
                   payPanel.add( new Label("Please pay"), BorderLayout.WEST );
                   payPanel.add(pay, BorderLayout.CENTER);
                   Panel buttonPanel = new Panel();
                   buttonPanel.setLayout(new GridLayout(1,3));
                   Button b2 = new Button("Reset");
                   b2.addActionListener(this);     // register listener
                   buttonPanel.add(b2);
                   Button b3 = new Button("Calculate");
                   b3.addActionListener(this);     // register listener
                   buttonPanel.add(b3);
                   /* Set up the layout for the applet, using a GridLayout,
              and add all the components that have been created. */
              setLayout(new GridLayout(8,2));
                   add(incomePanel);
                   add(agePanel);
                   add(childPanel);
                   add(parentPanel);
              add(coursePanel);
              add(maidPanel);
              add(payPanel);
              add(buttonPanel);
              /* Try to give the input focus to xInput, which is
              the natural place for the user to start. */
              income.requestFocus();
              } // end init()
         public TaxCal() {
         calc = new Calculate();
         public Insets getInsets() {
    // Leave some space around the borders of the applet.
         return new Insets(2,2,2,2);
         // event handler for ActionEvent
         public void actionPerformed (ActionEvent e) {
              String s = e.getActionCommand();
              if (s.equals("Calculate"))
                   double relief = calc.GetRelief(age.getText(), child.getText(), parent.getText(), course.getText(), maid.getText());
                   double result = calc.GetResult(income.getText(), relief);
                   pay.setText(Double.toString(relief));
              else
                   income.setText("");
                   age.setText("");
                   child.setText("");
                   parent.setText("");
                   course.setText("");
                   maid.setText("");
                   pay.setText("");
    }     // end actionPerformed()
    public class Calculate
    private double result;
    private double incomeTotal;
    private double ageTotal;
    private double childTotal;
    private double parentTotal;
    private double courseTotal;
    private double maidTotal;
    private double relief;
    public Calculate()
    relief = 0.0;
    result = 0.0;
    incomeTotal = 0;
    ageTotal = 0;
    childTotal = 0;
    parentTotal = 0;
    courseTotal = 0;
    maidTotal = 0;
    public double GetResult(String theincome, Double therelief)
         incomeTotal = Double.parseDouble(theincome);
         relief = therelief;
         incomeTotal =- relief;
         if (incomeTotal <= 7500)
         result = incomeTotal * .02;
         else if (incomeTotal > 7500 && incomeTotal <= 20000)
         result = 150 + ((incomeTotal - 7500) * .05);
         else if (incomeTotal > 20000 && incomeTotal <= 35000)
         result = ((incomeTotal - 20000) * .08) + 775;
         else if (incomeTotal> 35000 && incomeTotal <= 50000)
         result = ((incomeTotal - 35000) * .12) + 1975;
         else if (incomeTotal > 50000 && incomeTotal <= 75000)
         result = ((incomeTotal - 50000) * .16) + 3775;
         else if (incomeTotal > 75000 && incomeTotal <= 100000)
         result = ((incomeTotal - 75000) * .2) + 7775;
         else if (incomeTotal > 100000 && incomeTotal <= 150000)
         result = ((incomeTotal - 100000) * .22) + 12775;
         else if (incomeTotal > 150000 && incomeTotal <= 200000)
         result = ((incomeTotal - 150000) * .23) + 23775;
         else if (incomeTotal > 200000 && incomeTotal <= 400000)
         result = ((incomeTotal - 200000) * .26) + 35275;
         else if (incomeTotal > 400000)
         result = ((incomeTotal - 400000) * .28) + 87275;
         return result;
    public double GetRelief(String theage, String thechild, String theparent, String thecourse, String themaid)
         ageTotal = Double.parseDouble(theage);
         parentTotal = Double.parseDouble(theparent);
         maidTotal = Double.parseDouble(themaid);
         childTotal = Double.parseDouble(thechild);
         courseTotal = Double.parseDouble(thecourse);
                             //determine age relief
                             if(ageTotal<55)
                             relief += 3000;
                             else if(ageTotal>=55 && ageTotal<= 59)
                             relief += 8000;
                             else
                             relief += 10000;
                             //determine children relief
                             if(childTotal<=3)
                             relief += (childTotal*2000);
                             else if(childTotal>3 && childTotal<6)
                             relief += ((childTotal-3)*500 + 6000);
                             else
                             relief += 0;
                             //determine parent relief
                             if(parentTotal == 1)
                             relief += 3000;
                             else if(parentTotal ==2)
                             relief += 6000;
                             else
                             relief += 0;
                             //determine course subsidy
                             if(courseTotal != 0 ) {
                                  if(courseTotal <= 2500)
                                  relief += courseTotal;
                                  else
                                  relief += 2500;
                             //determine maid levy
                             if(maidTotal != 0) {
                                  if(maidTotal <= 4000)
                                  relief += 2 * maidTotal;
                                  else
                                  relief += 0;
    return relief;
    } // end of class Calculate
    }      // end class TaxCal

    You're probably not getting anything to show up because in your actionPerformed() method, b3 has not been initialized.
    You declare static variables:
    Button b2, b3;
    but then in your init() method, you delare new local variables when you specify:
    Button b2 = new Button(...);
    Button b3 = new Button(...);
    Since you're declaring and initializing the new local variables, you have never set the static variables to any values. Try removing the type declaration for b2 and b3 in your init() method as follows:
    b2 = new Button(...)
    b3 = new Button(...)
    Hope this helps!

  • Tax Calculator

    Hi,
    I'm new & working on my assignment. I'm working on a tax calculator applet. I'm having problems (cannot work) and would like to ask if anyone can correct my mistakes.
    Here's my code
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TaxCal extends Applet implements ActionListener {
         private TextField income, age, child, parent, course, maid, pay;
         private Button b2, b3;
         public void init() {
                   setBackground(Color.lightGray);
                   /* Create the input boxes, and make sure that the background
                   color is white. (On some platforms, it is automatically.) */
                   income = new TextField(10);
                   Panel incomePanel = new Panel();
                   incomePanel.setLayout(new BorderLayout(2,2));
                   incomePanel.add( new Label("Input your annual income"), BorderLayout.WEST );
              incomePanel.add(income, BorderLayout.CENTER);
                   age = new TextField(2);
                   Panel agePanel = new Panel();
                   agePanel.setLayout(new BorderLayout(2,2));
                   agePanel.add( new Label("Input your age"), BorderLayout.WEST );
                   agePanel.add(age, BorderLayout.CENTER);
                   child = new TextField(2);
                   Panel childPanel = new Panel();
                   childPanel.setLayout(new BorderLayout(2,2));
                   childPanel.add( new Label("Number of children"), BorderLayout.WEST );
                   childPanel.add(child, BorderLayout.CENTER);
                   parent = new TextField(1);
                   Panel parentPanel = new Panel();
                   parentPanel.setLayout(new BorderLayout(2,2));
                   parentPanel.add( new Label("Number of parent that live with you"), BorderLayout.WEST );
                   parentPanel.add(parent, BorderLayout.CENTER);
                   course = new TextField(5);
                   Panel coursePanel = new Panel();
                   coursePanel.setLayout(new BorderLayout(2,2));
                   coursePanel.add( new Label("Course fee"), BorderLayout.WEST );
                   coursePanel.add(course, BorderLayout.CENTER);
                   maid = new TextField(5);
                   Panel maidPanel = new Panel();
                   maidPanel.setLayout(new BorderLayout(2,2));
                   maidPanel.add( new Label("Maid levy paid"), BorderLayout.WEST );
                   maidPanel.add(maid, BorderLayout.CENTER);
                   pay = new TextField(10);
                   pay.setEditable(false);
                   Panel payPanel = new Panel();
                   payPanel.setLayout(new BorderLayout(2,2));
                   payPanel.add( new Label("Please pay"), BorderLayout.WEST );
                   payPanel.add(pay, BorderLayout.CENTER);
                   Panel buttonPanel = new Panel();
                   buttonPanel.setLayout(new GridLayout(1,3));
                   Button b2 = new Button("Reset");
                   b2.addActionListener(this);     // register listener
                   buttonPanel.add(b2);
                   Button b3 = new Button("Calculate");
                   b3.addActionListener(this);     // register listener
                   buttonPanel.add(b3);
                   /* Set up the layout for the applet, using a GridLayout,
              and add all the components that have been created. */
              setLayout(new GridLayout(8,2));
                   add(incomePanel);
                   add(agePanel);
                   add(childPanel);
                   add(parentPanel);
              add(coursePanel);
              add(maidPanel);
              add(payPanel);
              add(buttonPanel);
              /* Try to give the input focus to xInput, which is
              the natural place for the user to start. */
              income.requestFocus();
              } // end init()
         public Insets getInsets() {
    // Leave some space around the borders of the applet.
         return new Insets(2,2,2,2);
         // event handler for ActionEvent
         public void actionPerformed (ActionEvent e) {
              if (e.getSource() == b3) {
                   double x = 0;
                   double relief = 0;
                   String incomeString = income.getText();
                   double income = Double.parseDouble(incomeString);
                   String ageString = age.getText();
                   int age = Integer.parseInt(ageString);
                   String childString = child.getText();
                   int child = Integer.parseInt(childString);
                   String parentString = parent.getText();
                   int parent = Integer.parseInt(parentString);
                   String courseString = course.getText();
                   double course = Double.parseDouble(courseString);
                   String maidString = maid.getText();
                   double maid = Double.parseDouble(maidString);
                             //determine age relief
                             if(age<55) {
                             relief += 3000;
                             else if(age>=55 && age<= 59) {
                             relief += 8000;
                             else {
                             relief += 10000;
                             //determine children relief
                             if(child<=3) {
                             relief += (child*2000);
                             else if(child>3 && child<6) {
                             relief += ((child-3)*500 + 6000);
                             else {
                             relief += 0;
                             //determine parent relief
                             if(parent == 1) {
                             relief += 3000;
                             else if(parent ==2) {
                             relief += 6000;
                             else {
                             relief += 0;
                             //determine course subsidy
                             if(course != 0 ) {
                                  if(course <= 2500) {
                                  relief += course;
                                  else {
                                  relief += 2500;
                             //determine maid levy
                             if(maid != 0) {
                                  if(maid <= 4000) {
                                  relief += 2 * maid;
                                  else {
                                  relief += 0;
                             income =- relief;
                             if (income <= 7500) {
                             x = income * .02;
                             else if (income > 7500 && income <= 20000)
                             x = 150 + ((income - 7500) * .05);
                             else if (income > 20000 && income <= 35000)
                             x = ((income - 20000) * .08) + 775;
                             else if (income > 35000 && income <= 50000)
                             x = ((income - 35000) * .12) + 1975;
                             else if (income > 50000 && income <= 75000)
                             x = ((income - 50000) * .16) + 3775;
                             else if (income > 75000 && income <= 100000)
                             x = ((income - 75000) * .2) + 7775;
                             else if (income > 100000 && income <= 150000)
                             x = ((income - 100000) * .22) + 12775;
                             else if (income > 150000 && income <= 200000)
                             x = ((income - 150000) * .23) + 23775;
                             else if (income > 200000 && income <= 400000)
                             x = ((income - 200000) * .26) + 35275;
                             else if (income > 400000)
                             x = ((income - 400000) * .28) + 87275;
                   pay.setText("$" + x);
              else
                   income.setText("");
                   age.setText("");
                   child.setText("");
                   parent.setText("");
                   course.setText("");
                   maid.setText("");
                   pay.setText("");
    }     // end actionPerformed()
    }      // end class TaxCal

    The problem that you're having is actually one of scope. At the top of your class, you declare the two buttons:
    private Button b2, b3;These Button objects have class scope.
    Within the init() method, the lines:
    Button b2 = new Button("Reset");
    Button b3 = new Button("Calculate");declare another pair of Button objects that have method scope. These are the objects that are added to the panel and that receive the mouse click.
    In the actionPerformed() method, the statement:
    if (e.getSource() == b3) {cannot refer to the two Button object that are encapsulated in the init() method, but it can and does refer to the Button object with class scope. This is not the object that was added to the panel, so it hasn't received any events and won't be the source of the event that triggered execution of the actionPerformed() method. Since you don't check for any other events, the processing associated with the "Reset" button (b2) will always be executed.
    If you change the two lines in the init() method to:
    b2 = new Button("Reset");
    b3 = new Button("Calculate");
    your code will work as originally written (but there are a couple of errors in the computation logic).

  • A new AWT/Swing?

    I have a question for the community.
    IMHO, and I am not alone, AWT/Swing have major flaws that really ought to be fixed. Probably, because the APIs themselves are seriously flawed, what is required is a replacement for Swing.
    How would one go about proposing such a thing and getting Sun's support?
    Specific issues:
    1) A set of specific design rules should be codified, which all conforming components, layout managers, UIs, etc., should obey. Along with the rules, there should be automated tests, so that it could be confirmed whether components, layout managers, UIs, etc., work correctly.
    Currently, Swing and 3rd party components often do not work well together, for reasons such as
    a) Highly irrational behavior of layout managers. Currently, none of the AWT/Swing layout managers behave in a reasonable way under all circumstances, with the possible exception of BorderLayout. Also, layout managers use constraints in inconsistent ways, and they are ill-suited to control by GUI builders.
    b) Failure to use minimumSize, preferredSize, and size consistently.
    c) Inconsistent use of UIs. What is the division of responsibility between the UI, layout managers, L&F, and the main class(es)?
    2) Software design rules. For example, there is currently at least one Swing class that alters its behavior depending on which container it is placed in. That violates basic principles of OO development. Perusing the AWT/Swing source code, you will find plenty of objectional coding practices. It seems that the pressure to maintain backwards compatibility has been a real impediment to "doing things right".
    3) Performance. AWT/Swing are notorious for various performance problems, including
    a) Non-linear CPU cost associated with building certain graphical data structures (combo-boxes, for one).
    b) Layout managers that call getMinimumSize or getPreferredSize on child components multiple times. Currently, the layout managers are the CPU bottleneck in many AWT/Swing GUIs.
    c) Some text components are almost unbelievably slow. Try scrolling a lot of text through a JTextArea and you will be disappointed.
    d) The current validation logic is extremely complex, inefficient, and undocumented. I count approximately 15 basic API methods that affect how and when components are repainted. I defy ANYONE to explain how it all works. The typical result is that repaints occur FAR more often than is necessary.
    A lot of optimization is required to fix these problems. That means automating tests, profiling, removing extra repaints, CPU bottlenecks, etc.
    4) Excessive complexity of the APIs. For example, it seems that building practical tables and trees is harder than it should be. The APIs are complex and documentation obscure or lacking in detail. Also, the separation between model and view is often tainted. It shouldn't be necessary to do so much conversion between model and view indices, for example. A basic set of model classes should be shared by all components that use underlying data models. These model classes should support standard functionality such as filtering, sorting, etc.
    5) No portable remote operation. Yes, I am familiar with SAWT (slow and buggy), and the possibility of using X11 remotely when the Java application is run on a *nix platform (slow over a high-latency network such as the Internet and unusable on Windows systems).  There does not seem to be a usable, universal solution.
    Yes, I am familiar with SWT. However, for a variety of reasons, I believe that the AWT approach is superior. SWT is more platform dependent and it has the X11 reverse-object-orientation in which child classes know about their parents. I have done some performance testing, which suggests that
    1) SWT layout managers are faster than their corresponding AWT/Swing managers
    2) Most other graphics, including 2D graphics, are faster in AWT/Swing than SWT.
    I am sure that SWT encapsulates some good ideas. However, it seems that if the efficiency of validation and layouts could be improved, then AWT/Swing performance would be excellent, while maintaining OO and platform-independent characteristics.
    Possibly, these issues could be worked out piecemeal. For example, a new, rational set of layout managers could be developed entirely independently.
    Other issues, such as defining how UIs, L&F, and component classes should be architected, are going to be more problematic. Creating order in the current chaos will be difficult.
    Any ideas?

    >
    How would one go about proposing such a thing and
    getting Sun's support?
    As for proposing such a thing, you can always become a member of the Java Community Process Program (it's free for individual members): http://www.jcp.org/en/home/index. As a member you can post a Java Specification Request with your suggestions. If you want to operate on a smaller scale you can report bugs to the bug database.
    As for getting Sun's support....well, good luck! :-)

  • Appletviewer problem...

    I've literally changed a few Button on my applet to JButton and when I compile it one of the button fills the entire appletviewer. I've tried changing it back to Button but this still happens.
    Any ideas? :S

    import java.awt.*;                                                                 //Import all the classes within the abstract windows toolkit
    import java.applet.*;                                                            //Import applet class
    import java.awt.event.*;
    import java.awt.Graphics.*;
    import javax.swing.*;
    public class Cinema extends JApplet implements ActionListener
         JButton seating, exit1, exit2, calcost, sexit;     //Declare buttons
         JButton a1, a2, a3, a4, a5, a6, a7, a8;
         JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12;
         JButton c1, c2, c3, c4, c5, c6, c7, c8;
         JButton empty, empty1, empty2, empty3, empty4, empty5;
         Button next, exit;
         Font verdana; //Declare font
         Label title, description, movieselect, aco, stitle, moviec; //Declare labels
         Frame mSelect, seatdisplay; //Declare frames
         Panel panelLeft, panelMiddle, panelRight, panelBottom, panelTop, panelW; //Declare panels
         TextField chooseTime, chooseAge, movieInfo; //Declare text fields
         // private int t; //Declare integer variable
         private Choice movies; //Declare combo box
         private char ageGroup; //Declare character variable
         private int filmTime;
         private double chSeat;
         public void init()
              setSize(500,100); //Set size of applet
              setBackground(Color.green); //Set colour of applet to green
              verdana = new Font("Verdana", Font.BOLD,18); //Define font parameters
              title = new Label("Welcome to Jay's Cinema Booking System"); //Define label
              title.setForeground(Color.black); //Make label black
              title.setFont(verdana); //Set label to the Verdana font
              description = new Label("Choose a film, time and seat #.");
              description.setForeground(Color.black);
              add(title); //Add title label to applet
              add(description);
              movieselect = new Label("Select movie:");
              movieselect.setForeground(Color.black);
              movies = new Choice(); //Define new combo box
              movies.setFont(new Font("Verdana", Font.BOLD,12));
              movies.add("Saw IV"); //Add item to combo box
              movies.add("Good Luck Chuck");
              movies.add("Silk");
              movies.add("Planet Terror");
              movies.setForeground(Color.white); //Set foreground of combo box to white
              movies.setBackground(Color.black); //Set background of combo box to black
              next = new Button("Continue"); //Define new button
              next.setForeground(Color.white);
              next.setBackground(Color.black);
              next.addActionListener(this); //Have actions listen to this button
              add(next); //Add button to the applet
              exit = new Button("Exit");
              exit.setForeground(Color.white);
              exit.setBackground(Color.black);
              exit.addActionListener(this);
              add(exit);
              seating = new JButton("Continue");
              seating.setForeground(Color.white);
              seating.setBackground(Color.black);
              seating.addActionListener(this);
              exit1 = new JButton("Exit");
              exit1.setForeground(Color.white);
              exit1.setBackground(Color.black);
              exit1.addActionListener(this);
              sexit = new JButton("Exit");
              panelLeft = new Panel(); //Define new panels
              panelMiddle = new Panel();
              panelRight = new Panel();
              panelTop = new Panel();
              panelBottom = new Panel();
              panelW = new Panel();
              aco = new Label("Adult, Child or OAP");
              stitle = new Label("Seating");
              stitle.setFont(new Font("Verdana", Font.BOLD,18));
              moviec = new Label("Movies");
              moviec.setFont(new Font("Verdana", Font.BOLD,18));
              chooseTime = new TextField(7); //Define new text fields
              chooseAge = new TextField(7);
              movieInfo = new TextField();
         public void paint(Graphics graf)
         public void actionPerformed(ActionEvent ev)
              if (ev.getSource() == next) //if next button is pressed
                   mSelect = new Frame("Movie Page"); //Define frame
                   mSelect.setLayout(new FlowLayout()); //Set layout
                   mSelect.setVisible(true); //Frame is visible
                   mSelect.setSize(150,300); //Set the size of the frame
                   mSelect.setBackground(Color.green); //Background colour of the frame
                   mSelect.add(moviec); //Add labels
                   mSelect.add(movieselect);
                   mSelect.add(movies);
                   mSelect.add(new Label("Select time: 1, 3, 5, 7, 9"));
                   mSelect.add(chooseTime); //Add text field
                   mSelect.add(new Label("Adult, Child or OAP?"));
                   mSelect.add(chooseAge);
                   mSelect.add(seating); //Add JButton
                   mSelect.add(exit1);
              else
                   setVisible(false); //Frame is insivible and there's no size
                   setSize(0,0);
              if (ev.getSource() == seating)
                   seatdisplay = new Frame("Seating Display");
                   seatdisplay.setLayout(new BorderLayout()); //Define border layout
                   seatdisplay.setVisible(true);
                   seatdisplay.setBackground(Color.green);
                   seatdisplay.setSize(550,500);
                   seatdisplay.add(panelLeft, BorderLayout.WEST); //Position object to the west
                   seatdisplay.add(panelMiddle, BorderLayout.CENTER);
                   seatdisplay.add(panelRight, BorderLayout.EAST);
                   seatdisplay.add(panelTop, BorderLayout.NORTH);
                   seatdisplay.add(panelBottom, BorderLayout.SOUTH);
                   panelLeft.setLayout(new GridLayout(4,2)); //Define new grid layout
                   panelLeft.add(a1 = new JButton("A1")); //Add buttons
                   panelLeft.add(a2 = new JButton("A2"));
                   panelLeft.add(a3 = new JButton("A3"));
                   panelLeft.add(a4 = new JButton("A4"));
                   panelLeft.add(a5 = new JButton("A5"));
                   panelLeft.add(a6 = new JButton("A6"));
                   panelLeft.add(a7 = new JButton("A7"));
                   panelLeft.add(a8 = new JButton("A8"));
                   panelMiddle.setLayout(new GridLayout(3,6));
                   panelMiddle.add(empty = new JButton("")); empty.setVisible(false);
                   panelMiddle.add(b1 = new JButton("B1"));
                   panelMiddle.add(b2 = new JButton("B2"));
                   panelMiddle.add(b3 = new JButton("B3"));
                   panelMiddle.add(b4 = new JButton("B4"));
                   panelMiddle.add(empty3 = new JButton("")); empty3.setVisible(false);
                   panelMiddle.add(empty1 = new JButton("")); empty1.setVisible(false);
                   panelMiddle.add(b5 = new JButton("B5"));
                   panelMiddle.add(b6 = new JButton("B6"));
                   panelMiddle.add(b7 = new JButton("B7"));
                   panelMiddle.add(b8 = new JButton("B8"));
                   panelMiddle.add(empty4 = new JButton("")); empty4.setVisible(false);
                   panelMiddle.add(empty2 = new JButton("")); empty2.setVisible(false);
                   panelMiddle.add(b9 = new JButton("B9"));
                   panelMiddle.add(b10 = new JButton("B10"));
                   panelMiddle.add(b11 = new JButton("B11"));
                   panelMiddle.add(b12 = new JButton("B12"));
                   panelRight.setLayout(new GridLayout(4,2));
                   panelRight.add(c1 = new JButton("C1"));
                   panelRight.add(c2 = new JButton("C2"));
                   panelRight.add(c3 = new JButton("C3"));
                   panelRight.add(c4 = new JButton("C4"));
                   panelRight.add(c5 = new JButton("C5"));
                   panelRight.add(c6 = new JButton("C6"));
                   panelRight.add(c7 = new JButton("C7"));
                   panelRight.add(c8 = new JButton("C8"));
                   // t = Integer.parseInt(chooseTime.getText()); //Convert vlaue into integer
                   movieInfo = new TextField("Movie: " + movies.getSelectedItem() + " Time: "
                   + chooseTime.getText() + "pm" + " Age: " + chooseAge.getText()); /* Concatenate
                   strings together */
                   panelBottom.add(movieInfo);     movieInfo.setEditable(false); //add non editable text field
                   movieInfo.setBackground(Color.black); movieInfo.setForeground(Color.yellow);
                   panelBottom.add(calcost = new JButton("Calculate Cost"));
                   panelBottom.add(exit2 = new JButton("Exit"));
                   panelTop.setLayout(new FlowLayout());
                   panelTop.add(stitle);
                   calcost.addActionListener(this); exit2.addActionListener(this);
                   a1.addActionListener(this); c1.addActionListener(this);
                   a2.addActionListener(this); c2.addActionListener(this);
                   a3.addActionListener(this); c3.addActionListener(this);
                   a4.addActionListener(this); c4.addActionListener(this);
                   a5.addActionListener(this); c5.addActionListener(this);
                   a6.addActionListener(this); c6.addActionListener(this);
                   a7.addActionListener(this); c7.addActionListener(this);
                   a8.addActionListener(this); c8.addActionListener(this);
                   b1.addActionListener(this); b2.addActionListener(this);
                   b3.addActionListener(this); b4.addActionListener(this);
                   b5.addActionListener(this); b6.addActionListener(this);
                   b7.addActionListener(this); b8.addActionListener(this);
                   b9.addActionListener(this); b10.addActionListener(this);
                   b11.addActionListener(this); b12.addActionListener(this);
                   a1.setBackground(Color.black); a1.setForeground(Color.white);
                   a2.setBackground(Color.black); a2.setForeground(Color.white);
                   a3.setBackground(Color.black); a3.setForeground(Color.white);
                   a4.setBackground(Color.black); a4.setForeground(Color.white);
                   a5.setBackground(Color.black); a5.setForeground(Color.white);
                   a6.setBackground(Color.black); a6.setForeground(Color.white);
                   a7.setBackground(Color.black); a7.setForeground(Color.white);
                   a8.setBackground(Color.black); a8.setForeground(Color.white);
                   b1.setBackground(Color.black); b1.setForeground(Color.white);
                   b2.setBackground(Color.black); b2.setForeground(Color.white);
                   b3.setBackground(Color.black); b3.setForeground(Color.white);
                   b4.setBackground(Color.black); b4.setForeground(Color.white);
                   b5.setBackground(Color.black); b5.setForeground(Color.white);
                   b6.setBackground(Color.black); b6.setForeground(Color.white);
                   b7.setBackground(Color.black); b7.setForeground(Color.white);
                   b8.setBackground(Color.black); b8.setForeground(Color.white);
                   b9.setBackground(Color.black); b9.setForeground(Color.white);
                   b10.setBackground(Color.black); b10.setForeground(Color.white);
                   b11.setBackground(Color.black); b11.setForeground(Color.white);
                   b12.setBackground(Color.black); b12.setForeground(Color.white);
                   c1.setBackground(Color.black); c1.setForeground(Color.white);
                   c2.setBackground(Color.black); c2.setForeground(Color.white);
                   c3.setBackground(Color.black); c3.setForeground(Color.white);
                   c4.setBackground(Color.black); c4.setForeground(Color.white);
                   c5.setBackground(Color.black); c5.setForeground(Color.white);
                   c6.setBackground(Color.black); c6.setForeground(Color.white);
                   c7.setBackground(Color.black); c7.setForeground(Color.white);
                   c8.setBackground(Color.black); c8.setForeground(Color.white);
              if (ev.getSource() == exit1)
                   mSelect.setVisible(false);
                   mSelect.setSize(0,0);
              if (ev.getSource() == exit2)
                   seatdisplay.setVisible(false);
              if (ev.getSource() == a1)
                   a1.setBackground(Color.red);
    class Ticket
         public Ticket()
         public Ticket(char age, int time, double seat)
              ageGroup = age;
              filmTime = time;
              chSeat = seat;
         public char displayAge()
              return ageGroup;
         public int displayTime()
              return filmTime;
         public double chargeSeat()
              return chSeat;
    }

  • Problem with jpanel size

    Hi I want to add a view port to a JPanel
    the main problem is that the Jpanel change size as the frame.
    how can i make it independent from the frame so having it; own w, h
    thanks
    package help;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 150;
    static final int FPS_INIT = 0;
    static int fps;
    double x1,x2;
    double y1,y2;
    int dr =1;
    int dy= 1;
    int Selection=0;
    boolean click=true; //check if start has been clicked
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
    protected static int count;
    int R,G,B;  //color
    Cursor c;                    //cursor object
    private static ShapePanel bpnl;
    public MyFrame()
            R=G=B=0;
            int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            frame.setTitle("Game");
            //panel to hold buttons
            JPanel upPanel = new JPanel();
            upPanel.setLayout(new FlowLayout());
            upPanel.setSize(width, height/5);
            //panel to hold SLIDERS
            JPanel leftPanel = new JPanel();
            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
            leftPanel.setSize(50, height);
            //initialize buttons and add to the upPanel
            drawCircle=new JButton("Draw Circle");
            upPanel.add(drawCircle);
            drawStar=new JButton("Draw Star");
            upPanel.add(drawStar);
            drawRectangle=new JButton("Draw Rectangle");
            upPanel.add(drawRectangle);
            drawSquare=new JButton("Draw Square");
            upPanel.add(drawSquare);
            start=new JButton("Start");
            start.setBackground(Color.GREEN);
            //upPanel.add(start);
            clear=new JButton("Clear");
            upPanel.add(clear);
            back=new JButton("Back");
            upPanel.add(back);
            quit=new JButton("Quit");
            quit.setBackground(Color.red);
            upPanel.add(quit);  
            screenshoot=new JButton("ScreenShoot");
            c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
         this.setCursor (c);
            //new object spanel to hold TIMER
            JPanel spanel=new JPanel();
                spanel.setLayout(new GridLayout());
                //slider dimension construction
                JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
                sDimension.setMajorTickSpacing(30);
                sDimension.setMinorTickSpacing(3);
                sDimension.setPaintTicks(true);
                sDimension.setPaintLabels(true);
                Font font = new Font("Serif", Font.ITALIC, 15);
                sDimension.setFont(font);
                sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
                //slider speed construction
                int FPS_MIN_s = 0;
                int FPS_MAX_s = 60;
                int FPS_INIT_s = 0;    //initial frames per second
                JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
                sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
             ////////////////////////// // slider colors////////////////////////////////////////////////////
                int FPS_MIN_C = 0;
                int FPS_MAX_C = 250;
                int FPS_INIT_C = 0;  
                JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
                JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderG.setMajorTickSpacing(50);
                sliderG.setMinorTickSpacing(25);
                sliderG.setPaintTicks(true);
                sliderG.setPaintLabels(true);
                sliderG.setFont(font);
                sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
                JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
              //     spanel.add(sSpeed,BorderLayout.EAST);
                  frame.add(upPanel,BorderLayout.NORTH);
                  frame.add(leftPanel,BorderLayout.WEST);
                  bpnl = new ShapePanel(3000,3000);
                        System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                        bpnl.setFocusable(true);
                  upPanel.setBackground(Color.DARK_GRAY);
                  upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
            frame.add(spanel,BorderLayout.SOUTH);       
            frame.add(bpnl, BorderLayout.CENTER);
            frame.setSize(width, height);
            frame.setVisible(true);               
               leftPanel.add(sliderR);
               leftPanel.add(sliderB);
               leftPanel.add(sliderG);
               leftPanel.add(sDimension,BorderLayout.WEST); 
                 System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private javax.swing.Timer animationTmr;
         private float heigth;
         private float width;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
        thanks

    sorry i hope this is better
    package help;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    int dr =1;
    int dy= 1;
    int Selection=0;
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;     //screen higth
    private static ShapePanel bpnl;
    public MyFrame()
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            bpnl = new ShapePanel(3000,3000);
            System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
            bpnl.setFocusable(true);
              frame.add(bpnl);
            frame.setSize(width, height);
               pack();
            frame.setVisible(true);               
    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
       

  • Cannot output my result using setText

    Everything in my code works fine except for the very last line. I have created a program that calculates a grade based on 5 inputs. After calculating the grade i try and display the result in the output field in my window. The line readsoutput.setText(grade) but it gives me the error when i compile "cannot find symbol". Now if i changed the variable (grade) to a value like ("100") it works no problem, so it appears that the problem has something to do with my variable, which is type double. I cannot figure out how to make my variable display in the output field. The full code is below. Thanks for your help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class gradeCalculator extends JFrame implements ActionListener
    public static final int WIDTH = 300;
    public static final int HEIGHT = 240;
    private TextField inputOne;
    private TextField inputTwo;
    private TextField inputThree;
    private TextField inputFour;
    private TextField inputFive;
    private TextField output;
    public static void main(String[]args)
    gradeCalculator Calculator = new gradeCalculator();
    Calculator.setVisible(true);
    public gradeCalculator()
    setTitle("GradeBook Calculator");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(WIDTH,HEIGHT);
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel scorePanel = new JPanel();
    scorePanel.setLayout(new GridLayout(5,2));
    scorePanel.setBackground(Color.LIGHT_GRAY);
    JLabel labelOne = new JLabel("Unit One: ",JLabel.RIGHT);
    scorePanel.add(labelOne);
    inputOne = new TextField ("",15);
    inputOne.setBackground(Color.white);
    scorePanel.add(inputOne);
    JLabel labelTwo = new JLabel("Unit Two: ",JLabel.RIGHT);
    scorePanel.add(labelTwo);
    inputTwo = new TextField ("",15);
    inputTwo.setBackground(Color.white);
    scorePanel.add(inputTwo);
    JLabel labelThree = new JLabel("Unit Three: ",JLabel.RIGHT);
    scorePanel.add(labelThree);
    inputThree = new TextField ("",15);
    inputThree.setBackground(Color.white);
    scorePanel.add(inputThree);
    JLabel labelFour = new JLabel("Unit Four: ",JLabel.RIGHT);
    scorePanel.add(labelFour);
    inputFour = new TextField ("",15);
    inputFour.setBackground(Color.white);
    scorePanel.add(inputFour);
    JLabel labelFive = new JLabel("Lab: ",JLabel.RIGHT);
    scorePanel.add(labelFive);
    inputFive = new TextField ("",15);
    inputFive.setBackground(Color.white);
    scorePanel.add(inputFive);
    contentPane.add(scorePanel,BorderLayout.NORTH);
    FlowLayout layout = new FlowLayout();
    layout.setAlignment(FlowLayout.RIGHT);
    JPanel averagePanel = new JPanel();
    averagePanel.setLayout(layout);
    averagePanel.setBackground(Color.GRAY);
    JLabel average = new JLabel("Average: ");
    averagePanel.add(average);
    output = new TextField("",15);
    output.setBackground(Color.white);
    averagePanel.add(output);
    contentPane.add(averagePanel,BorderLayout.CENTER);
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.setBackground(Color.LIGHT_GRAY);
    JButton calButton = new JButton("Calculate");
    calButton.addActionListener(this);
    buttonPanel.add(calButton);
    JButton resetButton = new JButton("Reset");
    resetButton.addActionListener(this);
    buttonPanel.add(resetButton);
    contentPane.add(buttonPanel,BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("Reset"))
    inputOne.setText("");
    inputTwo.setText("");
    inputThree.setText("");
    inputFour.setText("");
    inputFive.setText("");
    output.setText("");
    else if(e.getActionCommand().equals("Calculate"))
    String expression;
    int result;
    double grade;
    expression = inputOne.getText();
    result = Integer.parseInt(expression);
    expression = inputTwo.getText();
    result += Integer.parseInt(expression);
    expression = inputThree.getText();
    result += Integer.parseInt(expression);
    expression = inputFour.getText();
    result += Integer.parseInt(expression);
    expression = inputFive.getText();
    result += ((Integer.parseInt(expression))*0.5);
    grade = (result/4.5);
    output.setText(grade);
    }

    Thanks, I kinda knew what I needed to do, but couldn't quite figure it out. Your info pointed me in the right direction. I changed my code to this
    String string = Double.toString(grade);
    output.setText(string);and it seems to work fine now.
    Thanks for your help.

  • Trouble using scroll panel in textArea

    Hello all,
    Im kinda stuck again I'm having a small simple problem where I'm reading the results of a search performed from a .txt file and I'm returning the results to a textArea but the only problem is that the textArea will not create a scroll bar when it is needed and i was wondering if anybody could help
    public Container create_mainPanel()
    //This creates the main panel that will hold the other panel
    //that is used in this program
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    //create JPanels
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    textArea_panel = new JPanel();
    textArea_panel.setLayout(new BorderLayout());
    exit_button_panel = new JPanel();
    exit_button_panel.setLayout(new BorderLayout());
    //The grid layout is used to make a row with 2 buttons across and a column
    panel.setLayout(new GridLayout(1 , 1));
    search_field = new JTextField(20);
    search_field.addActionListener(this);
    textArea = new JTextArea(20 , 50);
    scroll_panel = new JScrollPane(textArea , JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll_panel.setBorder(BorderFactory.createEmptyBorder(0,20,10,20));
    textArea.setEditable(false);
    textArea_panel.add(textArea);
    textArea_panel.setBorder(BorderFactory.createEmptyBorder(10 , 20 , 10 , 20));
    //Create a search button that will connect to the Google Web site and performs
    //a search on the behalf of the user and returns it in XML
    JButton search_button = new JButton("Search the web...");
    panel.add(search_button);
    panel.add(search_field);
    panel.setBorder(BorderFactory.createEmptyBorder(10 , 20 , 10 , 20));
    //Creates a button that can be used to exit the applet
    exit_button = new JButton("Exit");
    //creates a button that can be used to display the results in the text area
    display_button = new JButton("Display results on text area");
    //adds the display_results button to the exit_button_panel
    exit_button_panel.add(display_button);
    //adds the Exit button to the exit_button_panel
    exit_button_panel.add(exit_button);
    exit_button_panel.setLayout(new GridLayout(0 , 1));
    search_button.addActionListener(new search_button_listener());
    exit_button.addActionListener(new exit_button_listener());
    display_button.addActionListener(new display_button_listener());
    //This code is used to specify where the panels should be put to be
    //displayed on the main panel
    //West is the left hand side, East is the right hand side,
    //South is the bottom of the page, and North is the top of the page
    mainPanel.add("North" , panel);
    mainPanel.add("Center" , scroll_panel);
    mainPanel.add("Center" , textArea_panel);
    mainPanel.add("South" , exit_button_panel);
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10 , 10 , 10 , 10));
    return mainPanel;
    } //End of public Applet2()
    Rgds,
    Tony
    [email protected]

    I don't understand why you add textArea twice to mainPanel?
    1. scroll_panel = new JScrollPane(textArea , JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    mainPanel.add("Center" , scroll_panel);2.textArea_panel.add(textArea);
    mainPanel.add("Center" , textArea_panel);

  • JOptionPane.showConfirmDialog -- remember decision checkbox

    Hi
    JOptionPane.showConfirmDialog -- remember decision checkbox
    is there something to set "remember my decision" for the following dialog box i.e. this dialog sits inside a loop over a set of files
    so if i say "yes overwrite" it should remember that decision. Should i make a dialog box on my own or is there a parameter setting for this
    purpose ?
    if(currentCsvOutputFile.isFile()){
    int userConfirm = JOptionPane.showConfirmDialog(
              new JFrame(),
              currentCsvOutputFile + " already exists , Do you want to overwrite it ? " ,
              "Confirm",
              JOptionPane.YES_NO_OPTION);
    }Regards

    No need for a custom dialog, just add a JLabel and a JCheckBox to a JPanel and pass that as the message parameter.JCheckBox remember = new JCheckBox("Remember my decision");
        JPanel panel = new JPanel(new BorderLayout()); // or whatever layout you find best
        panel.add(new JLabel("File already exists , Do you want to overwrite it ? "), BorderLayout.NORTH);
        anel.add(remember, BorderLayout.SOUTH);
        int userConfirm = JOptionPane.showConfirmDialog(new JFrame(), panel, "Confirm", JOptionPane.YES_NO_OPTION);db

  • Add a actionlistener to JTextArea and print out string when  the user input

    Hello:
    I got a problem to add a actionlistener to JTextArea and print out string which from the user input a sentence and after the user press the "enter".
    Could anyone help me please?
    Thanks
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JScrollBar;
    public class PanelDemo extends JFrame {
       private static JTextArea tAreaUp, tAreaDown;
       private BorderLayout layout;
       private static String strings;
       public PanelDemo()
          super( " test " );
          Container container = getContentPane();
          layout = new BorderLayout();
          container.setLayout( layout );
          tAreaUp = new JTextArea(2,1);
          tAreaUp.setLineWrap(true);
          tAreaUp.setWrapStyleWord(true);
          tAreaUp.setEditable(false);
          tAreaUp.append("I am testing ");
          tAreaUp.append("I am testing");
           JScrollPane scrollPane = new JScrollPane(tAreaUp);
           scrollPane.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
           scrollPane.setPreferredSize(new Dimension(250, 250));
          tAreaDown =new JTextArea(2,1);
          tAreaDown.setLineWrap(true);
          tAreaDown.setWrapStyleWord(true);
          tAreaDown.addActionListener(new TextAreaHandler());
          JScrollPane scrollPane2 = new JScrollPane(tAreaDown);
          scrollPane2.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          container.add( scrollPane, layout.CENTER );
          container.add( scrollPane2, layout.SOUTH );
          setSize( 300, 300 );
          setVisible( true );
         //private inner class for event handling
         private class TextAreaHandler implements ActionListener{
              //process textArea events
            public void actionPerformed(ActionEvent e){
               strings=e.getActionCommand();
                System.out.println(strings);
       public static void main( String args[] )
          PanelDemo application = new PanelDemo();
          application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    Thanks for your help, but I still got a question for you.
    Do you think the way I register the even handler to the TextArea is correct?
    Because the compailer complains about that which like
    "D:\101\fig13_27\PanelDemo.java:43: cannot resolve symbol
    symbol  : method addActionListener (PanelDemo.TextAreaHandler)
    location: class javax.swing.JTextArea
          tAreaDown.addActionListener(new TextAreaHandler());

  • Problems implementing abstract classes

    hello.
    this is james mcfadden. I am developing a multiplayer BlackJack card game in Java. the game consists of three programs: BlackJack.java, BlackJackServer.java and BlackJackClient.java (three 3 programs are shown below). i don't know how to implement abstract classes. i am trying to get the BlackJack.java program working with the BlackJackServer.java program. there should be "extends BlackJackServer" somewhere in the BlackJack.java program, but i don't know where.
    import javax.swing.*;
    public class BlackJack extends JPanel{
       public BlackJack(){
          //FlowLayout is default layout manager for a JPanel
          add(new JButton("Hit"));
          add(new JButton("Stay"));
          add(new JButton("New Game"));
       public static void main(String[] args){
          JFrame frame=new JFrame("BlackJack");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(500,500);
          frame.setLocation(200,200);
          BlackJack bj=new BlackJack();
          frame.setContentPane(bj);
          frame.setVisible(true);
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.net.*;//Provides the classes for implementing networking applications
    import java.util.*;//Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
    import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    public class BlackJackServer extends JFrame{
       private JTextArea jta=new JTextArea();//a text area for displaying text
       public static void main(String[] args){  
              new BlackJackServer();//invokes the constructor BlackJackServer()
       }//end main
       public BlackJackServer(){
          setLayout(new BorderLayout());//places the text area on the frame
          add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
          setTitle("BlackJack Server");//Sets the title for this frame to the specified string
          setSize(500,300);//Resizes this component so that it has a width and a height
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
          setVisible(true);//shows the frame
          try{
             ServerSocket serverSocket=new ServerSocket(8000);//creates a server socket
             jta.append("Server started at "+new Date()+'\n');//displays the current date in the text area
             Socket socket=serverSocket.accept();//listens for a connection request
             DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());//creates a data input stream
             DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());//creates a data output stream
             while(true){
                float bet=inputFromClient.readFloat();//receives bet from the client
                float doublebet=bet+bet;//computes double the bet
                outputToClient.writeFloat(doublebet);//sends double the bet back to the client
                jta.append("Bet received from client: "+bet+'\n');//displays the bet in the text area
                jta.append("Double the bet found: "+doublebet+'\n');//displays double the bet in the text area
             }//end while
          }//end try
          catch(IOException ex){
             System.err.println(ex);//displays an error message
          }//end catch
       }//end constructor
    }//end class BlackJackServer
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.net.*;//Provides the classes for implementing networking applications
    import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
    import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    public class BlackJackClient extends JFrame{
       private JTextField jtf=new JTextField();//a text field for receiving text
       private JTextArea jta=new JTextArea();//a text area for displaying text
       private DataOutputStream toServer;//output stream
       private DataInputStream fromServer;//input stream
       public static void main(String[] args){
          new BlackJackClient();//invokes the constructor BlackJackClient()
       public BlackJackClient(){
          JPanel p=new JPanel();//holds the label and text field
          p.setLayout(new BorderLayout());//sets the layout of the content pane of this component by default
          p.add(new JLabel("Enter bet"),BorderLayout.WEST);//displays the bet and lays out a JLabel, arranging and resizing its components to fit in the western region
          p.add(jtf,BorderLayout.CENTER);//lays out the text field, arranging and resizing its components to fit in the centre region
          jtf.setHorizontalAlignment(JTextField.RIGHT);//Sets the horizontal alignment of the text to the right
          setLayout(new BorderLayout());//places the text area on the frame
          add(p,BorderLayout.NORTH);//lays out the text field, arranging and resizing its components to fit in the northern region
          add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
          jtf.addActionListener(new ButtonListener());//invokes the ButtonListener class
          setTitle("BlackJack Client");//Sets the title for this frame to the specified string
          setSize(500,300);//Resizes this component so that it has a width and a height
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
          setVisible(true);//shows the frame
          try{
             Socket socket=new Socket("localhost",8000);//creates a socket to connect to the server
             fromServer=new DataInputStream(socket.getInputStream());//creates an input stream to receive data from the server
             toServer=new DataOutputStream(socket.getOutputStream());//creates an output stream to send data to the server
          }//end try
          catch(IOException ex){
             jta.append(ex.toString()+'\n');//displays an error message
          }//end catch
       private class ButtonListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
             try{
                float bet=Float.parseFloat(jtf.getText().trim());//gets the bet from the text field
                toServer.writeFloat(bet);//Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream
                toServer.flush();//Flushes this output stream and forces any buffered output bytes to be written out
                float doublebet=fromServer.readFloat();//gets double the bet from the server
                jta.append("Bet is "+bet+"\n");//displays the bet in the text area
                jta.append("Double the bet received from the server is "+doublebet+'\n');//displays double the bet in the text area
             }//end try
             catch(IOException ex){
                System.err.println(ex);//displays an error message
             }//end catch
          }//end method
       }//end class
    }//end class BlackJackClient

    there should be "extends BlackJackServer" somewhere in the BlackJack.java programI very much doubt that.
    It's possible you might need to create a BlackJackServer object or something like that. But I don't see the point in subclassing it.

Maybe you are looking for