java 对话框里可不可以加按钮组件?

java 对话框里可不可以加按钮组件?,第1张

可以。模态不模态和添加组件没有关系

JDialog dialog = new JDialog(frame, "Setting")

// dialog.setModalityType(...)

dialog.getContentPane().add(new JButton("OK"), BorderLayout.PAGE_END)

dialog.pack()

dialog.setVisible(true)

你可以定义一个数组,

JButton[] b = new JButton[4]

for(i=1i<=4i++){

b[i]=new JButton(i+"号按钮 ")

container.add(b)}

给你一个例子:

import java.awt.*

import javax.swing.*

import java.awt.event.*

class DrawRect{

int[][] e

JFrame jf

public DrawRect() {

jf = new JFrame("Button")

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

JButton[] bgroup=new JButton[225]

Container contentPane=jf.getContentPane()

contentPane.setLayout(new GridLayout(15,15))

String s

for(int i=0i<225i++){

bgroup[i]=new JButton()

contentPane.add(bgroup[i])

bgroup[i].addActionListener(new showData(i))//为bgroup注册监听器

}

jf.pack()

jf.setVisible(true)

}

//类showData是事件的监听器,监听到单击事件就会执行actionPerformed方法

class showData implements ActionListener{

int num

public showData(int i){ //将编号传入,以便输出

num = i

}

public void actionPerformed(ActionEvent e){ //方法名称不可改变

String message = "这个按钮的编号是: " + num

JOptionPane.showMessageDialog(jf,message)

//调用message对话框输出,jf为对话框基于哪个JFrame,message为要输出的字符串

}

}

}

public class a {

public static void main(String[] args) {

DrawRect d = new DrawRect()

}

}

用frame.add(button)添加按钮对象到窗体对象,

再用frame.setVisable(true)显示窗口即可

或用

panel.add(button)

frame.add(panel)

frame.setVisable(true)


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

原文地址:https://54852.com/bake/11864651.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存