swing各組件重繪外觀

來源:互聯網
上載者:User

JPanle、JButton、JLabel等等組件,若想實現漂亮的外觀,可以通過實現paintComponent(Graphics g)來完成。

樣本:自訂JButton的滑鼠經過與滑鼠離開的效果。

一、建立NewButton類

package background;import java.awt.Graphics;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.ImageIcon;import javax.swing.JButton;public class NewButton extends JButton {ImageIcon icon = null;public NewButton(){setBorder(null);//取消邊框icon = new ImageIcon("button1.png");this.addMouseListener(new MouseAdapter() {@Overridepublic void mouseExited(MouseEvent e) {//滑鼠離開icon = new ImageIcon("button1.png");repaint();//重繪圖形,調用paintComponent}@Overridepublic void mouseEntered(MouseEvent e) {//滑鼠經過icon = new ImageIcon("button2.png");repaint();}});}public void paintComponent(Graphics g){int x=0,y=0;g.drawImage(icon.getImage(), x, y, 95, 32, this);}}

二、主視窗JFrameDemo

package background;import javax.swing.ImageIcon;import javax.swing.JFrame;public class JFrameDemo extends JFrame {public JFrameDemo(){super("Jpanel Background Demo");//視窗標題NewButton b2 = new NewButton();this.getContentPane().add(b2);//將button加入視窗this.setSize(95, 32);this.setLocationRelativeTo(null);//設定視窗置中this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}/** * @param args */public static void main(String[] args) {new JPanelDemo();}}

通過實現paintComponent可以實現各個組件的自訂外觀。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.