我想创建一个包含一些JLabel的JPanel子类。我开始编写代码,但我立刻发现了一个大问题。添加到JPanel子类的组件不可见(或者它们未添加到JPanel我不会卡诺)。这是JPanel子类的代码:
public class ClientDetails extends JPanel
{
private JLabel nameAndSurname = new JLabel ("Name & Surname");
private JLabel company = new JLabel ("Company");
private JPanel topPanel = new JPanel ();
public ClientDetails ()
{
this.setBackground(Color.white);
this.setLayout(new BorderLayout());
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
topPanel.add(nameAndSurname);
topPanel.add(company);
this.add(topPanel,BorderLayout.PAGE_START);
}
}
答案 0 :(得分:1)
你需要
public class Test extends JPanel {
private JLabel nameAndSurname = new JLabel ("Name & Surname");
private JLabel company = new JLabel ("Company");
private JPanel topPanel = new JPanel ();
JFrame frame;
public Test()
{
this.setBackground(Color.white);
this.setLayout(new BorderLayout());
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
topPanel.add(nameAndSurname);
topPanel.add(company);
this.add(topPanel,BorderLayout.PAGE_START);
frame = new JFrame("test");
frame.add(this);
frame.pack();
frame.setVisible(true);
}
}