paintComponent不可见java

时间:2017-04-06 01:11:52

标签: java swing jpanel paintcomponent

我想将其添加到另一个JPanel中,但它在那里看不到。我的另一个Jpanel叫做bottomPanel。 paintComponent应该显示在底部面板

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

}

2 个答案:

答案 0 :(得分:3)

问题始于:

bottomPanel.setLayout(null);

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

将来,发布一个MCVE而不是300多行代码,其中包含文件I / O,表格,行分类器等不相关的附加内容。

答案 1 :(得分: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