【发布时间】:2012-07-07 07:46:20
【问题描述】:
我的组件没有显示出来。我该如何解决这个问题?
代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class login implements ActionListener{
JTextField gusername;
JTextField gpassword;
static String username;
static String password;
void logini() throws IOException {
JFrame window = new JFrame("Login");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300, 250);
window.setResizable(false);
window.setVisible(true);
JPanel mainp = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
window.add(mainp);
BufferedImage myPicture = ImageIO.read(new File("c:\\bgd.png"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
mainp.add(picLabel, c);
c.gridx = 0;
c.gridy = 1;
gusername = new JTextField();
gusername.setText("Username");
mainp.add(gusername, c);
c.gridx = 0;
c.gridy = 2;
gpassword = new JTextField();
gpassword.setText(" password ");
mainp.add(gpassword, c);
c.gridx = 0;
c.gridy = 3;
JButton login = new JButton("Login");
mainp.add(login, c);
login.addActionListener(this);
login.setActionCommand("ok");
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("ok")){
try {
this.username = (gusername.getText());
this.password = (gpassword.getText());
System.out.println("0");
}
catch(NumberFormatException ex){
System.out.println("ERROR: Could not preform function: 7424");
}
}
}
}
结果:
【问题讨论】:
-
您编写代码的方式值得怀疑。在实现
JFrame的大小之前,切勿调用setVisible(true)。也就是说,将您的组件添加到您的Jframe,然后调用setVsibile()。请看看这个相关的example -
@nIcE cOw 好的,它起作用了,现在所有的对象都没有在图片上,而是写在框架的下方。
-
由于您将组件添加到
JPanel,并且图片在JLabel上。所以你可以做的是,或者在JPanel上绘制图像,如上面我展示的示例中所述,或者您可以通过将其设置为Layout将组件添加到JLabel,如@987654322 中所述@。 +1 至少显示您正在使用的代码,尽管它不是更接近有效的SSCCE -
@nIcE cOw 我看不懂这些例子,主要是因为我不明白什么是做什么的概念。 ://
-
抱歉回复晚了,那是晚上,你发这个消息的时候:(我给你加个小例子,我会一步一步来解释整个事情。跨度>
标签: java swing jframe jpanel bufferedimage