Swing组件中,如何用一个BUTTONd出一个新窗口?

Swing组件中,如何用一个BUTTONd出一个新窗口?,第1张

在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)

}

}

// 修改后的代码。里面有几个地方需要注意一下:

// 1 实现接口必须要实现接口的方法

// 2 创建新窗口必须实例化新的JFrame或JDialog对象。

// 详细的请看代码注释吧。

import javax.swing.*

import java.awt.Rectangle

import java.awt.event.*

public class Swing7 extends JFrame implements ActionListener {

JButton jb = new JButton()

public Swing7() {

this.setTitle("Java——")

jb.setText("确定")

jb.setMnemonic('a')

this.add(jb)

this.setBounds(200, 300, 250, 300)

this.setVisible(true)

jb.addActionListener(this)//由于Swing7实现了ActionListener接口,所以给jb添加的ActionListener就是Swing7实例。

}

public void actionPerformed(ActionEvent e) {// 实现ActionListener接口的actionPerformed接口。

JFrame frame = new JFrame("新窗口")//构造一个新的JFrame,作为新窗口。

frame.setBounds(// 让新窗口与Swing7窗口示例错开50像素。

new Rectangle(

(int) this.getBounds().getX() + 50,

(int) this.getBounds().getY() + 50,

(int) this.getBounds().getWidth(),

(int) this.getBounds().getHeight()

)

)

JLabel jl = new JLabel()// 注意类名别写错了。

frame.getContentPane().add(jl)

jl.setText("这是新窗口")

jl.setVerticalAlignment(JLabel.CENTER)

jl.setHorizontalAlignment(JLabel.CENTER)// 注意方法名别写错了。

frame.setVisible(true)

}

public static void main(String args[]) {

Swing7 s = new Swing7()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/bake/11887599.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存