paintComponent 不可见 java

paintComponent not visible java

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

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

}

适合我...

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 来证明您的问题

问题开始于:

bottomPanel.setLayout(null);

Java GUI 必须在不同的 OS'、屏幕尺寸、屏幕分辨率等上工作,在不同的语言环境中使用不同的 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them along with layout padding and borders for white space.

并且在未来,post 一个 MCVE,而不是 300 多行代码以及不相关的添加,例如文件 I/O、表格、行排序器等