//我是用内部类的形式解决该问题的。而且直接 *** 作jFrame的组件。
//还可以在新建自定义jDialog类时,传入jFrame的引用。
import java.awt.BorderLayout
import java.awt.GridLayout
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.JTextArea
import javax.swing.JTextField
public class FrameTest extends JFrame {
private JTextArea textArea
public static void main(String[] args) {
new FrameTest()
}
public FrameTest() {
this.setSize(400, 300)
this.setDefaultCloseOperation(EXIT_ON_CLOSE)
initPanel()
this.setVisible(true)
}
private void initPanel() {
JButton button = new JButton("Add")
textArea = new JTextArea()
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openDialog()
}
})
this.add(button, BorderLayout.NORTH)
this.add(textArea, BorderLayout.CENTER)
}
private void openDialog() {
final JDialog dialog = new JDialog(this, true)
dialog.setSize(300, 200)
dialog.setLocation(getX() + 50, getY() + 50)
dialog.setLayout(new GridLayout(3, 2))
final JTextField name = new JTextField(10)
final JTextField phone = new JTextField(10)
JButton save = new JButton("保存")
JButton cancel = new JButton("取消")
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append(name.getText() + ":" + phone.getText() + "\n")
dialog.dispose()
}
})
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose()
}
})
dialog.add(new JLabel("姓名:"))
dialog.add(name)
dialog.add(new JLabel("电话:"))
dialog.add(phone)
dialog.add(save)
dialog.add(cancel)
dialog.setVisible(true)
}
}
JDialog添加单选框, 和 JFrame,JPanel等容器 添加单选框是一样的
步骤:
创建单选按钮.
并把相关的单选按钮都添加到ButtonGroup里,
然后把单选按钮添加到JDialog里
效果图
参考代码
import java.awt.*import java.awt.event.*
import java.util.Enumeration
import javax.swing.*
public class MyTest {// 测试类
public static void main(String[] args) {
JDialog jd = new JDialog()
jd.setTitle("兴趣选择")
jd.setModal(true)
JPanel jp = new JPanel()// 流式布局
JLabel jl = new JLabel("兴趣[单选]")
ButtonGroup bg = new ButtonGroup()
JRadioButton jrb1 = new JRadioButton("跑步")
jrb1.setSelected(true)//默认选择此选项
JRadioButton jrb2 = new JRadioButton("唱歌")
JRadioButton jrb3 = new JRadioButton("跳舞")
bg.add(jrb1)//把单选按钮都加入到ButtonGroup 才能实现单选的效果
bg.add(jrb2)
bg.add(jrb3)
JButton jb = new JButton("确定")
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Enumeration<AbstractButton> btns= bg.getElements()
while(btns.hasMoreElements()){
JRadioButton jr = (JRadioButton) btns.nextElement()
if(jr.isSelected()) {
JOptionPane.showMessageDialog(null, "兴趣是:"+jr.getText())
}
}
}
})
jp.add(jl)
jp.add(jrb1)
jp.add(jrb2)
jp.add(jrb3)
jp.add(jb)
jd.add(jp)
jd.setLayout(new FlowLayout())
jd.setSize(320, 100)// 大小
jd.setLocationRelativeTo(null)// 居中
jd.setVisible(true)
jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)