2017-05-12 29 views
0

最近,我遇见了的paintComponent功能没有在函数调用的问题,我发现,当我使用splitpane功能,将禁用涂料的功能,并给出错误:如何在Java的挥杆分割面板漆

cannot add to layout: unknown constraint: null

我认为这幅画功能可能被添加到正确的方式,下面是我的代码(部分):

类:测试

public class Test extends JFrame{ 

    public Test() throws IOException{ 
     //JFrame jf = new JFrame("my frame"); 
     this.add(new NewPanel(this)); 

     this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     this.setBounds(300,200,1050,600); 
     this.setVisible (true); 

    } 

    public static void main (String[] args) throws IOException{ 

     Test test = new Test(); 
     test.setTitle("Hello"); 
      //frame.pack(); 
    } 
} 

类:NewPanel

public class NewPanel extends JPanel{ 
    public NewPanel(JFrame frame) throws IOException{ 
      JTabbedPane jTabbedpane = new JTabbedPane(); 
      JSplitPane splitPane = new JSplitPane(); 
      JPanel p1    = new JPanel(); 

      p1.setLayout(null); 
      p2.setLayout(new FlowLayout()); 

      splitPane.setOneTouchExpandable(true); 
      splitPane.setContinuousLayout(true); 
      //splitPane.setPreferredSize(new Dimension (250,500)); 
      splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); 
      splitPane.setLeftComponent(p1); 
      splitPane.setRightComponent (p2); 
      splitPane.setDividerSize(3); 
      splitPane.setDividerLocation(250); //balance two panels width 

      jTabbedpane.addTab("ABC",p2); 
      jTabbedpane.addTab("AB",p3); 
      jTabbedpane.addTab("AC",p4); 
      jTabbedpane.addTab("BC",p5); 

      frame.setContentPane(splitPane); 
      frame.add(jTabbedpane); 

      } 
    } 
    public void paintComponent(Graphics g){ 
     super.paint(g); 
     g.setColor(Color.BLUE); 
     g.drawLine(303, 90, 303, 200); 
     g.drawLine(583, 90, 583, 200); 
     g.drawLine(863, 90, 863, 200); 
    } 
} 

当我评论frame.add(jTabbedpane),该行可以在面板上绘制,它只是在一个面板中提供,我无法将其拉入另一个分裂面板,我不不知道为什么..当我取消注释frame.add(jTabbedpane)时,它弹出上面提到的错误。

回答

0

你的UI组件没有意义。你正在调用'setContentPane'到splitpane,它是OK(但不寻常),但是你调用add()到框架,然后尝试添加其他内容到contentPane(JSplitPane)。在将splitPane添加到JPanel之前,您应该将JTabbedPane添加到SplitPane,或者以不同的方式设置您的布局。

//These don't make sense together. 
frame.setContentPane(splitPane); 
frame.add(jTabbedpane); 

关于绘制蓝线的第二个问题比较复杂。 你正在做一堆疯狂的东西 - 你正在创建一个NewPanel并试图将它添加到JFrame,但是之后你将JFrame的contentPane设置为一个不同的组件。您需要通过Swing教程并更好地布置UI。

0

I think the paint function may not be added to the right way,

public void paintComponent(Graphics g){ 
    super.paint(g); 

要覆盖paintComponent(...),那么,为什么你叫super.paint(...)

首先阅读Swing基础知识的Swing Tutorial。本教程中的所有部分都有可以下载和测试的工作示例。

所以,你可能开始:

  1. 如何使用拆分窗格 - 它会告诉你如何分割窗格中添加一帧
  2. 表演风俗画 - 这将解释如何绘画作品和表演如何重写paintComponent(...)方法。