#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14

    Desperate help with Java needed


    Hi All,

    I know it's not usually kosher to get anwers to school questions online, but I am at the end of my rope with several problems for my intro to Java course. online resources don't seem to explain it in a way that I can understand and I'm hoping you guys can help. I have two problems that I cannot get to work. I'll post one, then , maybe,m the other.

    In this problem, I have a single java file that is to present two buttons, these buttons will show other windows when clicked. I'm working on one currently. I have the window displaying, but the class file that is supposed to fill the frame isnt there, it's a blank frame. There are no errors given, and I don't know what's wrong.

    Main file:
    Code:
    // MultipleWindowsDemo.java: Display mortgage in a seperate window
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MultipleWindowsDemo extends JFrame implements ActionListener
    {
      private JTextArea jta;
      private JButton jbtShowMortgage = new JButton("Mortgage");
      private exercise10_3_panel mortgage = new exercise10_3_panel();
    
      // Create a new frame to hold the histogram panel
      private JFrame mortgageFrame = new JFrame();
    
      // Construct the frame
      public MultipleWindowsDemo()
      {
    
        // Place scroll pane and button in the frame
        getContentPane().add(jbtShowMortgage, BorderLayout.SOUTH);
    
        // Register listener
        jbtShowMortgage.addActionListener(this);
    
        // Create a new frame to hold the histogram panel
        mortgageFrame.getContentPane().add(mortgage);
        mortgageFrame.pack();
        mortgageFrame.setTitle("Mortgage");
      }
    
      // Handle the button action
      public void actionPerformed(ActionEvent e)
      {
      	
      	mortgage.init();
        // Show the frame
        mortgageFrame.setVisible(true);
      }
    
      // Main method
      public static void main(String[] args)
      {
        MultipleWindowsDemo frame = new MultipleWindowsDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Multiple Windows Demo");
        frame.pack();
        frame.setVisible(true);
      }
    
    }
    and the class it calls:




    Code:
    //************************************************
    //* exercise10_3.java                            *
    //*                                              *
    //* Purpose: Re-write the mortgageApplet from    *
    //* example 10.3 in the book to allow it to run  *
    //* as both an applet and an application as      *
    //* described in Exercise 10.3                   *
    //*                                              *
    //* ID: 2112496                                  *
    //*                                              *
    //* @author:  Rod Naugler                        *
    //* @date:    January 23, 2003                   *
    //* @version: 1.0                                *
    //************************************************
    
    // MortgageApplet.java: Applet for computing mortgage payments
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    
    public class exercise10_3_panel extends JPanel implements ActionListener
    {
      // Declare and create text fields for interest rate
      // year, loan amount, monthly payment, and total payment
      private JTextField jtfAnnualInterestRate = new JTextField();
      private JTextField jtfNumOfYears = new JTextField();
      private JTextField jtfLoanAmount = new JTextField();
      private JTextField jtfMonthlyPayment = new JTextField();
      private JTextField jtfTotalPayment = new JTextField();
    
      // Declare and create a Compute Mortgage button
      private JButton jbtComputeMortgage = new JButton("Compute Mortgage");
    
      // Initialize user interface
      public void init()
      {
        // Set properties on the text fields
        jtfMonthlyPayment.setEditable(false);
        jtfTotalPayment.setEditable(false);
    
        // Right align text fields
        jtfAnnualInterestRate.setHorizontalAlignment(JTextField.RIGHT);
        jtfNumOfYears.setHorizontalAlignment(JTextField.RIGHT);
        jtfLoanAmount.setHorizontalAlignment(JTextField.RIGHT);
        jtfMonthlyPayment.setHorizontalAlignment(JTextField.RIGHT);
        jtfTotalPayment.setHorizontalAlignment(JTextField.RIGHT);
    
        // Panel p1 to hold labels and text fields
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 2));
        p1.add(new Label("Annual Interest Rate"));
        p1.add(jtfAnnualInterestRate);
        p1.add(new Label("Number of Years"));
        p1.add(jtfNumOfYears);
        p1.add(new Label("Loan Amount"));
        p1.add(jtfLoanAmount);
        p1.add(new Label("Monthly Payment"));
        p1.add(jtfMonthlyPayment);
        p1.add(new Label("Total Payment"));
        p1.add(jtfTotalPayment);
        p1.setBorder(new
          TitledBorder("Enter interest rate, year and loan amount"));
    
        // Panel p2 to hold the button
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
        p2.add(jbtComputeMortgage);
    
        // Add the components to the applet
        JPanel p3 = new JPanel();
        p3.add(p1, BorderLayout.CENTER);
        p3.add(p2, BorderLayout.SOUTH);
    
        // Register listener
        jbtComputeMortgage.addActionListener(this);
      }
      
      // Handler for the "Compute Mortgage" button
      public void actionPerformed(ActionEvent e)
      {
        if (e.getSource() == jbtComputeMortgage)
        {
          // Get values from text fields
          double interest =
            (Double.valueOf(jtfAnnualInterestRate.getText())).doubleValue();
          int year =
            (Integer.valueOf(jtfNumOfYears.getText())).intValue();
          double loan =
            (Double.valueOf(jtfLoanAmount.getText())).doubleValue();
    
          // Create a mortgage object
          Mortgage m = new Mortgage(interest, year, loan);
    
          // Display monthly payment and total payment
          jtfMonthlyPayment.setText(String.valueOf(m.monthlyPayment()));
          jtfTotalPayment.setText(String.valueOf(m.totalPayment()));
        }
      }
      public Dimension getPreferredSize()
      {
      	return new Dimension(300,300);
      }
    }
    Please ignore the headers on both, as I'm canablising other code for this.

    Thanks

    Statik
  2. #2
  3. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    I found your problem but I won't give you the answer. However, I will tell you that the problem is located in the exercise10_3_panel object, specifically in the 'init' method. Something to do with the panels that you make. Good luck!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14
    Well, that's better than nothing. Maybe I can get it from there. If I have further problems, can I continue to get help? Also, I have another problem, unrealated, in another exercise. Do you mind helping htere as well?

    EDIT: I see that my panel p3 isn't being added to anything, but I don't know what to add it to. more hintage please?

    Statik
    Last edited by Statik; January 30th, 2003 at 03:51 PM.
  6. #4
  7. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    I personally will continue to help as long as I am here and I feel you are trying to help yourself also. I will not give you the answers to school problems but I will help you find the anwers yourself ("Give a man a fish and feed him for a day, teach a man to fish and feed him for a lifetime" and all that).

    Your problem in 'init' is very simple. I am sure you merely overlooked it. Just go through the steps you need to do in that method and you should see it eventually. Oh, and your comments in that method are misleading.
    Last edited by Nemi; January 30th, 2003 at 03:45 PM.
  8. #5
  9. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    Hmm, I was assuming you had wrote the code we see, but you may be using an existing code base? I say this because I assumed a certain level of understanding from the code that I see, but I may be wrong.

    You do not add panel3 to the exercise10_3_panel itself. Also, there is a slight problem with panel3. JPanels have a FlowLayout by default, and as the code reads it appears that the writer wants the button to be right aligned in the panel (panel2's layout is expressly set to RIGHT). Since the layout manager is not changed for panel3, the BorderLayout.CENTER and BorderLayout.SOUTH are ignored. To use a BorderLayout, you must change the default layout manager when creating panel3. Your code should be something like:
    Code:
    ...
    
        JPanel p3 = new JPanel(new BorderLayout());
        p3.add(p1, BorderLayout.CENTER);
        p3.add(p2, BorderLayout.SOUTH);
    
        add(p3);
    
        // Register listener
        jbtComputeMortgage.addActionListener(this);
      }
    ...
    This will add those three panels to the exercise10_3_panel object, which is itself a JPanel. Hope that helps
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14
    I might have caught the Borderlayout problem, but my text made no mention of the add(p3); type command. I was always trying to figure out what the x would be in an x.add(p3); type command was. Thanks for that extra piece of knowledge. As for the mortgage app itself, it was an example in the book, as is the calculator app that will be on a second button. Now that I can see where the problem was, I think I can handle the second button.

    Are you ready for the other problem?

    In the following code, I'm to create a text label and three scroll bars, one for red, green and blue. Based on the values of these, I'm to set the color of the label. The problem is, I can't figure out the reference method back to the label from the action listener. It's a scope issue, I think, but I can 't work out how to fix it. This one I wrote entirely myself.
    Attached Files
  12. #7
  13. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    was always trying to figure out what the x would be in an x.add(p3); type command was
    The x in x.add(p3) is actually the keyword "this". So, you can also use this.add(p3) and it will work also. The "this" keyword is implicit when you just say add(p3). The reason you can do this is because that object is itself a JPanel and has all the methods available to it that a JPanel has.
    The problem is, I can't figure out the reference method back to the label from the action listener. It's a scope issue, I think, but I can 't work out how to fix it. This one I wrote entirely myself.
    You have several problems here, some I think are created from your attempt to access the displayPanel. Your changeColor method is defined in another method. That won't work. In that method you are missing a right parenthesis.

    The reason you cannot access displayPanel is indeed a scope issue. If you want to access a common object from several methods you have two choices - you can pass the object to each method or you can make the object a instance variable of the class you are working in. The easiest in this case is to declare displayPanel a private instance variable. Then it is accessible from all those methods.

    Lastly, you are setting the foreground color of the panels and that only affects something you paint on the panel. What you want to do it set the background color of the panels.

    I am supplying some edited code below. Not all the sliders are working at this point, so it is not done. I am not sure what editor you are using when coding, or what they want you to use there at school, but if you download Eclipse from www.eclipse.org it may be easier for you to spot some of these problems. GL

    Code:
    //************************************************
    //* exercise9_9.java                             *
    //*                                              *
    //* Purpose: Create a program that creates four  *
    //* text fields and a combo box for users to     *
    //* enter address information. Also create a     *
    //* store button that takes the contents of the  *
    //* text fields and the combo box and places them*
    //* in the text area as described in Exercise 9.7*
    //*                                              *
    //* ID: 2112496                                  *
    //*                                              *
    //* @author:  Rod Naugler                        *
    //* @date:    December 4, 2002                   *
    //* @version: 1.0                                *
    //************************************************
    
    //Imports used in this class
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Color;
    
    public class exercise9_9 extends JFrame implements AdjustmentListener {
    	//Define the private variables we need
    	private JScrollBar scrollRed, scrollGreen, scrollBlue;
    	private TitledBorder scrollPanelBorder = new TitledBorder("");
    	JPanel mainPanel;
    	private JPanel displayPanel;
    	//Main method
    	public static void main(String[] args) {
    		//Variables used in this class
    		Dimension frameSize; //This holds the size of the frame as a variable
    		Dimension screenSize; //This holds the size of the screen as a variable
    		int screenWidth; //A variable to hold the width of the screen
    		int screenHeight; //A variable to hold the height of the screen
    		int y; //A variable to hold the vertical destination for
    		//the frame
    		int x; //A variable to hold the horizontal destination for
    		//the frame
    
    		//Create a frame that is 400 pixels wide and 250 pixels high. We add an
    		//extra 20 pixels of width because of the way the scrollbar seems to
    		//render. 
    		exercise9_9 frame = new exercise9_9();
    		frame.setSize(420, 250);
    		//Make sure that if the window is closed, it terminates the program.
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		//Get the dimensions of the screen
    		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    		screenWidth = screenSize.width;
    		screenHeight = screenSize.height;
    
    		//Get the dimensions of the frame and center the frame by halving the
    		//difference between the screen size and the frame size
    		frameSize = frame.getSize();
    		x = (screenWidth / 2) - (frameSize.width / 2);
    		y = (screenHeight / 2) - (frameSize.height / 2);
    
    		//Use the values of x and y to center the frame
    		frame.setLocation(x, y);
    
    		//Set the frame as visible
    		frame.setVisible(true);
    
    	}
    
    	//Default constructor
    	public exercise9_9() {
    		//Title the window
    		setTitle("Exercise 9.9: Use Scroll Bars");
    
    		//Create the scrollbars with horizontal orientation, minimum value of 0
    		//and maximum value of 255. Make the visible amount 255, the block increment 25
    		//and the unit incrememnt 1
    
    		scrollRed = new JScrollBar();
    		scrollRed.setOrientation(Adjustable.HORIZONTAL);
    		scrollRed.setMinimum(0);
    		scrollRed.setMaximum(255);
    		int redValue = 128;
    		scrollRed.setValue(redValue);
    		scrollRed.setVisibleAmount(1);
    		scrollRed.setBlockIncrement(25);
    		scrollRed.setUnitIncrement(1);
    
    		scrollBlue = new JScrollBar();
    		scrollBlue.setOrientation(Adjustable.HORIZONTAL);
    		scrollBlue.setMinimum(0);
    		scrollBlue.setMaximum(255);
    		int blueValue = 128;
    		scrollBlue.setValue(blueValue);
    		scrollBlue.setVisibleAmount(1);
    		scrollBlue.setBlockIncrement(25);
    		scrollBlue.setUnitIncrement(1);
    
    		scrollGreen = new JScrollBar();
    		scrollGreen.setOrientation(Adjustable.HORIZONTAL);
    		scrollGreen.setMinimum(0);
    		scrollGreen.setMaximum(255);
    		int greenValue = 128;
    		scrollGreen.setValue(greenValue);
    		scrollGreen.setVisibleAmount(1);
    		scrollGreen.setBlockIncrement(25);
    		scrollGreen.setUnitIncrement(1);
    
    		//Create the scrollbar pane
    		JPanel scrollPanel = new JPanel();
    		scrollPanel.setLayout(new GridLayout(3, 1));
    
    		//Add the scrollbars
    		scrollPanel.add(scrollRed);
    		scrollPanel.add(scrollGreen);
    		scrollPanel.add(scrollBlue);
    
    		//Create three labels
    		JLabel redLabel = new JLabel("Red");
    		JLabel blueLabel = new JLabel("Blue");
    		JLabel greenLabel = new JLabel("Green");
    		JLabel textLabel = new JLabel("Show Colors");
    
    		//Create a label panel and add the labels
    		JPanel labelPanel = new JPanel();
    		labelPanel.setLayout(new GridLayout(3, 1));
    
    		//Add the labels
    		labelPanel.add(redLabel);
    		labelPanel.add(greenLabel);
    		labelPanel.add(blueLabel);
    
    		//Create a inputPanel to hold the labels and the scrollbars
    		JPanel inputPanel = new JPanel();
    		inputPanel.setLayout(new GridLayout(1, 2));
    		inputPanel.add(labelPanel);
    		inputPanel.add(scrollPanel);
    
    		//Create a title border to apply to the panel
    		scrollPanelBorder = new TitledBorder("Choose Colors");
    
    		//Apply the border to the panel
    		inputPanel.setBorder(scrollPanelBorder);
    
    		//Create the output panel
    		displayPanel = new JPanel();
    		displayPanel.setFont(new Font("SansSerif", Font.BOLD, 20));
    		displayPanel.setBackground(new Color(redValue, greenValue, blueValue));
    		displayPanel.add(textLabel);
    
    		//Create the main pane
    		mainPanel = new JPanel();
    
    		//Set the frame layoutManager and add the two panels		
    		mainPanel.setLayout(new GridLayout(2, 1));
    		mainPanel.add(displayPanel);
    		mainPanel.add(inputPanel);
    
    		getContentPane().setLayout(new GridLayout(1, 1));
    		getContentPane().add(mainPanel);
    
    		//Register the scrollbars with the action handlers
    		scrollRed.addAdjustmentListener(this);
    		scrollGreen.addAdjustmentListener(this);
    		scrollBlue.addAdjustmentListener(this);
    
    	}
    
    	public void changeColor(int Red, int Green, int Blue) {
    		displayPanel.setBackground(new Color(Red, Green, Blue));
    	}
    
    	//Handle the button and combobox events
    	public void adjustmentValueChanged(AdjustmentEvent e) {
    		//If the source of the action was the red scrollbar
    		if (e.getSource() == scrollRed) {
    			//Get the current value of the scrollbar
    			int redValue = scrollRed.getValue();
    			displayPanel.setBackground(new Color(redValue, 128, 128));
    		}
    		//If the source of the action was the green scrollbar
    		if (e.getSource() == scrollGreen) {
    			//Get the current value of the scrollbar
    			int greenValue = scrollGreen.getValue();
    		}
    		//If the source of the action was the red scrollbar
    		if (e.getSource() == scrollBlue) {
    			//Get the current value of the scrollbar
    			int blueValue = scrollBlue.getValue();
    		}
    	}
    }
    Last edited by Nemi; February 1st, 2003 at 01:56 PM.
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2001
    Posts
    130
    Rep Power
    14
    I did download eclipse as you suggested. It looks nice, but I don't see a way to load in a previously saved .java file. So I have to cut/paste the file in?

    I still have to find a way to change the foreground color of the label. I originally had a block using fontmetrics to draw the label and then I could set it's foreground. But I had the same problem with scope as I did with just a straight label.

    Maybe I can do it now.

    Statik
  16. #9
  17. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    Use 'Import->File system' pick the directory then the files will show up in the split pane. You can choose the one you want to import.

    I am not sure what you mean by foreground color of the label. If you want to change anything with the label, you need to make it a instance variable of the class like I did with the panel. foreground color will change the text color, background color will change the background.
    Last edited by Nemi; February 2nd, 2003 at 06:28 PM.

IMN logo majestic logo threadwatch logo seochat tools logo