开发者

Java Swing - Why JComponent won't display?

开发者 https://www.devze.com 2023-03-22 07:12 出处:网络
I\'m trying to extend a class to eventually make a custom button.I read in several places that it\'s best to extend as high as possible on the heirarchy (for better polymorphism?), so I\'m trying to e

I'm trying to extend a class to eventually make a custom button. I read in several places that it's best to extend as high as possible on the heirarchy (for better polymorphism?), so I'm trying to extend JComponent:

import javax.swing.*;
import java.awt.*;

public class TestButton extends JC开发者_如何转开发omponent {
    private static final long serialVersionUID = 1L;
    
    
    public TestButton() {
        super();        
    }
    
}

And the code that calls this is:

 b1 = new TestButton();     
 basePanel.add(b1,gbc);  // (gbc is GridBagConstraints object)

The thing is, my JComponent isn't displayed in my layout. If I extend the class as JButton, it shows no problem. What's the deal?

Update:

FYI, this is sort of a noob conceptual question, I'm far from proficient here obviously.

Here's a picture to describe. The only thing changed is extends ______.

What should be happening is a purple-filled block, the same height as the yellow block on the bottom.

What is happening is a default sized block that has no background (the black is from the JFrame).

Java Swing - Why JComponent won't display?


One of the main differences between JComponent and it's subclasses is that the latter have UI delegates, while JComponent does not. Note that the setBackground() "color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations." As a result, you "must override paintComponent() to honor this property."


What do you expect to see in the place where JComponent is supposed to be? when you extend JButton, you get all its graphic with it, but you created an empty component, with nothing in it. Try putting something in the component (such as a JLabel or similar)


You still need to extends JButton if you want JButton's functionality. Otherwise everybody can extend Object and expect everything.


It is a blank component (basically a template). It has no properties. You have to add your own graphical elements by overriding the paintComponent method and then add logical elements by overriding the update method.


Either use the JButton as it is:

 JButton b1 = new JButton("Enter JButton text here");     
 basePanel.add(b1,gbc); 

or extend the JButton class if you wish to change certain properties and customize it for your own preferences:

public class TestButton extends JButton {
    private static final long serialVersionUID = 1L;


    public TestButton(String buttonText) 
    {
        super(buttonText);        
    }

}
0

精彩评论

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

关注公众号