java swing自定义对话框_Java Swing - 如何扩展JDialog创建确认对话框

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.Frame;

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JDialog;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JTree;

import javax.swing.border.EmptyBorder;

public class Main {

public static void main(String[] args) {

JFrame f = new JFrame();

final ConfirmDialog dialog = new ConfirmDialog(f);

final JTree tree = new JTree();

tree.setVisibleRowCount(5);

final JScrollPane treeScroll = new JScrollPane(tree);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton b = new JButton("Choose Tree Item");

b.addActionListener(e -> {

int result = dialog.showConfirmDialog(treeScroll, "Choose an item");

if (result == ConfirmDialog.OK_OPTION) {

System.out.println(tree.getSelectionPath());

} else {

System.out.println("User cancelled");

}

});

JPanel p = new JPanel(new BorderLayout());

p.add(b);

p.setBorder(new EmptyBorder(50, 50, 50, 50));

f.setContentPane(p);

f.pack();

f.setLocationByPlatform(true);

f.setVisible(true);

}

}

class ConfirmDialog extends JDialog {

public static final int OK_OPTION = 0;

public static final int CANCEL_OPTION = 1;

private int result = -1;

JPanel content;

public ConfirmDialog(Frame parent) {

super(parent, true);

JPanel gui = new JPanel(new BorderLayout(3, 3));

gui.setBorder(new EmptyBorder(5, 5, 5, 5));

content = new JPanel(new BorderLayout());

gui.add(content, BorderLayout.CENTER);

JPanel buttons = new JPanel(new FlowLayout(4));

gui.add(buttons, BorderLayout.SOUTH);

JButton ok = new JButton("OK");

buttons.add(ok);

ok.addActionListener(e->{

result = OK_OPTION;

setVisible(false);

});

JButton cancel = new JButton("Cancel");

buttons.add(cancel);

cancel.addActionListener(e->{

result = CANCEL_OPTION;

setVisible(false);

});

setContentPane(gui);

}

public int showConfirmDialog(JComponent child, String title) {

setTitle(title);

content.removeAll();

content.add(child, BorderLayout.CENTER);

pack();

setLocationRelativeTo(getParent());

setVisible(true);

return result;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值