java点击按钮实现开启新界面_Swing组件中,如何用一个BUTTON弹出一个新窗口?

满意答案

dcebd7a0de6265b6ccae5ead692f1eab.png

znzrg

2013.12.24

dcebd7a0de6265b6ccae5ead692f1eab.png

采纳率:45%    等级:12

已帮助:7121人

在JButton 的事件中 new 一个窗口然后 设置窗口为可见的

例如 dialog.setVisble(true);

下面是一个示例:

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

/**

*

* @author guan

*/

public class FrameDemo extends JFrame {

JButton loginButton =null;

JButton exitButton = null;

JPanel mainPanel =null;

JDialog dialog =null;

public FrameDemo() {

loginButton = new JButton("Login");

exitButton = new JButton("Exit");

loginButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

showDialog(); //显示窗口

}

});

exitButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

System.exit(0); //关闭窗口

}

});

mainPanel = new JPanel();

mainPanel.add(loginButton);

mainPanel.add(exitButton);

this.add(mainPanel); //将主面板添加到frame中

}

/**

* 显示对话框

*/

private void showDialog(){

this.setVisible(false);

dialog = new JDialog(this, true);

dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

dialog.setSize(300,180);

dialog.setTitle("DialogTest");

dialog.add(new JLabel("这个是对话框"));

dialog.setLocationRelativeTo(this);

dialog.setVisible(true); //显示对话框,窗口阻塞,不往下执行,只有等到对话框关闭了才往下执行。

//判断主窗口是否是隐藏的,如果是隐藏的就显示

if (!this.isVisible()) {

this.setVisible(true);

}

}

public static void main(String[] args) {

JFrame frame = new FrameDemo();

frame.setTitle("JFrame Demo");

frame.setSize(500, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

00分享举报

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值