开发者

JButton Customization Issue

开发者 https://www.devze.com 2023-03-25 21:32 出处:网络
I need some help with customizing JButton. I am using following extended method to do so ... I need to add backgound color to the button and also i need to place two different text at two location in

I need some help with customizing JButton.

I am using following extended method to do so ... I need to add backgound color to the button and also i need to place two different text at two location in the button(Top Left & Center)

My code is not able to support both the scenarios(Color and Text Position). Either I am able to have the tex开发者_StackOverflow中文版t located or I am able to get a BG color. In the current code I am getting BG color but text in not appearing

protected void paintComponent(Graphics g) {
        g.setColor( color);
        g.fillRect(0, 0, getSize().width, getSize().height);
        super.paintComponent(g);
        setPreferredSize(new Dimension(47, 33));

        if (isHeader) {
            g.setFont(new Font("Arial", Font.PLAIN, 11));
            g.drawChars(date.toCharArray(), 0, date.length(), 13, 20);
            //setBackground(color);

        } else {
            g.setFont(new Font("Arial", Font.PLAIN, 9));
            g.drawChars(date.toCharArray(), 0, date.length(), 3, 11);

            g.setFont(new Font("Arial", Font.PLAIN, 11));
            g.drawChars(hours.toCharArray(), 0, hours.length(), 18, 20);

        }
        super.paintComponent(g);
        setContentAreaFilled(false);
        g.finalize();
    }


At first glance it looks like you are drawing the text, but you're drawing it in the same color as the background, so you won't be able to see it. Black text on a black background is just black.

You need a different color for the text and the background. Something like;

protected void paintComponent(Graphics g) {
    g.setColor(backgroundColor);
    g.fillRect(0, 0, getSize().width, getSize().height);
    super.paintComponent(g);
    setPreferredSize(new Dimension(47, 33));

    g.setColor(textColor); //set the text color before drawing the text
    if (isHeader) {
        g.setFont(new Font("Arial", Font.PLAIN, 11));
        g.drawChars(date.toCharArray(), 0, date.length(), 13, 20);
    } else {
        g.setFont(new Font("Arial", Font.PLAIN, 9));
        g.drawChars(date.toCharArray(), 0, date.length(), 3, 11);

        g.setFont(new Font("Arial", Font.PLAIN, 11));
        g.drawChars(hours.toCharArray(), 0, hours.length(), 18, 20);
    }
    super.paintComponent(g);
    setContentAreaFilled(false);
    g.finalize();
}

These seems to be a couple of other funnies in your code. Why don't you use setBackground() and why do you call super.paintComponent() twice?

Edit: Also, why are you setting the component's size in the paint method? That seems wrong. And why are you calling finalize() on the Graphics object?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号