2013-10-25 2 views
0

У меня есть 2 класса. Один класс предназначен для gui, а другой класс - для некоторых сотрудников. Второй класс включает Swingworker. Он ищет некоторые файлы журналов и принимает оттуда некоторое предложение. Также в gui есть метка, которая записывается в Searching.. Please wait.., а когда второй класс заканчивает работу, ее следует изменить на Searching is finished...Доступ к JLabel от другого класса, Swingworker

Это название этикетки searchLabel и определите в первом классе. Это частная переменная.

Моя цель: во втором классе есть done способ. Внутри этого метода я хочу сделать searchLabel.setText("blabla");

Как это сделать? Я не могу получить доступ. Кроме того, публичное JLabel не является решением, которое я думаю. Вы можете легко найти эту часть в коде с искажающей /* PROBLEM IS IN HERE */ этой строкой.

Вот код

Это мой гуй класс:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UIManager.LookAndFeelInfo; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.SwingConstants; 

public class mainGui extends JFrame { 

private JPanel contentPane; 
private JTextField userNametextField; 
public static JLabel searchLabel,userNameWarningLabel,pathWarningLabel; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    try { 
     for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (Exception e) { 
     // If Nimbus is not available, you can set the GUI to another look and feel. 
    } 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       mainGui frame = new mainGui(); 
       Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
       int w = frame.getSize().width; 
       int h = frame.getSize().height; 
       int x = (dim.width-w)/4; 
       int y = (dim.height-h)/2; 
       frame.setLocation(x, y); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the frame. 
*/ 
public mainGui() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 550, 455); 
    contentPane = new JPanel(); 
    getContentPane().setLayout(null); 
    setTitle("Role Finding Script"); 
    // Border border; 

    JLabel lblUsername = new JLabel(" Username :"); 
    lblUsername.setFont(new Font("LucidaSans", Font.BOLD, 13)); 
    lblUsername.setBounds(10, 53, 113, 30); 
    //Border border = BorderFactory.createRaisedSoftBevelBorder(); 
    // border = BorderFactory.createEtchedBorder(); 
    // lblUsername.setBorder(border); 
    getContentPane().add(lblUsername); 


    userNametextField = new JTextField(); 
    userNametextField.setBounds(146, 53, 250, 30); 
    userNametextField.setFont(new Font("LucidaSans", Font.PLAIN, 13)); 
    getContentPane().add(userNametextField); 
    userNametextField.setColumns(20); 

    JLabel lblRole = new JLabel(" Roles  :"); 
    lblRole.setFont(new Font("LucidaSans", Font.BOLD, 13)); 
    lblRole.setBounds(10, 124, 113, 30); 
    // border = BorderFactory.createEtchedBorder(); 
    // lblRole.setBorder(border); 
    getContentPane().add(lblRole); 

    JComboBox<String> comboBox = new JComboBox<String>(); 
    comboBox.setBounds(146, 124, 250, 30); 
    comboBox.addItem("VR_ANALYST1"); 
    comboBox.addItem("VR_ANALYST2"); 
    comboBox.addItem("VR_ANALYST3"); 
    comboBox.addItem("VR_ANALYST4"); 
    comboBox.addItem("VR_ANALYST5"); 
    comboBox.addItem("VR_ANALYST6"); 
    comboBox.addItem("VR_ANALYST7"); 
    comboBox.addItem("VR_ANALYST8"); 
    comboBox.addItem("VR_ANALYST9"); 
    comboBox.addItem("VR_ANALYST10"); 
    comboBox.addItem("VR_ANALYST11"); 
    comboBox.addItem("VR_ANALYST12"); 
    comboBox.setMaximumRowCount(6); 
    getContentPane().add(comboBox); 


    this.searchLabel = new JLabel("Searching.. Please wait.."); 
    searchLabel.setFont(new Font("LucidaSans", Font.BOLD, 13)); 
    searchLabel.setBounds(169, 325, 195, 30); 
    searchLabel.setVisible(false); 
    getContentPane().add(searchLabel); 

    JButton btnNewButton = new JButton("Show Me "); 
    btnNewButton.setFont(new Font("LucidaSans", Font.BOLD, 13)); 
    btnNewButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      if(userNametextField.getText() == null || userNametextField.getText().equals("")){ 
       userNameWarningLabel.setText("Please filled in the Username part."); 

      }else{ 
       searchLabel.setVisible(true); 
       VolvoMain task = new VolvoMain(); 
       task.execute(); 
      } 


     } 
    }); 
    btnNewButton.setBounds(188, 271, 126, 30); 
    getContentPane().add(btnNewButton); 

    JLabel lblPath = new JLabel(" Path   :"); 
    lblPath.setFont(new Font("Dialog", Font.BOLD, 13)); 
    lblPath.setBounds(10, 195, 113, 30); 
    getContentPane().add(lblPath); 

    userNameWarningLabel = new JLabel(""); 
    userNameWarningLabel.setBounds(156, 89, 227, 14); 
    userNameWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10)); 
    userNameWarningLabel.setForeground(Color.red); 
    getContentPane().add(userNameWarningLabel); 

    JButton btnNewButton_1 = new JButton("..."); 
    btnNewButton_1.setBounds(412, 195, 30, 30); 
    getContentPane().add(btnNewButton_1); 

    JButton btnNewButton_2 = new JButton("+"); 
    btnNewButton_2.setBounds(460, 195, 44, 30); 
    getContentPane().add(btnNewButton_2); 

    JLabel headerLabel = new JLabel("Find the Role"); 
    headerLabel.setFont(new Font("Tahoma", Font.BOLD, 15)); 
    headerLabel.setHorizontalAlignment(SwingConstants.CENTER); 
    headerLabel.setBounds(94, 11, 358, 30); 
    headerLabel.setForeground(Color.red); 
    getContentPane().add(headerLabel); 

    pathWarningLabel = new JLabel(""); 
    pathWarningLabel.setForeground(Color.RED); 
    pathWarningLabel.setFont(new Font("Dialog", Font.ITALIC, 10)); 
    pathWarningLabel.setBounds(156, 236, 227, 14); 
    getContentPane().add(pathWarningLabel); 
} 
} 

И это другой класс:

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.regex.Pattern; 
import javax.swing.SwingWorker; 


public class VolvoMain extends SwingWorker{ 

    private FileInputStream fstream; 
    private BufferedReader br; 
    private String username = "HALAA"; 
    private String role = "VR_ANALYST"; 
    private String firstLine = ""; 
    private Pattern regex; 
    private List<String> stringList = new ArrayList<String>(); 
    private File dir; 
    private mainGui mg = new mainGui(); 

    //String reg = "\\t'AUR +(" + username + ") .*? /ROLE=\"(" + role + ")\".*$"; 


    @SuppressWarnings("unchecked") 
    @Override 
    protected Object doInBackground() throws Exception { 

     String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$"; 
     String reg = String.format(fmt, username, role); 

     regex = Pattern.compile(reg); 


     dir = new File(
       "C:"+File.separator+"Documents and Settings"+File.separator+"sbx1807"+File.separator+"Desktop"+File.separator 
       +"Batu"+File.separator+"Deneme"+File.separator 
       ); 

     File[] dirs = dir.listFiles(); 

     String[] txtArray = new String[dirs.length]; 

     int z=0; 
     for (File file : dirs) { 
      if (file.isDirectory()) { 

      }else { 
       if(file.getAbsolutePath().endsWith(".log")){ 
        txtArray[z] = file.getAbsolutePath(); 
        System.out.println(file.getAbsolutePath()); 
        z++; 
       } 
      } 

      int j = 0; 

      for(int i=0; i<txtArray.length; i++){ 
       if(txtArray[i] != null && !txtArray[i].equals("")){ 
        try{ 
         fstream = new FileInputStream(txtArray[i]); 
         br = new BufferedReader(new InputStreamReader(fstream)); 
         String strLine; 

         while ((strLine = br.readLine()) != null) { 
          /* parse strLine to obtain what you want */ 
          if((j%2)== 0){ 
           firstLine = strLine; 
          } 
          if(((j%2) != 0) && regex.matcher(strLine).matches()){ 
           stringList.add(firstLine); 
           stringList.add(strLine); 
          } 
          publish(stringList.size()); 
          j++; 
         } 
         publish(stringList.size()); 
         br.close(); 
        } catch (Exception e) { 
         System.err.println("Error: " + e.getMessage()); 
        } 
       } 
      } 
      for(int k=0; k<stringList.size(); k++){ 
       System.out.println(stringList.get(k)); 
      } 
     } 
     return null; 
    } 

    @Override 
    public void done() { 
     System.out.println("bitti"); 
    // getSearchJLabel().setText("Searching is done.."); 
    // mainGui m = new mainGui(); 
    // m.searchLabel.setText("done"); 

    } 
} 
+1

1) Для лучшей помощи раньше, отправьте сообщение [SSCCE] (http://sscce.org/). 2) Не устанавливайте размер контейнеров верхнего уровня. Вместо этого разместите контент и вызовите 'pack()'. 3) Java GUI, возможно, придется работать на нескольких платформах, на разных разрешениях экрана и использовании разных PLAF. Таким образом, они не способствуют точному размещению компонентов. Чтобы организовать компоненты для надежного графического интерфейса, вместо этого используйте менеджеров компоновки или [их комбинаций] (http://stackoverflow.com/a/5630271/418556), а также макеты и границы для [пробела] (http: //stackoverflow.com/q/17874717/418556). –

+0

Я вырезал код в некоторых частях –

+0

Примечание. Я не советовал редактировать короткий фрагмент кода, но SSCCE. –

ответ

1

Настройте VolvoMain класс так, чтобы он принимает ссылку до JLabel в его конструкторе. Сохраните это в поле private final, и вы можете использовать его в методе done().

public class VolvoMain extends SwingWorker{ 

    // ... 

    private final JLabel labelToUpdate; 

    public VolvoMain(JLabel labelToUpdate) { 
     this.labelToUpdate = labelToUpdate; 
    } 

    // ... 

    @Override 
    public void done() {   
     // Update labelToUpdate here 
    } 

done() метод будет вызван на событие диспетчерской темы, так что это будет безопасно настроить текст метки непосредственно.

+0

Спасибо за ваш ответ, но я не понимаю, что вы хотите сказать: «Настройте свой класс Volvomain» –

+1

@BatuhanBardak Смотрите правки выше. –

+0

действительно благодарю вас за этот ответ, он работает –

Смежные вопросы