Changing the JFrame title

前端 未结 4 507
终归单人心
终归单人心 2020-12-03 15:19

This code compiles, I just can\'t get the name to change on the title bar.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;  
import java.awt         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-03 15:55

    newTitle is a local variable where you create the fields. So when that functions ends, the variable newTitle, does not exist anymore. (The JTextField that was referenced by newTitle does still exist however.)

    Thus, increase the scope of the variable, so that you can access it another method.

    public SomeFrame extends JFrame {
       JTextField myTitle;//can be used anywhere in this class
    
       creationOfTheFields()
       {
       //other code
          myTitle = new JTextField("spam");  
          myTitle.setBounds(80, 40, 225, 20);
          options.add(myTitle);
       //blabla other code
       }
    
       private void New_Name()  
       {  
          this.setTitle(myTitle.getText());  
       } 
    }
    

提交回复
热议问题