簡體   English   中英

在另一個類中使用內部類actionListener

[英]Using an inner class actionListener in another class

因此,我使用鏈接列表(要放入隊列中的Job對象)創建了此隊列。 我僅使用這兩個類文件就使該程序能夠工作,但是現在我試圖使其與GUI一起工作。

我希望能夠使用Queue和Job文件從GUI主方法運行程序。 我創建的GUI有8個按鈕和一個JTextArea用於輸出。 我希望能夠通過單擊按鈕來執行每個功能(排隊,顯示隊列等的長度)。

我的查詢在結尾

PS。 最初的main方法被省略以保持其重點。

這是我要進入隊列的Job對象,這里是一般內容...省略了getters / setters:

public class Job 
{

String ID; //(A unique number to identify each print job)
String userID; //(The login of the user that sent the document to print)
String documentName; //(The name of the document being printed)
int fileSize; //(Size of the document being printed in Kb’s)

public Job(String p, String u, String e, int f) 
{ //local variables n,t,e only used in this method
    printID = p;
    userID = u;
    documentName = e;
            fileSize = f;
}

這是帶有構造函數和方法的Queue類。所有這些都可以使用AFAIK。

public class Queue<Item> implements Iterable<Item> 
{
private int N;         // number of elements on queue
private Node first;    // beginning of queue
private Node last;     // end of queue



// helper linked list class
private class Node 
{
    private Item item;
    private Node next;
}

/**
 * Initialises an empty queue.
 */
public Queue() 
{
    first = null;
    last  = null;
    N = 0;
  //  assert check();
}

//is the list empty?
public boolean isEmpty() 
{
    return first == null;
}

//gives number of elements in the queue
public int length() 
{
    return N;     
}


 //looks at first item, if it is empty then return error. If it has something then return
 the   content of the element.
 public Item peek() 
 {
    if (isEmpty()) throw new NoSuchElementException("Nothing in queue");
    return first.item; 
 }

//add an item
 public void enqueue(Item item) 
{
    Node oldlast = last;  //move the current last to a placeholder
    last = new Node();  //create a new node inside of last
    last.item = item; //place the item i passed to the method call to the new last's item area
    last.next = null; //set the end of the queue
    if (isEmpty())   //checks the rest of the queue
        first = last;  //if empty creates a queue of 1 element length
    else           
        oldlast.next = last; //if not empty then previous last will point to this new one
    N++; //increment the number of elements being tracked.

}

 //remove an item
 public Item dequeue() 
 {
    if (isEmpty()) throw new NoSuchElementException("Nothing in queue");
    Item item = first.item;
    first = first.next;
    N--;
    if (isEmpty()) last = null;   // to avoid loitering

    return item;
}

這是我的GUI:

public class GUI {   

  public static void main(String[] args) 
  {        
    Queue s = new Queue();

    JFrame frame = new JFrame("test");
    frame.setVisible(true);
    frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



    JPanel panel = new JPanel(new GridBagLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);

    GridBagConstraints c = new GridBagConstraints();

    JButton button1 = new JButton("Enqueue a print job");
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(10,10,10,10);
    panel.add(button1, c);
    button1.addActionListener(new Enqueue(){});

    JButton button2 = new JButton("Dequeue a print job");
    c.gridx = 0;
    c.gridy = 1;
    panel.add(button2, c);
    button2.addActionListener(new Dequeue(){});

    JButton button3 = new JButton("is the queue empty?");
    c.gridx = 1;
    c.gridy = 0;
    panel.add(button3, c);
    button3.addActionListener(new empty(){});

    JButton button4 = new JButton("Print first in queue");
    c.gridx = 1;
    c.gridy = 1;
    panel.add(button4, c);
    button4.addActionListener(new first(){});

    JButton button5 = new JButton("Length of queue");
    c.gridx = 0;
    c.gridy = 2;
    panel.add(button5, c);
    button5.addActionListener(new length(){});

    JButton button6 = new JButton("Print entire queue");
    c.gridx = 1;
    c.gridy = 2;
    panel.add(button6, c); 
    button6.addActionListener(new printAll() {});

    JTextArea jTextArea = new JTextArea();


    c.gridx = 4;
    c.gridy = 4;
    frame.add( jTextArea, BorderLayout.SOUTH);

這是有問題的內部類(在GUI文件中):我在這里做錯了什么? 我試過嘗試引用's'隊列,但是對於這個單獨的類,該隊列只是不存在於main之外。 這意味着我無法對其執行功能。

 static class length implements ActionListener
 {
 public void actionPerformed (ActionEvent e) 
    { 
         System.out.println("The length of the queue is: " + s.length() +"\n");
    }
 }

當我知道該怎么做時,我將創建更多的actionListeners。

PS。 如果您知道如何從我在GUI文件的main方法中創建的actionListener寫入JTextArea,而不是使用Sys out也會對我有幫助!

這是我第一次使用GUI,因此任何見識都會很棒。 謝謝 :)

您聲明:

PrintQueue s = new PrintQueue();

main()方法內部-這意味着它僅可從main()內部使用(方法范圍)。 如果要在方法之外使用它,則必須將其聲明為類成員,並通過“ get()”方法公開它。

例如:

public class GUI { 

  static PrintQueue s = null;  

  public static void main(String[] args) {        
    s = new PrintQueue();
    ...
  }

  public PrintQueue getS() {return s;}

然后,您將可以使用它:

public void actionPerformed (ActionEvent e) { 
     System.out.println("The length of the queue is: " + s.length() +"\n"); //from the same class
}

或從班級外部使用:

GUI gui = new Gui();
PrintQueue s = gui.getS();

評論
我不確定main()是否是實例化PrintQueue的正確位置-可能是這樣,但是也可能是構造函數會是一個更好的主意。

我認為以下代碼將是添加內部類ActionListener的合法示例。 我是在IDE外部編寫代碼的,經常會出錯,因此您必須在IDE中進行檢查。

在聲明中

   final PrintQueue s = new PrintQueue();

在構造函數中

   button1.addActionListener(new ActionCommand()
   {
      public void actionPerformed (ActionEvent e) 
      { 
          System.out.println("The length of the queue is: " + s.length() +"\n");
      }    

   });

要點:

  • 新的ActionCommand沒有名稱,它是匿名的,

  • 內部類中引用的任何變量都必須是final

  • 匿名內部類是實際類,而不是類的方法,

  • 內部類應具有actionPerformed方法作為其定義的一部分。

如果需要區分幾個不同的JButton,則有兩種常見的編程方式。

(1)向JButton添加“ setActionCommand”方法,並為按鈕提供一個標識字符串。 然后,所有按鈕都可以調用實現ActionListener的單個類的新實例(例如Length類),然后可以從ActionEvent參數e派生出ActionCommand字符串,並將其用於分支到相應按鈕的代碼。

(2)為每個按鈕創建一個單獨的內部類ActionListener,並為該按鈕自定義actionPerformed方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM