代码之家  ›  专栏  ›  技术社区  ›  Gavin Craft

将以前使用的字符串导入新方法

  •  1
  • Gavin Craft  · 技术社区  · 8 年前

    我有一个字符串(在main方法中初始化),我想在新的JFrame窗口方法中使用它。我有以下代码:

    public static void main(String[] args){
    WebElement link = driver.findElement(By.xpath("//*[@id='pagecontainer']/section/ul/li[1]/a"));
    String linkLocation = link.getAttribute("href");
    }
    

    对于我的main方法和JPanel中JButton的以下代码:

    public void actionPerformed(ActionEvent e) 
    {
    desk.browse(new URI(linkLocation));
    }
    

    3 回复  |  直到 8 年前
        1
  •  0
  •   Coder ACJHP    8 年前

    像这样的东西可能会帮助你:

    public String LinkLocation(){
        WebElement link = driver.findElement(By.xpath("//*[@id='pagecontainer']/section/ul/li[1]/a"));
        String linkLocation = link.getAttribute("href");
        return linkLocation;
        }
    
    public void actionPerformed(ActionEvent e) 
    {
    desk.browse(new URI(LinkLocation()));
    }
    
        2
  •  0
  •   Aaron Franke    8 年前

    定义您的 String 外面 main :

    public String linkLocation = " ";
    public static void main(String[] args) {
        WebElement link = driver.findElement(By.xpath("//*[@id='pagecontainer']/section/ul/li[1]/a"));
        linkLocation = link.getAttribute("href");
    }
    

    您现在可以参考 linkLocation 来自其他地方。简单地打字 链接位置 如果您的新方法在同一类中,则应该工作,否则使用 classname.linkLocation .

        3
  •  0
  •   user2575725 user2575725    8 年前

    JButton 在同一个地方,你已经取得 linkLocation 你试试看 JButton.setActionCommand() :

    public static void main(String[] args) {
       // ...
       String linkLocation = link.getAttribute("href");
       jButton.setActionCommand(linkLocation);
       // ..
    }
    

    现在,您可以使用它,根据您的帖子,下面是按钮处理程序:

    public void actionPerformed(ActionEvent e) {
      desk.browse(new URI(e.getActionCommand()));
    }