简体   繁体   中英

using setTitle on a method

I need to set the title from a method (not constructor). I tried doing it like this, but it's not working:

import javax.swing.*;
import java.awt.*;
public class PointGraphWriter extends JPanel
{
   public String title;

   public void setTitle(String name)
   {
       title = name;
   }
   public PointGraphWriter()
   {
       JFrame frame = new JFrame;
       int width= 300;
       frame.setSize(width*3/2,width);
       frame.setVisible(true);
       frame.setTitle(title);
       frame.setBackground(Color.white);
       frame.getContentPane;
       frame.add(this);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

with the main method :

public class TestPlot
{
    public static void main(String[] a)
    { 
        PointGraphWriter e = new PointGraphWriter();
        e.setTitle("Graph of y = x*x");
    }
}

You changed the variable title but that doesn't affect the frame. You will need to call setTitle on the frame again.

Keep an instance variable for the frame:

private JFrame frame;

In the constructor, assign the new JFrame to the instance variable, so you can change its title later in setTitle :

public void setTitle(String name)
{
   title = name;
   frame.setTitle(name);
}

You have a method to alter the variable title , which is good. The problem you are having is that you are trying to set the title of the frame in the constructor method .

In this code:

PointGraphWriter e = new PointGraphWriter();
e.setTitle("Graph of y = x*x");

e is constructed before you use the setTitle method to change the title variable in the PointGraphWriter class. Therefore, you are trying to set the title of the frame to be a null String because the setTitle method is only called after the constructor method.

You could do two things:

  1. Set the title of the frame in the setTitle method:

     JFrame frame = new JFrame; public void setTitle(String name) { frame.setTitle(name); } 
  2. Or you could change your constructor method to take in the title as an argument:

     public PointGraphWriter(String title) { JFrame frame = new JFrame; int width= 300; frame.setSize(width*3/2,width); frame.setVisible(true); frame.setTitle(title); frame.setBackground(Color.white); frame.getContentPane; frame.add(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } 

    And then create PointGraphWriter like this:

     PointGraphWriter e = new PointGraphWriter("Graph of y = x*x"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM