java yes_option返回值_java - JDialog返回值? - 堆栈内存溢出

您可能需要查看如何在对话框文档中使用模态 。 首先,您不需要将JFrame传递给您的类,您可以简单地将其删除。 看看这个例子:

import java.awt.BorderLayout;

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;

import javax.swing.SwingUtilities;

public class Demo {

private void createAndShowGUI() {

JButton button = new JButton("Show dialog");

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

MyOptionPane optionPane = new MyOptionPane();

int option = optionPane.showYesNoMessage("Close frame", "Do you really want to close the frame?");

if(option == MyOptionPane.YES) {

JButton button = (JButton)e.getSource();

SwingUtilities.getWindowAncestor(button).dispose();

}

}

});

JPanel content = new JPanel();

content.add(new JLabel("Test:"));

content.add(button);

JFrame frame = new JFrame("Demo");

frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

frame.getContentPane().add(content);

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

public class MyOptionPane {

public static final int YES = 0;

public static final int NO = -1;

private int choice = NO;

public int showYesNoMessage(String title, String message) {

JLabel label = new JLabel(message);

JButton yesButton = new JButton("Yes");

yesButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

choice = YES;

JButton button = (JButton)e.getSource();

SwingUtilities.getWindowAncestor(button).dispose();

}

});

JButton noButton = new JButton("No");

noButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

choice = NO;

JButton button = (JButton)e.getSource();

SwingUtilities.getWindowAncestor(button).dispose();

}

});

JPanel buttons = new JPanel();

buttons.add(yesButton);

buttons.add(noButton);

JPanel content = new JPanel(new BorderLayout(8, 8));

content.add(label, BorderLayout.CENTER);

content.add(buttons, BorderLayout.SOUTH);

JDialog dialog = new JDialog();

dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

dialog.setModal(true);

dialog.setTitle(title);

dialog.getContentPane().add(content);

dialog.pack();

dialog.setLocationRelativeTo(null);

dialog.setVisible(true);

return choice;

}

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new Demo().createAndShowGUI();

}

});

}

}

无关

关于setBounds()和@AndrewThompson的使用总是说:

Java GUI可能必须在许多平台上工作,在不同的屏幕分辨率和使用不同的PLAF。 因此,它们不利于组件的精确放置。 要组织强大的GUI组件,而是使用布局管理器或它们的组合,以及布局填充和白色空间边框。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值