JButton Daire Şeklinde Kenar Ekleme Ve Transparent (Saydam) Arka Plan Yapma
01-01-2015
JButton nesnesine tıklandığında ve bu butonun üzerine fare ile gelindiğinde farklı arka plan rengi eklemek için aşağıdaki gibi kendi JButton sınımızı oluşturmalıyız:
Not: Eğer dairesel kenar istemiyorsanız 34. ve 36. satırlardaki kodu silip, 37. ve 38. satırdaki kodları kullanabilirsiniz.
Örnek olarak aşağıdaki gibi MyButton nesnesi yaratıp kullanabiliriz:
private class MyButton extends JButton {
private Color hoverBackgroundColor;
private Color pressedBackgroundColor;
public MyButton() {
this(null);
}
public MyButton(String text) {
super(text);
super.setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics g) {
if (getModel().isPressed()) {
g.setColor(pressedBackgroundColor);
} else if (getModel().isRollover()) {
g.setColor(hoverBackgroundColor);
} else {
g.setColor(getBackground());
}
Graphics2D graphics = (Graphics2D) g;
Dimension arcs = new Dimension(5,5); //Border corners arcs {width,height},
int width=getWidth();
int height=getHeight();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Draws the rounded panel with borders.
//paint background
graphics.fillRoundRect(0, 0, width, height, arcs.width, arcs.height);
//paint border
graphics.drawRoundRect(0, 0, width - 1, height - 1, arcs.width, arcs.height);
//graphics.fillRect(0, 0, width, height);
//graphics.drawRect(0, 0, width-1, height-1);
super.paintComponent(g);
}
}
Not: Eğer dairesel kenar istemiyorsanız 34. ve 36. satırlardaki kodu silip, 37. ve 38. satırdaki kodları kullanabilirsiniz.
Örnek olarak aşağıdaki gibi MyButton nesnesi yaratıp kullanabiliriz:
private JButton createIconButton(String toolTip, String imageName) {
ClassLoader loader = getClass().getClassLoader();
URL url = loader.getResource(toolBarImagesLocation + imageName);
MyButton button;
if (url != null) {
ImageIcon icon = new ImageIcon(url);
button = new MyButton();
//Ikon eklendi
button.setIcon(icon);
button.setToolTipText(toolTip);
button.setHoverBackgroundColor(new Color(46, 50, 84, 47));
button.setPressedBackgroundColor(new Color(0, 0, 0, 89));
} else {
button = new MyButton(toolTip);
}
button.setFocusPainted(false);
button.setOpaque(false);
return button;
}