2017-04-06 119 views
1

我想将其添加到另一个JPanel中,但它在那里不可见。我的其他Jpanel被称为bottomPanel。 paintComponent应该显示在底部面板paintComponent不可见java

bottomPanel.setLayout(null); 
TestPane tp = new TestPane(); 
bottomPanel.add(tp); 

我已经扩展了Jpanel。

public class TestPane extends JPanel { 
    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(200, 200); 
    } 


    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D) g.create(); 
     int width = getWidth() - 100; 
     int height = getHeight() - 100; 
     int x = (getWidth() - width)/2; 
     int y = (getHeight() - height)/2; 
     g2d.setColor(Color.RED); 
     g2d.drawRect(x, y, width, height); 
     g2d.dispose(); 
    } 

} 
+1

你是如何加入面板父容器?这是如何获得在屏幕上显示? – MadProgrammer

+0

bottomPanel是我希望显示的另一个面板。不是bottomPanel.add(new TestPane());够了吗?抱歉,我是新来的java – hello12345678

+1

我们不需要屏幕截图,我们需要重现您的问题的代码。 –

回答

3

的问题开始:

bottomPanel.setLayout(null); 

Java GUI必须使用不同语言环境中使用不同PLAF的不同OS,屏幕大小,屏幕分辨率等。因此,它们不利于像素的完美布局。请使用布局管理器,或combinations of them以及white space的布局填充和边框。

而在未来,张贴MCVE而不是300行代码与无关的补充,如文件I/O,表,行分拣机等

2

对我的作品......

Working Evidence

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class Test { 

    public static void main(String[] args) { 
     new Test(); 
    } 

    public Test() { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       JFrame frame = new JFrame(); 
       JPanel outer = new JPanel(new BorderLayout()); 
       outer.add(new TestPane()); 
       frame.add(outer); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel { 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      int width = getWidth() - 100; 
      int height = getHeight() - 100; 
      int x = (getWidth() - width)/2; 
      int y = (getHeight() - height)/2; 
      g2d.setColor(Color.RED); 
      g2d.drawRect(x, y, width, height); 
      g2d.dispose(); 
     } 

    } 

} 

考虑提供runnable example这表明你的问题

+0

它的工作,但它不显示在jPanel – hello12345678

+0

@ hello12345678它适合我工作正常,告诉我它不工作 - 它甚至嵌入在另一个面板内,它仍然工作 – MadProgrammer

+0

嘿我在问题描述中添加了图片 – hello12345678