Domanda

I am trying to create a JFrame in Java, with a JPanel inside of it, which will hold a component.
I know how to add components using

panelname.add(component);

But I am making a class based off a JTextField and want to add the entire CLASS as a component into the JPanel, but when I do, Eclipse tells me:
The method add(Component) in the type Container is not applicable for the arguments (BetterText)

(BetterText been the name of the class)
So all it basically is, is a class with a JTextField setup with methods and such, but I want to add that class as a component to the JPanel. I looked at the JTextField.java class and cant see anything interesting there, it looks like an ordinary class like any other, but you are able to add an instance of that class to a JPanel, whereas with mine, you cant.
Any help will be appreciated, thankyou.
Also, if you know the solution, please post an example class.

Edit: Added code.

public BetterText(String defaultText) {
    super();
    //Sets up the textFields colours and the defaultText to display in it.
    setProperties();
    hasDefault = true;
    this.defaultText = defaultText;
    textField.addActionListener(this);
}

Another edit:

It also extends JTextField already.

public class BetterText extends JTextField implements ActionListener {
È stato utile?

Soluzione

Make sure your JFrame, JPanel and JTextField extend the correct classes (if they are custom classes).

Some pseudo code:

public class BetterText() extends JTextField{    
    public BetterText(){
        super();
    }   
}

And then to create the GUI:

JFrame frame = new JFrame();
JPanel panel = new JPanel();
BetterText textField = new BetterText();
frame.add(panel);
panel.add(textField);
panel.pack();
panel.setVisible(true);

Altri suggerimenti

Verify that you are importing javax.swing.JComponent, then make your BetterText class inherit from JTextField.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top