2011-11-21 59 views
1

我在主类中为我的程序创建了一个框架(大型机),我想添加和删除面板以便在我的程序的不同屏幕之间切换。我的程序的第一个屏幕是具有开始按钮的登录面板。当我按下开始按钮时,我想切换到菜单框架。从actionlistener访问主要创建的JFrame

removeAll方法似乎工作正常,因为登录面板消失了,但是当我使用add,validate和repaint方法时,在它的位置没有任何东西出现。我试图明确指出actionlistener中的大型机(即mainframe.add(menu)),但它不能识别该对象。

在此先感谢!

public class Main { 

    public static JFrame mainframe = new JFrame(); 

    public static void main(String[] args) { 

     // Create mainframe to add and remove panels from 
     LoginPanel lp = new LoginPanel(); 
     System.out.println("mainframe created!"); 

     // Set size of mainframe 
     mainframe.setBounds(0, 0, 500, 500); 
     mainframe.add(lp); 

     // Get the size of the screen 
     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 

     // Determine the new location of the mainframe 
     int w = mainframe.getSize().width; 
     int h = mainframe.getSize().height; 
     int x = (dim.width-w)/2; 
     int y = (dim.height-h)/2; 

     // Move the mainframe 
     mainframe.setLocation(x, y); 
     mainframe.setVisible(true);  
    } 
} 

这是我的登录面板类:

public class LoginPanel extends JPanel { 
    private JTextField usernameField; 
    private JPasswordField passwordField; 
    private final Action action = new SwingAction(); 

    /** 
    * Create the panel. 
    */ 
    public LoginPanel() { 

     JButton btnLogin = new JButton("Login"); 
     btnLogin.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       String username = usernameField.getText(); 
       String password = new String (passwordField.getPassword()); 

       Login login = new Login(); 
       boolean Correct = login.isCorrect(username, password); 
       **if (Correct == true){ 
        removeAll(); 
        Menu menu = new Menu(); 
        add(menu); 
        validate(); 
        repaint(); 
        setBounds(0, 0, 500, 500); 
        System.out.println("Attempted to start menu!"); 
       }** 
      } 
     }); 
     btnLogin.setAction(action); 
     btnLogin.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent arg0) { 

     }}); 

} 
+1

你可以请你的代码在http://sscce.org/表格 – mKorbel

+0

我的随机猜测,如果你要添加到你已经删除的嵌套面板。那个或者你添加到哪个面板的其他错误。 –

+0

在相当基础的层面上,我想知道为什么在我的主类中JFrame公开静态不能在另一个类中解决:S - 任何想法? @mKorbel – user1058210

回答

4

我想添加和删除面板在不同之间顺序切换我的程序屏幕

听起来像你应该使用Card Layout

+0

我解决了它!我所做的是引用框架制作的类:Main.mainframe。然后在actionlistener部分中,我创建了一个容器,并将其用作引用它的更方便的方法,如下所示: Container content = Main.mainframe.getContent(); content.removeAll();等等 – user1058210

1

定义mainframe为一类领域:

private JFrame mainframe;