2

I am relatively new to Java and recently I have been working on a GUI based html parser. The interface is simple, consisting of:

  1. JTextField for entering a search term
  2. JButton b1 to initiate the search
  3. JButton b2 to exit
  4. JButton b3 to display an URL in the browser using cmd prmt.

The problem arises with b3. Here is a code sample:

while (mstyle2.find()) 
{
    String s=mstyle2.group(0);
    String pattern = "(?i)(<cite.*?>)(.+?)(</cite>)";
    String updated = s.replaceAll(pattern, "$2"); 
    String pattern2 = "(?i)(<b>)(.+?)(</b>)";
    String updated2 = updated.replaceAll(pattern2, "$2"); 
    String pattern3 = "(http://)";
    boolean c=true;
    String updated32 = updated2.replaceAll(pattern3, ""); 
    String pattern32 = "(https://)";
    final String updated3 = updated32.replaceAll(pattern32,""); 

    try {
        URL url2 = new URL("http://"+updated3);
        URLConnection conne = url2.openConnection();
        conne.connect();
    } catch (MalformedURLException e) {
        c=false;
    } catch (IOException e) {
        c=false;//checks validity of url 
    }

    if(c) {
        Process p=Runtime.getRuntime().exec("cmd /c start http://"+updated3);
    }
}

The idea is that the following command line should only be executed when b3 is pressed. Otherwise the loop will not execute, and remain in that line until the button is pressed.

Process p=Runtime.getRuntime().exec("cmd /c start http://"+updated3);

However, I cannot find any viable way to properly implement the ActionListener method in order to make this possible.

In most of my tries, once b3 is pressed, all link open at once (thus beating the purpose of the b3) and not one by one with every click of b3.

4

1 回答 1

3

解决方案

JButtons 有一个方法叫做addActionListener(). 此方法允许您将可运行对象附加到按钮,因此仅在单击时调用代码。

 b3.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
      {
           // Your code here!
      }
 });

这是在做什么?

好吧,这是向ActionListener您的按钮添加一个新对象。但是,ActionListener有一个抽象方法,actionPeformed需要一个实现。您只是在构造函数中提供代码。

于 2013-04-11T16:51:29.523 回答