歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java 重新繪制JButton

使用paintComponent()方法繪制的各種Button:

正常狀態:

獲得焦點狀態:

被按下狀態:

被釋放狀態:

實現代碼:

  1. package com.han;
  2. import java.awt.Color;
  3. import java.awt.Container;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.Font;
  7. import java.awt.Graphics;
  8. import java.awt.Graphics2D;
  9. import java.awt.Image;
  10. import java.awt.RadialGradientPaint;
  11. import java.awt.RenderingHints;
  12. import java.awt.Toolkit;
  13. import java.awt.event.MouseAdapter;
  14. import java.awt.event.MouseEvent;
  15. import java.awt.font.LineMetrics;
  16. import java.awt.geom.Ellipse2D;
  17. import java.awt.geom.Point2D;
  18. import java.awt.geom.Rectangle2D;
  19. import java.awt.geom.RoundRectangle2D;
  20. import java.awt.image.BufferedImage;
  21. import java.io.IOException;
  22. import javax.imageio.ImageIO;
  23. import javax.swing.JButton;
  24. import javax.swing.JFrame;
  25. import javax.swing.UIManager;
  26. import javax.swing.UIManager.LookAndFeelInfo;
  27. import javax.swing.UnsupportedLookAndFeelException;
  28. @SuppressWarnings("serial")
  29. publicclass JButton_Bg extends JFrame {
  30. public JButton_Bg() {
  31. for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
  32. if (laf.getName().equals("Nimbus")) {
  33. try {
  34. UIManager.setLookAndFeel(laf.getClassName());
  35. } catch (ClassNotFoundException | InstantiationException
  36. | IllegalAccessException
  37. | UnsupportedLookAndFeelException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. // TODO Auto-generated constructor stub
  44. Container c = getContentPane();
  45. c.setLayout(new FlowLayout());
  46. final JButton button = new MyButton("button 2");
  47. c.add(button);
  48. JButton button2 = new JButton("button 2");
  49. c.add(button2);
  50. button2.setBackground(Color.blue);
  51. JButton button3 = new MyButton2("Cancel");
  52. c.add(button3);
  53. // 完全重繪的Button,其Text的HTML設置特性消失
  54. // JButton button4 = new
  55. // MyButton3("<html><font size=12>Sub</font></html>");
  56. JButton button4 = new MyButton3("Sub");
  57. // button4.setFont(new Font("Serif", Font.PLAIN, 14));
  58. c.add(button4);
  59. }
  60. privateclass MyButton extends JButton {
  61. private String text;
  62. private String state = "normal";
  63. // private String state = "focused";
  64. // private String state = "pressed";
  65. // private String state = "released";
  66. // 無參構造繼承時自動調用,而有參構造繼承時則需手動重寫
  67. MyButton(String text) {
  68. // super("<html><font size=5>" + text + "</font></html>");
  69. super(text);
  70. this.text = text;
  71. // 下 面的代碼塊若是放到下面的paintComponent()方法裡則Swing界面初始化時,
  72. // 布局管理器還是采用的是系統默認的PreferredSize。因為構造函數要優先於
  73. // paintComponent()方法執行。
  74. Dimension preferredSize = getPreferredSize();
  75. Dimension preferredSizeNew = new Dimension(preferredSize.width,
  76. preferredSize.width);
  77. setPreferredSize(preferredSizeNew);
  78. }
  79. @Override
  80. protectedvoid paintComponent(Graphics g) {
  81. Graphics2D g2 = (Graphics2D) g;
  82. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  83. RenderingHints.VALUE_ANTIALIAS_ON);
  84. int width = this.getPreferredSize().width;
  85. int height = this.getPreferredSize().height;
  86. // BufferedImage img;
  87. // try {
  88. // img = ImageIO.read(this.getClass().getResource(
  89. // "/images/icon.jpg"));
  90. // g2.drawImage(img, 0, 0, width, height, this);
  91. // } catch (IOException e1) {
  92. // // TODO Auto-generated catch block
  93. // e1.printStackTrace();
  94. // }
  95. if (state.equals("normal")) {
  96. // draw background pattern
  97. Point2D center = new Point2D.Float(width / 2, height / 2);
  98. float radius = height / 2;
  99. float[] dist = { 0.0f, 1.0f };
  100. Color[] colors = { new Color(0, 0, 0, 255),
  101. new Color(255, 255, 255, 0) };
  102. RadialGradientPaint paint = new RadialGradientPaint(center,
  103. radius, dist, colors);
  104. g2.setPaint(paint);
  105. g2.fill(new Ellipse2D.Double(width / 2 - height / 2, 0, height,
  106. height));
  107. // draw string text
  108. g2.setColor(Color.RED);
  109. Font defaultFont = getFont();
  110. g2.setFont(defaultFont);
  111. Rectangle2D rect = defaultFont.getStringBounds(text,
  112. g2.getFontRenderContext());
  113. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  114. g2.getFontRenderContext());
  115. g2.drawString(
  116. text,
  117. (float) (width / 2 - rect.getWidth() / 2),
  118. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  119. .getDescent()) / 2 - lineMetrics.getDescent())));
  120. } elseif (state.equals("focused")) {
  121. // draw background pattern
  122. Point2D center = new Point2D.Float(width / 2, height / 2);
  123. float radius = height / 2;
  124. float[] dist = { 0.2f, 1.0f };
  125. Color[] colors = { new Color(0, 0, 0, 255),
  126. new Color(255, 255, 255, 0) };
  127. RadialGradientPaint paint = new RadialGradientPaint(center,
  128. radius, dist, colors);
  129. g2.setPaint(paint);
  130. g2.fill(new Ellipse2D.Double(width / 2 - height / 2, 0, height,
  131. height));
  132. // draw string text
  133. g2.setColor(Color.RED);
  134. Font defaultFont = getFont();
  135. g2.setFont(defaultFont);
  136. Rectangle2D rect = defaultFont.getStringBounds(text,
  137. g2.getFontRenderContext());
  138. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  139. g2.getFontRenderContext());
  140. g2.drawString(
  141. text,
  142. (float) (width / 2 - rect.getWidth() / 2),
  143. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  144. .getDescent()) / 2 - lineMetrics.getDescent())));
  145. } elseif (state.equals("pressed")) {
  146. // draw background pattern
  147. int offsetCenter = 1;
  148. Point2D center = new Point2D.Float(width / 2 + offsetCenter,
  149. height / 2 + offsetCenter);
  150. float radius = height / 2;
  151. float[] dist = { 0.2f, 1.0f };
  152. Color[] colors = { new Color(0, 0, 0, 255),
  153. new Color(255, 255, 255, 0) };
  154. RadialGradientPaint paint = new RadialGradientPaint(center,
  155. radius, dist, colors);
  156. g2.setPaint(paint);
  157. g2.fill(new Ellipse2D.Double(width / 2 - height / 2
  158. + offsetCenter, offsetCenter, height, height));
  159. // draw string text
  160. g2.setColor(Color.RED);
  161. Font defaultFont = getFont();
  162. g2.setFont(defaultFont);
  163. Rectangle2D rect = defaultFont.getStringBounds(text,
  164. g2.getFontRenderContext());
  165. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  166. g2.getFontRenderContext());
  167. g2.drawString(
  168. text,
  169. (float) (width / 2 - rect.getWidth() / 2)
  170. + offsetCenter,
  171. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  172. .getDescent()) / 2 - lineMetrics.getDescent()))
  173. + offsetCenter);
  174. } elseif (state.equals("released")) {
  175. // draw background pattern
  176. Point2D center = new Point2D.Float(width / 2, height / 2);
  177. float radius = height / 2;
  178. float[] dist = { 0.2f, 1.0f };
  179. Color[] colors = { new Color(0, 0, 0, 255),
  180. new Color(255, 255, 255, 0) };
  181. RadialGradientPaint paint = new RadialGradientPaint(center,
  182. radius, dist, colors);
  183. g2.setPaint(paint);
  184. g2.fill(new Ellipse2D.Double(width / 2 - height / 2, 0, height,
  185. height));
  186. // draw string text
  187. g2.setColor(Color.RED);
  188. Font defaultFont = getFont();
  189. g2.setFont(defaultFont);
  190. Rectangle2D rect = defaultFont.getStringBounds(text,
  191. g2.getFontRenderContext());
  192. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  193. g2.getFontRenderContext());
  194. g2.drawString(
  195. text,
  196. (float) (width / 2 - rect.getWidth() / 2),
  197. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  198. .getDescent()) / 2 - lineMetrics.getDescent())));
  199. }
  200. addMouseListener(new MouseAdapter() {
  201. @Override
  202. publicvoid mouseEntered(MouseEvent e) {
  203. // TODO Auto-generated method stub
  204. System.out.println("光標移入組件");
  205. state = "focused";
  206. repaint();
  207. }
  208. @Override
  209. publicvoid mouseExited(MouseEvent e) {
  210. // TODO Auto-generated method stub
  211. System.out.println("光標移出組件");
  212. state = "normal";
  213. repaint();
  214. }
  215. @Override
  216. publicvoid mousePressed(MouseEvent e) {
  217. // TODO Auto-generated method stub
  218. System.out.print("鼠標按鍵被按下,");
  219. state = "pressed";
  220. repaint();
  221. }
  222. @Override
  223. publicvoid mouseReleased(MouseEvent e) {
  224. // TODO Auto-generated method stub
  225. System.out.print("鼠標按鍵被釋放,");
  226. state = "released";
  227. repaint();
  228. }
  229. });
  230. }
  231. }
  232. privateclass MyButton2 extends JButton {
  233. private String text;
  234. private String state = "normal";
  235. // private String state = "focused";
  236. // private String state = "pressed";
  237. // private String state = "released";
  238. // Initialize the size of the button according to the length and width
  239. // of the text string
  240. MyButton2(String text) {
  241. super(text);
  242. this.text = text;
  243. }
  244. @Override
  245. protectedvoid paintComponent(Graphics g) {
  246. Graphics2D g2 = (Graphics2D) g;
  247. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  248. RenderingHints.VALUE_ANTIALIAS_ON);
  249. int width = this.getWidth();
  250. int height = this.getHeight();
  251. if (state.equals("normal")) {
  252. // draw background pattern
  253. Point2D center = new Point2D.Float(width / 2, height / 2);
  254. float radius = width / 2;
  255. float[] dist = { 0.0f, 0.8f };
  256. Color[] colors = { new Color(255, 255, 255, 0),
  257. new Color(0, 0, 0, 255) };
  258. RadialGradientPaint paint = new RadialGradientPaint(center,
  259. radius, dist, colors);
  260. g2.setPaint(paint);
  261. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  262. height, height));
  263. // draw string text
  264. Font defaultFont = getFont();
  265. g2.setFont(defaultFont);
  266. g2.setColor(Color.BLACK);
  267. Rectangle2D rect = defaultFont.getStringBounds(text,
  268. g2.getFontRenderContext());
  269. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  270. g2.getFontRenderContext());
  271. g2.drawString(
  272. text,
  273. (float) (width / 2 - rect.getWidth() / 2),
  274. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  275. .getDescent()) / 2 - lineMetrics.getDescent())));
  276. } elseif (state.equals("focused")) {
  277. // draw background pattern
  278. Point2D center = new Point2D.Float(width / 2, height / 2);
  279. float radius = width / 2;
  280. float[] dist = { 0.0f, 0.8f };
  281. Color[] colors = { new Color(255, 255, 255, 0),
  282. new Color(20, 20, 20, 255) };
  283. RadialGradientPaint paint = new RadialGradientPaint(center,
  284. radius, dist, colors);
  285. g2.setPaint(paint);
  286. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  287. height, height));
  288. // draw string text
  289. Font defaultFont = getFont();
  290. g2.setFont(defaultFont);
  291. g2.setColor(Color.BLACK);
  292. Rectangle2D rect = defaultFont.getStringBounds(text,
  293. g2.getFontRenderContext());
  294. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  295. g2.getFontRenderContext());
  296. g2.drawString(
  297. text,
  298. (float) (width / 2 - rect.getWidth() / 2),
  299. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  300. .getDescent()) / 2 - lineMetrics.getDescent())));
  301. } elseif (state.equals("pressed")) {
  302. Point2D center = new Point2D.Float(width / 2, height / 2);
  303. float radius = width / 2;
  304. float[] dist = { 0.0f, 1.0f };
  305. Color[] colors = { new Color(255, 255, 255, 0),
  306. new Color(20, 20, 20, 255) };
  307. RadialGradientPaint paint = new RadialGradientPaint(center,
  308. radius, dist, colors);
  309. g2.setPaint(paint);
  310. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  311. height, height));
  312. // draw string text
  313. Font defaultFont = getFont();
  314. g2.setFont(defaultFont);
  315. g2.setColor(Color.BLACK);
  316. Rectangle2D rect = defaultFont.getStringBounds(text,
  317. g2.getFontRenderContext());
  318. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  319. g2.getFontRenderContext());
  320. g2.drawString(
  321. text,
  322. (float) (width / 2 - rect.getWidth() / 2),
  323. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  324. .getDescent()) / 2 - lineMetrics.getDescent())));
  325. } elseif (state.equals("released")) {
  326. Point2D center = new Point2D.Float(width / 2, height / 2);
  327. float radius = width / 2;
  328. float[] dist = { 0.0f, 0.8f };
  329. Color[] colors = { new Color(255, 255, 255, 0),
  330. new Color(20, 20, 20, 255) };
  331. RadialGradientPaint paint = new RadialGradientPaint(center,
  332. radius, dist, colors);
  333. g2.setPaint(paint);
  334. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  335. height, height));
  336. // draw string text
  337. Font defaultFont = getFont();
  338. g2.setFont(defaultFont);
  339. g2.setColor(Color.BLACK);
  340. Rectangle2D rect = defaultFont.getStringBounds(text,
  341. g2.getFontRenderContext());
  342. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  343. g2.getFontRenderContext());
  344. g2.drawString(
  345. text,
  346. (float) (width / 2 - rect.getWidth() / 2),
  347. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  348. .getDescent()) / 2 - lineMetrics.getDescent())));
  349. }
  350. addMouseListener(new MouseAdapter() {
  351. @Override
  352. publicvoid mouseEntered(MouseEvent e) {
  353. // TODO Auto-generated method stub
  354. System.out.println("光標移入組件");
  355. state = "focused";
  356. repaint();
  357. }
  358. @Override
  359. publicvoid mouseExited(MouseEvent e) {
  360. // TODO Auto-generated method stub
  361. System.out.println("光標移出組件");
  362. state = "normal";
  363. repaint();
  364. }
  365. @Override
  366. publicvoid mousePressed(MouseEvent e) {
  367. // TODO Auto-generated method stub
  368. System.out.print("鼠標按鍵被按下,");
  369. state = "pressed";
  370. repaint();
  371. }
  372. @Override
  373. publicvoid mouseReleased(MouseEvent e) {
  374. // TODO Auto-generated method stub
  375. System.out.print("鼠標按鍵被釋放,");
  376. state = "released";
  377. repaint();
  378. }
  379. });
  380. }
  381. }
  382. privateclass MyButton3 extends JButton {
  383. private String text;
  384. private String state = "normal";
  385. // private String state = "focused";
  386. // private String state = "pressed";
  387. // private String state = "released";
  388. // Initialize the size of the button according to the length and width
  389. // of the text string
  390. MyButton3(String text) {
  391. super(text);
  392. this.text = text;
  393. }
  394. @Override
  395. protectedvoid paintComponent(Graphics g) {
  396. Graphics2D g2 = (Graphics2D) g;
  397. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  398. RenderingHints.VALUE_ANTIALIAS_ON);
  399. int width = this.getWidth();
  400. int height = this.getHeight();
  401. if (state.equals("normal")) {
  402. Point2D center = new Point2D.Float(width / 2, height / 2);
  403. float radius = width / 2;
  404. float[] dist = { 0.0f, 0.8f };
  405. Color[] colors = { new Color(255, 255, 255, 0),
  406. new Color(0, 0, 0, 255) };
  407. RadialGradientPaint paint = new RadialGradientPaint(center,
  408. radius, dist, colors);
  409. g2.setPaint(paint);
  410. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  411. height, height));
  412. // draw string text
  413. Font defaultFont = getFont();
  414. g2.setFont(defaultFont);
  415. g2.setColor(Color.BLACK);
  416. Rectangle2D rect = defaultFont.getStringBounds(text,
  417. g2.getFontRenderContext());
  418. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  419. g2.getFontRenderContext());
  420. g2.drawString(
  421. text,
  422. (float) (width / 2 - rect.getWidth() / 2),
  423. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  424. .getDescent()) / 2 - lineMetrics.getDescent())));
  425. } elseif (state.equals("focused")) {
  426. Point2D center = new Point2D.Float(width / 2, height / 2);
  427. float radius = width / 2;
  428. float[] dist = { 0.0f, 0.8f };
  429. Color[] colors = { new Color(255, 255, 255, 0),
  430. new Color(20, 20, 20, 255) };
  431. RadialGradientPaint paint = new RadialGradientPaint(center,
  432. radius, dist, colors);
  433. g2.setPaint(paint);
  434. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  435. height, height));
  436. // draw string text
  437. Font defaultFont = getFont();
  438. g2.setFont(defaultFont);
  439. g2.setColor(Color.BLACK);
  440. Rectangle2D rect = defaultFont.getStringBounds(text,
  441. g2.getFontRenderContext());
  442. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  443. g2.getFontRenderContext());
  444. g2.drawString(
  445. text,
  446. (float) (width / 2 - rect.getWidth() / 2),
  447. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  448. .getDescent()) / 2 - lineMetrics.getDescent())));
  449. } elseif (state.equals("pressed")) {
  450. g2.setColor(new Color(0, 147, 255));
  451. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  452. height, height));
  453. Point2D center = new Point2D.Float(width / 2, height / 2);
  454. float radius = width / 2;
  455. float[] dist = { 0.0f, 1.0f };
  456. Color[] colors = { new Color(255, 255, 255, 0),
  457. new Color(20, 20, 20, 255) };
  458. RadialGradientPaint paint = new RadialGradientPaint(center,
  459. radius, dist, colors);
  460. g2.setPaint(paint);
  461. double borderWidth = 2.0f; // 2 pixels
  462. g2.fill(new RoundRectangle2D.Double(borderWidth, borderWidth,
  463. width - borderWidth * 2.0f,
  464. height - borderWidth * 2.0f, height - borderWidth
  465. * 2.0f, height - borderWidth * 2.0f));
  466. // draw string text
  467. Font defaultFont = getFont();
  468. g2.setFont(defaultFont);
  469. g2.setColor(Color.BLACK);
  470. Rectangle2D rect = defaultFont.getStringBounds(text,
  471. g2.getFontRenderContext());
  472. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  473. g2.getFontRenderContext());
  474. g2.drawString(
  475. text,
  476. (float) (width / 2 - rect.getWidth() / 2),
  477. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  478. .getDescent()) / 2 - lineMetrics.getDescent())));
  479. } elseif (state.equals("released")) {
  480. Point2D center = new Point2D.Float(width / 2, height / 2);
  481. float radius = width / 2;
  482. float[] dist = { 0.0f, 0.8f };
  483. Color[] colors = { new Color(255, 255, 255, 0),
  484. new Color(20, 20, 20, 255) };
  485. RadialGradientPaint paint = new RadialGradientPaint(center,
  486. radius, dist, colors);
  487. g2.setPaint(paint);
  488. g2.fill(new RoundRectangle2D.Double(0, 0, width, height,
  489. height, height));
  490. // draw string text
  491. Font defaultFont = getFont();
  492. g2.setFont(defaultFont);
  493. g2.setColor(Color.BLACK);
  494. Rectangle2D rect = defaultFont.getStringBounds(text,
  495. g2.getFontRenderContext());
  496. LineMetrics lineMetrics = defaultFont.getLineMetrics(text,
  497. g2.getFontRenderContext());
  498. g2.drawString(
  499. text,
  500. (float) (width / 2 - rect.getWidth() / 2),
  501. (float) ((height / 2) + ((lineMetrics.getAscent() + lineMetrics
  502. .getDescent()) / 2 - lineMetrics.getDescent())));
  503. }
  504. addMouseListener(new MouseAdapter() {
  505. @Override
  506. publicvoid mouseEntered(MouseEvent e) {
  507. // TODO Auto-generated method stub
  508. System.out.println("光標移入組件");
  509. state = "focused";
  510. repaint();
  511. }
  512. @Override
  513. publicvoid mouseExited(MouseEvent e) {
  514. // TODO Auto-generated method stub
  515. System.out.println("光標移出組件");
  516. state = "normal";
  517. repaint();
  518. }
  519. @Override
  520. publicvoid mousePressed(MouseEvent e) {
  521. // TODO Auto-generated method stub
  522. System.out.print("鼠標按鍵被按下,");
  523. state = "pressed";
  524. repaint();
  525. }
  526. @Override
  527. publicvoid mouseReleased(MouseEvent e) {
  528. // TODO Auto-generated method stub
  529. System.out.print("鼠標按鍵被釋放,");
  530. state = "released";
  531. repaint();
  532. }
  533. });
  534. }
  535. }
  536. /**
  537. * @param args
  538. */
  539. publicstaticvoid main(String[] args) {
  540. // TODO Auto-generated method stub
  541. JButton_Bg frame = new JButton_Bg();
  542. frame.pack();
  543. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  544. frame.setVisible(true);
  545. }
  546. }
Copyright © Linux教程網 All Rights Reserved