/ / paintComponent non visible java - java, swing, jpanel, paintcomponent

paintComponent java non visible - java, balançoire, jpanel, paintcomponent

Je veux ajouter ceci dans un autre JPanel mais il n’est pas visible là-bas. Mon autre Jpanel s’appelle bottomPanel. Le composant paintComponent est censé s’afficher dans le panneau inférieur.

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

J'ai étendu le 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();
}

}

Réponses:

3 pour la réponse № 1

Le problème commence par:

bottomPanel.setLayout(null);

Les interfaces graphiques Java doivent fonctionner sur différents SE ", écrantaille, résolution de l'écran, etc., en utilisant différents PLAF dans différents lieux. En tant que tels, ils ne sont pas propices à une disposition parfaite des pixels. Utilisez plutôt des gestionnaires de disposition, ou des combinaisons de ceux-ci avec un rembourrage de mise en page et des bordures pour espace blanc.

Et à l'avenir, postez un MCVE plutôt que plus de 300 lignes de code avec des ajouts non pertinents comme des entrées / sorties de fichiers, des tableaux, des trieurs de lignes, etc.


2 pour la réponse № 2

Travaille pour moi...

Preuve de travail

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

}

}

Envisagez de fournir un exemple exécutable ce qui démontre votre problème