0

我正在为一门课程写一个假期推荐系统。其中的 GUI 使用 CardLayout。在主类中创建一个用户对象,它的构造函数中定义了默认名称和访问级别。此对象从 main 传递到 UserCard 面板,该面板将其传递给 Login 并登录。如果用户成功登录,则卡片面板从 Login 转换为已登录,并且应该通过调用用户来显示登录用户的用户名.getUsername(); 方法。

我的问题是这样的。由于卡片布局的工作方式,已经在 UserCards 的构造函数中创建了带有用户名 display 的面板,并使用默认值从那时起首先创建了用户对象。在卡片布局对象上调用 show 方法后,我需要找到一种方法来强制此面板重新绘制。以下是有问题的 3 个类的代码。(我已将代码粘贴限制为相关方法)。

//the usercards panel

        public UserCards(User u)
    {
        CardLayout cl = new CardLayout();
        this.setLayout(cl);

        UserOptionsPanel options_card = new UserOptionsPanel(cl, this);
        RegisterPanel register_card = new RegisterPanel(cl, this);
        LoggedInPanel loggedin_card = new LoggedInPanel(cl, this, u);
        LoginPanel login_card = new LoginPanel(cl, this, u, loggedin_card);

        this.add(options_card, options);
        this.add(login_card, login);
        this.add(register_card, register);
        this.add(loggedin_card, loggedin);
    }

//the Loggin action listener user is passed in as a reference to the user object created in //main. the createUser(); method is a badly named method that simply calls setter methods on //the user object's fields

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        String[] vals = packData();
        try
        {
            DBConnection d = new DBConnection();
            Connection conn = d.getConnection();
            Validation v = new Validation(vals, user);
            v.getActual(conn);
            if(v.validate())
            {
                user = v.createUser();
                System.out.println(user.getUserName());
                l.revalidate();
                cl.show(pane, "loggedin");
            }
            else
            {
                lbl_statusmsg.setText("Password Incorrect");
                lbl_statusmsg.repaint();
            }

        }
        catch(ClassNotFoundException | SQLException ex)
        {
            ex.printStackTrace();
        }
    }

//the loggedin constructor

public class LoggedInPanel extends JPanel
{
    private User user;
    private JLabel lbl_details;
    public LoggedInPanel(CardLayout cl, Container pane, User u)
    {
        super();
        user = u;
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        lbl_details = new JLabel();
        lbl_details.setText("Welcome "+user.getUserName());

        this.add(lbl_details);
    }    
}

抱歉,如果我没有说得太清楚,我不会寻求帮助:)

4

1 回答 1

0

你的意思是这样的吗?

CardLayout cl = new CardLayout() {
  @Override
  public void show(java.awt.Container parent, String name) {
    super.show(parent, name);
    // your code here

  }
};
于 2013-03-18T13:06:07.813 回答