F_Schmidt:
私は、グリッドレイアウトマネージャを持つパネルとシンプルなフレームを作成しました。私は上書きpaintComponent(G:グラフィックス)との2つのカスタムボタンを作成するときの方法、その後1つのボタンの背景が間違って描かれています。
私は、これは位置は常にX = 0、Y = 0であることに起因していると思います。私はそれをどのように修正することができますか?
ボタンのコード:
public class JRoundedButton extends JButton {
private int arcRadius;
public JRoundedButton(String label, int arcRadius) {
super(label);
this.setContentAreaFilled(false);
this.arcRadius = arcRadius;
}
@Override
protected void paintComponent(Graphics g) {
if (g instanceof Graphics2D) {
//super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draw button background
graphics.setColor(getBackground());
graphics.fillRoundRect(getX(), getY(), getWidth() - 1, getHeight() - 1, arcRadius, arcRadius);
//Draw font
this.paintText(graphics);
}
}
protected final void paintText(@NotNull Graphics2D g) {
//Draw font
g.setColor(getForeground());
if (this.getFont() != null && this.getText() != null) {
FontMetrics fm = getFontMetrics(getFont());
g.setColor(this.getForeground());
g.drawString(this.getText(), ((this.getWidth() / 2) - (fm.stringWidth(this.getText()) / 2)),
((this.getHeight() / 2) + fm.getMaxDescent()));
}
}
そして、ここでフレームを作成するコードは次のようになります。
public static void main(String[] args) {
JFrame frame = new JFrame("Buttontest");
frame.setSize(new Dimension(500, 500));
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPanel = new JPanel();
contentPanel.setSize(new Dimension(500, 500));
contentPanel.setLayout(new GridLayout(2, 1, 0, 20));
JRoundedButton button1 = new JRoundedButton("Rounded Button", 40);
button1.setForeground(Color.YELLOW);
button1.setBackground(Color.GREEN);
JRoundedButton button2 = new JRoundedButton("Rounded Button 2", 40);
button2.setForeground(Color.WHITE);
button2.setBackground(Color.BLACK);
contentPanel.add(button1);
contentPanel.add(button2);
frame.add(contentPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
私はボタンを実行した場合、上側の一つは予想通り表示されますが、下の一つは、黒の背景は表示されません。何故ですか?
ウナギのホバークラフトのフル:
一目で、私は、これは間違っていることに注意してください。
graphics.fillRoundRect(getX(), getY(), getWidth() - 1, getHeight() - 1, arcRadius, arcRadius);
両方のことを理解getX()
し、getY()
コンポーネントの位置が戻るその親コンポーネントに対して、あなたのボタンが中に座っていることを通常のJPanelが、これは、あなたが描画される場所ではありません。むしろ、図面は、場所にあるべきボタン自体に相対。
これはおそらく、より良い動作しますので。
graphics.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, arcRadius, arcRadius);