如何从另一个类连接方法的ActionListener?

问题描述 投票:0回答:2

我试图从用户完成我的项目关于搜索的图表,其中的功能之一是输入(顶点和边)。

我已经在另一个类此的方法,但现在我需要把它放到GUI。

我已经试过很多教程,但是毫无效果。有人可以帮我,如何把方法getInputFromCommand桂?

我已经尝试过的方法复制到GUI,但由于无效结果类型,我试过只是调用该方法,(我知道..愚蠢)的存在与“返回G”的问题,但它没“T工作的。

package Process;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class FindIslands {



String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();

// constructor
FindIslands(int V) {
    this.V = V;

    adjListArray = new LinkedList[V];

    for (int i = 0; i < V; i++) {
        adjListArray[i] = new LinkedList<Integer>();
    }
}

void addEdge(int src, int dest) {

    adjListArray[src].add(dest);
    adjListArray[dest].add(src);
}

void DFSUtil(int v, boolean[] visited) {
    visited[v] = true;
    message += getValue(v) + " ";
    //   System.out.print(getValue(v) + " ");

    for (int x : adjListArray[v]) {
        if (!visited[x]) {
            DFSUtil(x, visited);
        }
    }

}

void connectedComponents() {

    boolean[] visited = new boolean[V];
    int count = 0;
    message = "";
    for (int v = 0; v < V; ++v) {
        if (!visited[v]) {

            DFSUtil(v, visited);
            message += "\n";
            //     System.out.println();
            count++;
        }
    }

    System.out.println("" + count);
    System.out.println("");
    System.out.println("Vypis ostrovu: ");
    String W[] = message.split("\n");
    Arrays.sort(W, new java.util.Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            // TODO: Argument validation (nullity, length)
            return s1.length() - s2.length();// comparison
        }
    });
    for (String string : W) {
        System.out.println(string);
    }

}

public static void main(String[] args) {


    FindIslands g = null; //
    String csvFile = "nodefile.txt";
    BufferedReader br = null;
    String line = "";
    int emptyLine = 0;
    try {
        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            if (line.equals("")) {
                emptyLine = 1;
                //    System.out.println("found blank line");
            }
            if (emptyLine == 0) {
                // System.out.println(line);
                nodeList.add(line);
            } else if (line.isEmpty()) {
                g = new FindIslands(nodeList.size());
            } else {
                String[] temp = line.split(",");
                g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("Soubor nenalezen, zadejte data v danem formatu");
        g = getInputFromCommand();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Pocet ostrovu");
    if (g != null) {
        g.connectedComponents();


    }
}


public static int getIndex(String str) {
    return nodeList.indexOf(str);
}

public static String getValue(int index) {
    return nodeList.get(index);
}

public static FindIslands getInputFromCommand() {


    FindIslands g = null;
    BufferedReader br = null;
    String line = "";
    int emptyLine = 0;
    Scanner scanner = new Scanner(System.in);


    line = scanner.nextLine();
    while (!line.equals("")) {
        if (line.equals("--gui")) {
            Guicko gui = new Guicko();
            gui.setVisible(true);
        } else
            nodeList.add(line);
            line = scanner.nextLine();
        }
        g = new FindIslands(nodeList.size());
        line = scanner.nextLine();
        while (!line.equals("")) {
            String[] temp = line.split(",");
            if (temp.length != 2) {
                System.out.println("spatny format zadanych dat, prosim zkuste znovu");
            } else {
                g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
            }

            line = scanner.nextLine();
        }
        return g;
    }

}

其中重要的是最后的方法“getInputFromCommand()”

和... GUI

package Process;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;

public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;


public Guicko() {
    add(panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setTitle("Zadej hodnoty");

    setSize(500, 400);

    textField2.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            FindIslands.getInputFromCommand();
        }
    });

    štartButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String str = "asd";
            FindIslands g = null;
            g.connectedComponents();
            textArea1.setText(str);
        }
    });



}



public static void main (String args[]){
    Guicko gui = new Guicko();
    gui.setVisible(true);
}

}

java
2个回答
0
投票

我敢肯定有很多方法这段代码可以是固定的,但恕我直言,你Guicko类需要有一个FindIslands类的成员,我认为你需要从FindIslands.main()将一些东西到Guicko.main()或其他方法。

然后你的“行动监听器”内部类的actionPerformed方法只是委托给在FindIslands成员实例的方法,这样

....
private FindIslands fi;

public Guicko() {
    ....
    textField2.addActionListener(new ActionListener() { 
        @Override
        public void actionPerformed(ActionEvent e) {
            fi = FindIslands.getInputFromCommand();
        }
    });

    startButton.addActionListener(new ActionListener() { 
        @Override
        public void actionPerformed(ActionEvent e) {
            String comps = fi.connectedComponents();// method needs to return a string
            textArea1.setText(comps);
        }
    });
}

0
投票

GUI分隔条件domain的整体思路是很容易做出改变。 GUIdomain的知识,但domain没有关于GUI知识。我们可以用一个接口来它们分开,在这种情况下,Domain说,我不在乎谁实现了这个接口,但是谁实现了这个接口会得到响应,并能和我一起工作。

所以,如果我们创建一个新的GUI,我们可以让它实现该接口和相同domain将与GUI工作。

有很多的错误,但是为了让它工作,向您展示一个例子,我做了一些改动。

public class Guicko extends JFrame implements PropertyChangeListener{
   private JButton štartButton;
   private JPanel panel;
   private JTextField textField2;
   private JTextArea textArea1;
   private FindIslands land;

   private JTextField textField;
   private JButton button;



public Guicko() {
    JPanel panel = new JPanel();
    super.getContentPane().setLayout(new GridLayout());

    //For each gui, there should be one land.
    this.setLand(new FindIslands(100));


    //Subscribe to the domain so that you can get update if something change in domain.
    this.getLand().subscribe(this);


    //Dummy buttons are fields(need too initiate first)
    textField2 = new JTextField("",30);
    štartButton = new JButton();
    textField = new JTextField("",30);
    button = new JButton();
    button.setPreferredSize(new Dimension(100, 40));
    button.setText("Get input from Domain");
    štartButton.setPreferredSize(new Dimension(100, 40));
    textField.setEditable(false);
    štartButton.setText("Start");
    panel.add(textField2);
    panel.add(štartButton);
    panel.add(textField);
    panel.add(button);



    add(panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setTitle("Zadej hodnoty");

    setSize(500, 400);

    //When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
    this.addListerToField(štartButton,this.getLand(),textField2);


    //Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
    this.addListerToSecondField(button,this.getLand(),textField);

}



//Here i can catch the events from the domain.
@Override
public void propertyChange(PropertyChangeEvent e) {
    if(e.getPropertyName().equals("String changed")) {
        this.getTextField().setText((String) e.getNewValue());
    }
}





private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            land.requireArgumentsForField();
        }

    });
}





private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
    štartButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                land.getInputFromCommand(field.getText());
            }
        });
}



public static void main (String args[]){
    Guicko gui = new Guicko();
    gui.setVisible(true);
 }



public FindIslands getLand() {
    return land;
}



public void setLand(FindIslands land) {
    this.land = land;
}






public JTextField getTextField() {
    return textField;
}





public void setTextField(JTextField textField) {
    this.textField = textField;
}





public JButton getButton() {
    return button;
}





public void setButton(JButton button) {
    this.button = button;
}

这是第二类。运行它,并试图让摸着它,它是如何工作的。

 public class FindIslands {




String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();

// constructor
FindIslands(int V) {
    this.V = V;
    //initialize the list
    this.setListeners(new ArrayList<>());

    adjListArray = new LinkedList[V];

    for (int i = 0; i < V; i++) {
        adjListArray[i] = new LinkedList<Integer>();
    }
}

void addEdge(int src, int dest) {

    adjListArray[src].add(dest);
    adjListArray[dest].add(src);
}

void DFSUtil(int v, boolean[] visited) {
    visited[v] = true;
    message += getValue(v) + " ";
    //   System.out.print(getValue(v) + " ");

    for (int x : adjListArray[v]) {
        if (!visited[x]) {
            DFSUtil(x, visited);
        }
    }

}

void connectedComponents() {

    boolean[] visited = new boolean[V];
    int count = 0;
    message = "";
    for (int v = 0; v < V; ++v) {
        if (!visited[v]) {

            DFSUtil(v, visited);
            message += "\n";
            //     System.out.println();
            count++;
        }
    }

    System.out.println("" + count);
    System.out.println("");
    System.out.println("Vypis ostrovu: ");
    String W[] = message.split("\n");
    Arrays.sort(W, new java.util.Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            // TODO: Argument validation (nullity, length)
            return s1.length() - s2.length();// comparison
        }
    });
    for (String string : W) {
        System.out.println(string);
    }

}

//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {

    FindIslands g = null; //
    String csvFile = "nodefile.txt";
    BufferedReader br = null;
    String line = "";
    int emptyLine = 0;
    try {
        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            if (line.equals("")) {
                emptyLine = 1;
                //    System.out.println("found blank line");
            }
            if (emptyLine == 0) {
                // System.out.println(line);
                nodeList.add(line);
            } else if (line.isEmpty()) {
                g = new FindIslands(nodeList.size());
            } else {
                String[] temp = line.split(",");
                g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("Soubor nenalezen, zadejte data v danem formatu");
        g = getInputFromCommand();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Pocet ostrovu");
    if (g != null) {
        g.connectedComponents();


    }
}
**/

public static int getIndex(String str) {
    return nodeList.indexOf(str);
}

public static String getValue(int index) {
    return nodeList.get(index);
}


//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {

    //Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
    System.out.println("Recieve string is " + string);



    //No idea what you are trying to do.
   /** FindIslands g = null;
    BufferedReader br = null;
    String line = "";
    int emptyLine = 0;
    Scanner scanner = new Scanner(System.in);

    line = scanner.nextLine();
    while (!line.equals("")) {
        if (line.equals("--gui")) {
            Guicko gui = new Guicko();
            gui.setVisible(true);
        } else
            nodeList.add(line);
            line = scanner.nextLine();
        }
        g = new FindIslands(nodeList.size());
        line = scanner.nextLine();
        while (!line.equals("")) {
            String[] temp = line.split(",");
            if (temp.length != 2) {
                System.out.println("spatny format zadanych dat, prosim zkuste znovu");
            } else {
                g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
            }

            line = scanner.nextLine();
        }
        return line;**/
    }

//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
    //Suppose i want to send following string.
    String name = "I don't know";
    this.getListeners().stream().forEach(e -> {
        //  I will catch this in view.
        e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
    });
}

private ArrayList<PropertyChangeListener> listeners;


//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
    this.getListeners().add(listener);
}



public ArrayList<PropertyChangeListener> getListeners() {
    return listeners;
}

public void setListeners(ArrayList<PropertyChangeListener> listeners) {
    this.listeners = listeners;
}
© www.soinside.com 2019 - 2024. All rights reserved.