[英]How to add a custom component to JFrame?
I'm experiencing issues with adding a new object (of my custom class TemplatesList
) to a JFrame
. 我在将新对象(自定义类TemplatesList
对象)添加到JFrame
遇到问题。 I added a Picture
object to the JFrame before and that works perfect. 我之前在JFrame中添加了Picture
对象,并且效果很好。 But when I want to add an object of my own class, it returns an error for some reason. 但是,当我想添加自己的类的对象时,由于某种原因它会返回错误。 Can you please help me with identifying the problem? 您能帮我找出问题吗? I would appriciate. 我会推荐。
The error says: cannot resolved method add(lista)
when I try to add this: 错误说:当我尝试添加此cannot resolved method add(lista)
时, cannot resolved method add(lista)
:
TemplatesList lista = new TemplatesList();
frame.add(lista);
here's the code: 这是代码:
import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JList;
public class ChoosingPage
{
static JFrame frame;
JLabel choose;
public ChoosingPage ()
{
frame = new JFrame ("Primark's templates");
frame.setSize(500,500);
frame.setLocation(50,50);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setBackground(Color.WHITE);
frame.getContentPane().setBackground(Color.WHITE);
choose = new JLabel("choose your template");
choose.setSize(choose.getPreferredSize());
//choose.setLocation(20,20);
frame.add(choose);
Picture zdjecie = new Picture();
frame.add(zdjecie);
TemplatesList lista = new TemplatesList();
frame.add(lista);
frame.setVisible(true);
}
public static void main (String [] args)
{
new ChoosingPage();
}
}
and the class which I want to add to the JFrame: 以及我要添加到JFrame的类:
import javax.swing.*;
public class TemplatesList
{
private JComboBox faceCombo;
public TemplatesList()
{
faceCombo = new JComboBox();
faceCombo.setEditable(false);
faceCombo.addItem("change request");
faceCombo.addItem("Emergancy Change request");
faceCombo.addItem("problem request");
faceCombo.addItem("problem handover");
}
}
You can only add objects of type Component
to JFrame. 您只能将Component
类型的对象添加到JFrame。 Your class extends Object
(by default). 您的课程扩展了Object
(默认情况下)。 So you have to change your class to look like 所以你必须改变你的班级看起来像
import javax.swing.*;
public class TemplatesList extends JComboBox<String>
{
public TemplatesList()
{
setEditable(false);
addItem("change request");
addItem("Emergancy Change request");
addItem("problem request");
addItem("problem handover");
}
}
as JComboBox
extends Component
. 随着JComboBox
扩展Component
。 And so by extending JComboBox
your TemplatesList
class also extends Component
. 因此,通过扩展JComboBox
您的TemplatesList
类也扩展了Component
。
Then you can use: 然后,您可以使用:
TemplatesList lista = new TemplatesList();
frame.add(lista);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.