如何在GUI按钮上调用void方法?

时间:2014-11-08 21:16:30

标签: java

我真的需要一个如何在我的按钮上调用这个void方法的帮助。关键是该方法必须根据要求无效。我有方法和按钮,我试图调用方法

public static void printIntBinary(int x) {
    if (x <= 0) {
    } else {
        // System.out.println(x % 2)
        printIntBinary(x / 2);
        System.out.println(x % 2);
    }
}

//Portion of my Gui.. runButton actionListner
runButton.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {

        try{
            int mm = Integer.parseInt(binaryTextField.getText());
            //I'm having problem down here.. Because my method printInBinary is void type
            binaryOutPut.append(Recurs.printIntBinary(mm));
        } catch(IllegalArgumentException ex){
            JOptionPane.showMessageDialog(null, "ertyui");
        }

1 个答案:

答案 0 :(得分:0)

如果您被迫保持方法printIntBinary不变(因为它直接打印到控制台,因此很奇怪),那么您可以暂时重定向System.out流以捕获该结果方法:

public void mouseClicked(MouseEvent e) {
    try{
        int mm = Integer.parseInt(binaryTextField.getText());

        // create temporary outputstream and set it to System.out
        final OutputStream originalOS = System.out;
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        final PrintStream ps = new PrintStream(os);
        System.setOut(ps);

        Recurs.printIntBinary(mm);
        binaryOutPut.append(os.toString());

        //reset System.out
        System.setOut(originalOS);
    } catch(IllegalArgumentException ex){
        JOptionPane.showMessageDialog(null, "ertyui");
    }
}

这是该要求的一种肮脏的解决方法。

如果您链接以避免将空格(e.q。\r\n)添加到textarea,请将os.toString()更改为os.toString().replaceAll("\\s", "")

如果您可以更改方法printIntBinary(其返回类型除外),则可以执行以下操作:

public static void printIntBinary(int x, JTextArea binaryOutPut) {
    if (x > 0) {
        printIntBinary(x / 2);
        binaryOutPut.append(String.valueOf(x % 2));
    }
}

如果您喜欢自己的每个号码,请使用binaryOutPut.append(String.valueOf(x % 2) + System.getProperty("line.separator"));

相关问题