2016-02-22 2 views
0

Вот мой код:Невозможно открыть новый JFrame с JButton из другого класса

LoginPage:

public class LoginPage { 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       LoginPage window = new LoginPage(); 
       window.frmLoginPage.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

private JFrame frmLoginPage; 
private JPasswordField passwordField; 
private JTextField textField; 

/** 
* Create the application. 
*/ 
public LoginPage() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frmLoginPage = new JFrame(); 
    frmLoginPage.setTitle("Login Page"); 
    frmLoginPage.getContentPane().setBackground(new Color(100, 149, 237)); 
    frmLoginPage.setBounds(100, 100, 742, 597); 
    frmLoginPage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frmLoginPage.getContentPane().setLayout(null); 

    JPanel panel = new JPanel(); 
    panel.setBorder(new LineBorder(new Color(0, 0, 0), 3, true)); 
    panel.setBackground(Color.WHITE); 
    panel.setBounds(131, 106, 459, 288); 
    frmLoginPage.getContentPane().add(panel); 
    panel.setLayout(null); 

    JLabel lblUserLogin = new JLabel("User Login"); 
    lblUserLogin 
      .setIcon(new ImageIcon(LoginPage.class.getResource("/javax/swing/plaf/metal/icons/ocean/info.png"))); 
    lblUserLogin.setFont(new Font("Trebuchet MS", Font.PLAIN, 34)); 
    lblUserLogin.setHorizontalAlignment(SwingConstants.CENTER); 
    lblUserLogin.setBounds(114, 16, 243, 39); 
    panel.add(lblUserLogin); 

    JLabel lblUserId = new JLabel("User ID:"); 
    lblUserId.setBounds(52, 75, 90, 20); 
    panel.add(lblUserId); 

    JLabel lblPassword = new JLabel("Password:"); 
    lblPassword.setBounds(52, 140, 90, 20); 
    panel.add(lblPassword); 

    passwordField = new JPasswordField(); 
    passwordField.setBounds(52, 176, 282, 26); 
    panel.add(passwordField); 

    textField = new JTextField(); 
    textField.setBounds(52, 98, 283, 26); 
    panel.add(textField); 
    textField.setColumns(10); 

    JButton btnLogIn = new JButton("Log In"); 
    btnLogIn.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent arg0) { 
      new SemesterPage(); 
      frmLoginPage.setVisible(false); 
     } 
    }); 

    btnLogIn.setBounds(52, 219, 115, 29); 
    panel.add(btnLogIn); 

    JButton btnRegister = new JButton("Register"); 
    btnRegister.setBounds(179, 219, 115, 29); 
    panel.add(btnRegister); 
} 

}

И когда кнопка "Вход" получает щелкнул, новое окно в этот класс должен выскочить:

SemesterPage:

public class SemesterPage { 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       SemesterPage window = new SemesterPage(); 
       window.frmControlPanel.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

private JFrame frmControlPanel; 

/** 
* Create the application. 
*/ 
public SemesterPage() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frmControlPanel = new JFrame(); 
    frmControlPanel.setTitle("Control Panel"); 
    frmControlPanel.setBounds(100, 100, 1000, 1000); 
    frmControlPanel.getContentPane().setBackground(new Color(100, 149, 237)); 

    JPanel panel = new JPanel(); 
    panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true)); 

    JPanel panel_1 = new JPanel(); 
    panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 2, true)); 

    JPanel panel_2 = new JPanel(); 
    panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 2, true)); 
    GroupLayout groupLayout = new GroupLayout(frmControlPanel.getContentPane()); 
    groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout 
      .createSequentialGroup().addContainerGap() 
      .addComponent(panel, GroupLayout.PREFERRED_SIZE, 637, GroupLayout.PREFERRED_SIZE).addGap(30) 
      .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) 
        .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE) 
        .addComponent(panel_2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
      .addContainerGap())); 
    groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING) 
      .addGroup(groupLayout.createSequentialGroup().addContainerGap() 
        .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) 
          .addComponent(panel, GroupLayout.PREFERRED_SIZE, 793, GroupLayout.PREFERRED_SIZE) 
          .addGroup(groupLayout.createSequentialGroup() 
            .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 370, 
              GroupLayout.PREFERRED_SIZE) 
            .addGap(18).addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 412, 
              GroupLayout.PREFERRED_SIZE))) 
        .addContainerGap(97, Short.MAX_VALUE))); 
    frmControlPanel.getContentPane().setLayout(groupLayout); 
    frmControlPanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JMenuBar menuBar = new JMenuBar(); 
    frmControlPanel.setJMenuBar(menuBar); 

    JMenu mnFile = new JMenu("File"); 
    menuBar.add(mnFile); 

    JMenuItem mntmNew = new JMenuItem("New"); 
    mnFile.add(mntmNew); 

    JMenuItem mntmSave = new JMenuItem("Save"); 
    mnFile.add(mntmSave); 

    JMenuItem mntmLogOut = new JMenuItem("Log Out"); 
    mnFile.add(mntmLogOut); 
} 

}

Проблема в том, что окно не открывается. Ничего не происходит при нажатии кнопки. У меня такое чувство, что когда я называю «новый SemesterPage()», конструктор в моем классе SemesterPage не запускает JFrame. Как я могу это исправить?

спасибо!

+1

Вызова 'SetVisible (истина)' на новой раме, так же, как вы делали для первого один? – immibis

+0

@immibis Да, но вопрос «как»;) – MadProgrammer

ответ

1

Вы не создадите новый экземпляр SemesterPage, но не делают его видимым ...

Ваш SemesterPage будет нужен метод, который позволит абоненту поручить ему, что он хотел бы сделать экземпляр JFrame который он создает видимый

может быть что-то вроде ...

public class SemesterPage { 

    private JFrame frmControlPanel; 

    //... 
    public void setVisible(boolean v) { 
     frmControlPanel.setVisible(v); 
    } 

Сказав это, вы можете немного пересмотреть свой дизайн ...

Посмотрите на The Use of Multiple JFrames, Good/Bad Practice?.

Тогда How to Make Dialogs и How to Use CardLayout некоторых идеи по альтернативам

Вы также мог бы рассмотреть, взглянув на Model-View-Controller, for example

+0

Это исправило мою проблему, большое вам спасибо! –

+0

@calvinphung: так как ответ Мада установил вашу проблему, не забудьте как проголосовать за ответ, так и принять его. Если у вас есть вопрос о том, как это сделать, просмотрите раздел справки: [когда кто-то отвечает на мой вопрос] (http://stackoverflow.com/help/someone-answers). –

+0

Да, я собирался это сделать. Был лимит времени, когда я мог голосовать и принимать ответ печально –

Смежные вопросы