21xrx.com
2024-09-19 09:43:35 Thursday
登录
文章检索 我的文章 写文章
Java实现按钮点击跳转新界面
2023-06-11 13:42:27 深夜i     --     --
Java GUI

当我们在使用Java GUI开发时,经常需要实现按钮点击跳转到一个新界面的功能。下面我们来介绍实现的具体步骤和代码案例。

首先,我们需要创建两个JFrame即原界面和目标界面,并且在原界面中添加一个 JButton。

接下来,我们需要给 JButton 添加一个 ActionListener,实现点击事件跳转到目标界面的功能。具体代码如下:


button.addActionListener(new ActionListener() {

  @Override

  public void actionPerformed(ActionEvent e) {

    new NewFrame().setVisible(true);

    dispose();

  }

});

其中,NewFrame 是目标界面的类名,dispose() 函数是关闭原界面的方法。

下面是完整的代码实现:


import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MainFrame extends JFrame {

  public MainFrame() {

    init();

    addComponent();

    addListener();

    setVisible(true);

  }

  private void init() {

    setTitle("Main Frame");

    setSize(300, 200);

    setLocationRelativeTo(null);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

  private void addComponent() {

    JPanel panel = new JPanel();

    JButton button = new JButton("Click to jump");

    panel.add(button);

    setContentPane(panel);

  }

  private void addListener() {

    button.addActionListener(new ActionListener() {

      @Override

      public void actionPerformed(ActionEvent e) {

        new NewFrame().setVisible(true);

        dispose();

      }

    });

  }

  public static void main(String[] args) {

    new MainFrame();

  }

}

class NewFrame extends JFrame {

  public NewFrame() {

    init();

    addComponent();

    setVisible(true);

  }

  private void init() {

    setTitle("New Frame");

    setSize(300, 200);

    setLocationRelativeTo(null);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

  private void addComponent() {

    JPanel panel = new JPanel();

    JLabel label = new JLabel("This is the new frame");

    panel.add(label);

    setContentPane(panel);

  }

}

三个 、按钮点击跳转、JFrame

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复