Friday, 19-04-2024, 8:44 AM
AFgame                                               

Chi sẻ kiến thức lập trình - Các demo và ứng dụng mở


Welcome Guest
Menu
Demo - HTML Hack [3]
Java - Swing [5]
Java - 2D Graphics [1]
Java - IO [3]
Java - Audio [1]
Java - Lập trình mạng [2]
Java - Trí tuệ nhân tạo [7]
Java - Lập Trình Nâng Cao [5]
Java - BT Lập trình mạng [6]
Java - Common [2]
C# [1]
Android [15]
Database [1]
Jsp/Servlet [5]
Application [1]
Tài liệu [3]
Thành viên đăng bài [0]
Nơi dành cho thành viên đăng các bài viết hoàn chỉnh hoặc các câu hỏi
Search
Statistics

Total online: 1
Guests: 1
Users: 0
Add background to jtexfield
08-05-2012, 8:10 PM



Để jtexfield có ảnh nền như trên chúng ta chỉ cần @Override lại phương thức paintComponent. Cụ thể làm như sau:
khai báo lớp:
class BackgroundJTexfield extends JTextField {
private BufferedImage image;
private TexturePaint paint;
image và paint là 2 đối tượng quan trọng cho việc vẽ lại ảnh nền cho textfield. Khởi tạo hàm dựng với File ảnh cần làm ảnh nền
public BackgroundJTexfield(File fileImageBg) throws IOException {
        image = ImageIO.read(fileImageBg);
        paint = new TexturePaint(image, new Rectangle(0, -10, image.getWidth(), image.getHeight()));
        setOpaque(false);
    }

Tiếp theo quan trọng là Override lại phương thức paitComponent:
@Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(paint);
        g.fillRect(0, 0, getWidth(), getHeight());
        super.paintComponent(g);
    }

Dựng hàm main để test:
public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("Anh nen cho jtexfield");
        frame.setSize(300, 80);
        JTextField textfield = new BackgroundJTexfield(new File(BackgroundJTexfield.class.getResource("40.jpg").getPath()));
        textfield.setText("Chuc can ban thanh cong!");
        frame.getContentPane().add(textfield);
        frame.setVisible(true);
    }
}
Category: Java - Swing | Added by: as_fancy | Tags: thiensuhanhphuc18, Demo, background, java, khanh, jtextfield, as_fancy, Jackie, afgame
Views: 1634 | Rating: 5.0/1
Total comments: 0
Giới Thiệu
Nghe Radio Zing
- Nhiều kênh
- Thêm kênh tùy thích
- Hẹn giờ tắt



Hát karaoke arirang
- Tìm kiếm nhanh chóng
- Hát thoải mái
- Nhạc beat Arirang chính hãng

Copyright AFgame © 2024
Trường ĐH Nông Lâm TP.HCM
Create a free website with uCoz