簡體   English   中英

搖擺與繼承

[英]Swing and inheritance

我有兩個班級,一個班級擴展了另一個班級。 在它們兩個中,我都有代表揮桿組件的字段。 問題是當我嘗試使用子類中的組件時出現了問題-似乎Swing線程無法訪問子組件。 我究竟做錯了什么?

public abstract class AppViewBase {
    protected JPanel jContentPane = null;

    protected void initialize() {
        //...
        addOutputControlls(jContentPane);
        //...
    }
    protected abstract void addOutputControlls(JPanel jContentPane) ;
}

public class Titrai extends AppViewBase  {
    public JTextPane line1 = null;
    public JTextPane line2 = null;

    protected void addOutputControlls(JPanel jContentPane2) {
        jContentPane2.add(getJTextPane());
        jContentPane2.add(getJTextPane2());
    }

    public void setCurrentLine(Object selectedValue) {
        String s = (String) selectedValue;
        getJTextPane().setText(s);
        getJTextPane2().setText("");

        getJTextPane().repaint();
        //only gets repainted i i move line1, line2 fields to parent class
        getJTextPane2().repaint();
    }

}

編輯-注釋中的代碼

if(EventQueue.isDispatchThread()) { 
  initialize(); 
} else { 
  try { 
    EventQueue.invokeAndWait(new Runnable() { 
       @Override 
       public void run() { 
         initialize(); 
       } 
    }); 
  } catch (InterruptedException e) { 
    e.printStackTrace(); 
  } catch (InvocationTargetException e) { 
    e.printStackTrace();
  } 
}

編輯2-OP的其他注釋中的代碼

  JTextPane getJTextPane() {
     if (line1 == null) {
        line1 = new JTextPane();
        line1.setFont(new Font("Tahoma", Font.PLAIN, 13));
        line1.setForeground(Color.white);
        line1.setPreferredSize(new Dimension(385, 16));
        line1.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, false);
        line1.setEditorKit(getDefaultLineEditorKit());
        line1.setEditable(false);
        line1.setLocation(new Point(15, 15));
        line1.setSize(new Dimension(385, 16));
        line1.setBackground(Color.black);
        line1.setFocusable(false);
        line1.setBorder(null);
     }
     return line1;
  }

恩...據我所知,您不會像

protected JPanel jContentPane = null;

我想你應該將域代碼修改為

protected JPanel jContentPane = new JPanel();

...因為null不是“准備使用”的對象值:)

我的意思是這種方法...

protected void initialize() {
        //...
        addOutputControlls(jContentPane);//<-- contain null 
        //...
    }

...似乎與null面板一起使用,因此初始化未正確完成。

祝好運 :)

暫無
暫無

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

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