-
[Java] 자바 스윙 JButton 꾸미기 (둥근 버튼)Study/Java 2020. 11. 21. 00:51반응형
Java Swing을 하다보면 JButton을 사용할 때가 많습니다.
JBtutton을 이용하여 버튼을 만들곤 하는데 자바에서 기본으로 지원하는 버튼의 모양이 맘에 들지 않는다면
아래 클래스를 활용하여 버튼을 개선할 수 있습니다.
//버튼 디자인 public class RoundedButton extends JButton { public RoundedButton() { super(); decorate(); } public RoundedButton(String text) { super(text); decorate(); } public RoundedButton(Action action) { super(action); decorate(); } public RoundedButton(Icon icon) { super(icon); decorate(); } public RoundedButton(String text, Icon icon) { super(text, icon); decorate(); } protected void decorate() { setBorderPainted(false); setOpaque(false); } @Override protected void paintComponent(Graphics g) { Color c=new Color(255,247,242); //배경색 결정 Color o=new Color(247,99,12); //글자색 결정 int width = getWidth(); int height = getHeight(); Graphics2D graphics = (Graphics2D) g; graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (getModel().isArmed()) { graphics.setColor(c.darker()); } else if (getModel().isRollover()) { graphics.setColor(c.brighter()); } else { graphics.setColor(c); } graphics.fillRoundRect(0, 0, width, height, 10, 10); FontMetrics fontMetrics = graphics.getFontMetrics(); Rectangle stringBounds = fontMetrics.getStringBounds(this.getText(), graphics).getBounds(); int textX = (width - stringBounds.width) / 2; int textY = (height - stringBounds.height) / 2 + fontMetrics.getAscent(); graphics.setColor(o); graphics.setFont(getFont()); graphics.drawString(getText(), textX, textY); graphics.dispose(); super.paintComponent(g); } }
저 클래스를 넣으시고
JButton 대신 RoundedButton을 쓰시면 적용됩니다.
반응형'Study > Java' 카테고리의 다른 글
[정보보호개론] Java로 RSA 암호문 해독하기 (RSA 복호화) (0) 2021.04.07 [정보보호개론] Java로 AES 복호화 프로그램 만들기 (0) 2021.04.02 [Java] 클래스 메소드 vs 인스턴스 메소드 (자바 static 관련) (0) 2021.02.23 [Java] main메소드에서 "Cannot make a static reference to the non-static method run() from the type main" 오류 해결법 (0) 2020.12.08 [Java] 자바 스윙 JTextField 꾸미기 (0) 2020.12.08