/ / paintComponent não está visível java - java, swing, jpanel, paintcomponent

paintComponent não visível java - java, swing, jpanel, paintcomponent

Eu quero adicionar isso em outro JPanel, mas não é visível lá. Meu outro Jpanel é chamado bottomPanel. O paintComponent deve ser exibido no painel inferior.

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

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

}

Respostas:

3 para resposta № 1

O problema começa com:

bottomPanel.setLayout(null);

GUIs Java tem que trabalhar em diferentes SO ", telatamanho, resolução de tela etc. usando diferentes PLAFs em diferentes localidades. Como tal, eles não são propícios ao layout perfeito de pixels. Em vez disso, use gerenciadores de layout ou combinações deles juntamente com preenchimento de layout e fronteiras para espaço em branco.

E, no futuro, poste um MCVE em vez de mais de 300 linhas de código com adições irrelevantes como E / S de arquivos, tabelas, classificadores de linha etc.


2 para resposta № 2

Funciona para mim...

Prova de trabalho

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

}

}

Considere fornecer um exemplo executável o que demonstra seu problema