简体   繁体   中英

Swing and inheritance

I have two classes one extending another. In both of them i have fields representing swing components. The problem is that something is wrong when i try to use components from child class - it seems Swing thread does not have access to child components. What am i doing wrong?

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();
    }

}

Edit - Code from comment

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();
  } 
}

Edit 2 - Code From OP's Other Comment

  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;
  }

Emm... As I can see you don't init this field as

protected JPanel jContentPane = null;

I guess you should modify the field code as

protected JPanel jContentPane = new JPanel();

...because null is not the "ready to be used" object value :)

I mean this method ...

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

...is seemed to work with null panel so the init is not done correctly.

Good luck :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM