public class Test extends JFrame
{
private static final long serialVersionUID = 1L;
public static void main(String [] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MyPanel p = new MyPanel();
p.setVisible(true);
}
});
}
}
Panel代码规定了MyPanel的外观。
public class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private JTextField txtUsername;
public MyPanel()
{
setLayout(null);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.control);
panel.setBounds(0, 0, 500, 500);
add(panel);
ImageIcon icon= new ImageIcon("C:/Users/Admin/Desktop/testPic.jpg");
JLabel wlabel = new JLabel(icon);
wlabel.setBounds(20, 10, 400, 222);
panel.add(wlabel);
JPanel panel_1 = new JPanel();
panel_1.setBounds(36, 244, 614, 159);
panel.add(panel_1);
panel_1.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(40, 40, 100, 20);
panel_1.add(lblUsername);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 18));
txtUsername = new JTextField();
txtUsername.setBounds(179, 52, 195, 30);
panel_1.add(txtUsername);
txtUsername.setColumns(10);
JButton btnSubmit = new JButton("SUBMIT");
btnSubmit.setBounds(424, 65, 145, 44);
panel_1.add(btnSubmit);
btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 18));
btnSubmit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
}
}
为什么我看不到实际的面板?代码编译并运行但我在屏幕上看不到任何内容。
答案 0 :(得分:2)
您必须将JPanel添加到JFrame中。它是JFrame,它是显示整个GUI的顶级窗口。如果没有如上所述直接创建顶级窗口,或者间接创建顶级窗口,例如创建JOptionPane时,将永远不会看到JPanel。
所以,而不是这个:
public void run()
{
MyPanel p = new MyPanel();
p.setVisible(true);
}
这样做:
public void run()
{
Test test = new Test();
test.setVisible(true);
}
然后在测试构造函数中创建MyPanel,并通过调用add(...)
将其添加到Test中。
接下来我们将讨论为什么空布局和setBounds(...)
是一件非常糟糕的事情。
关键教程链接: