1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public class JRoundedDialog extends JDialog {
private static final int TITLE_HEIGHT = 24;
private double ray;
public JRoundedDialog() {
setUndecorated(true);
addComponentListener(new ComponentAdapter() { // pour que la forme s'adapte à la taille automatiquement
@Override
public void componentResized(ComponentEvent e) {
ray=getRay(getWidth(),getHeight());
setShape(new RoundRectangle2D.Double(0,0,getWidth(),getHeight(), ray, ray)); // on affecte la taille
getContentPane().setBounds(0, TITLE_HEIGHT, getWidth(), getHeight()-TITLE_HEIGHT);
}
});
getRootPane().setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); // on ajoute un border vide pour laisser de la place pour son dessin (ligne fine de 1px)
}
@Override
public void paint(Graphics g) {
super.paint(g);
// exemple pour dessiner le titre
g.setColor((Color)UIManager.get("activeCaption"));
g.fillRect(0, 0, getWidth(), TITLE_HEIGHT);
Rectangle2D titleBounds = g.getFontMetrics().getStringBounds(getTitle(), g);
double xt = (getWidth()-titleBounds.getWidth())/2.0;
double yt = (TITLE_HEIGHT-titleBounds.getHeight())/2.0+g.getFontMetrics().getAscent();
g.setColor((Color)UIManager.get("activeCaptionText"));
g.drawString(getTitle(), (int)xt, (int)yt);
// dessin d'une bordure (ligne fine de 1 px)
g.setColor((Color)UIManager.get("windowBorder"));
g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, (int)ray, (int)ray);
}
protected double getRay(int width, int height) {
return Math.min(width, height)/10;
}
public static void main(String[] args) {
JRoundedDialog dialog = new JRoundedDialog();
dialog.setTitle("Titre");
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(null);
dialog.getContentPane().add(createDialogContent());
dialog.setVisible(true);
}
private static Component createDialogContent() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(Color.CYAN);
panel.add(new JLabel("TEXTE", JLabel.CENTER));
return panel;
}
} |
Partager