[英]How to set the default icon in a JFrame?
So I was making Java, and made a nice little program. 因此,我正在编写Java,并编写了一个不错的小程序。 Here's the code: 这是代码:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class aa extends JFrame{
private JButton jb;
private JTextField jt0;
private JTextField jt1;
private JTextField jt2;
int jti1;
int jti2;
public aa(){
jb = new JButton(">> FIGHT <<");
jt0 = new JTextField("", 25);
jt1 = new JTextField("", 25);
jt2 = new JTextField("<< BATTLE VICTOR >>", 35);
jt0.setText("");
jt2.setEditable(false);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jt0.getText().length() > jt1.getText().length())
jt2.setText((jt0.getText() + " << IS VICTORIUS OVER >> " + jt1.getText()));
else if(jt1.getText().length() > jt0.getText().length())
jt2.setText((jt1.getText() + " << IS VICTORIUS OVER >> " + jt0.getText()));
else if(jt1.getText().length() == jt0.getText().length())
jt2.setText((jt1.getText() + " << TIED >> " + jt0.getText()));
};
}
);
add(jt0, BorderLayout.NORTH);
add(jt1, BorderLayout.NORTH);
add(jt2, BorderLayout.NORTH);
add(jb, BorderLayout.CENTER);
}
}
And here is the running script: 这是正在运行的脚本:
import java.awt.FlowLayout;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class a{
public static void main(String[] args){
aa b = new aa();
b.setLayout(new FlowLayout());
b.setTitle("BattleWords");
b.setSize(420, 150);
b.setVisible(true);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
} }
I have so far tried the whole setIconImage()
crap and it did not work. 到目前为止,我已经尝试了整个setIconImage()
废话,但没有成功。 I want to add in a png or gif or ico image. 我想添加一个png或gif或ico图像。 Where should I place it? 我应该放在哪里? Where does the code go and how can it look like? 代码在哪里,它看起来如何?
You do in fact use JFrame.setIconImage()
. 实际上,您确实使用了JFrame.setIconImage()
。 Here is an example of code which could appear in the constructor of your JFrame
or even better in an initComponents
method: 这是一个代码示例,可能会出现在JFrame
的构造函数中,甚至可能出现在initComponents
方法中:
try {
Image image = ImageIO.read(aa.class.getResource("/TestImage.png"));
setIconImage(image);
} (IOException e) {
// handle exception
}
The image TestImage.png
would be located in the root folder where your class files are located. 图像TestImage.png
将位于类文件所在的根文件夹中。 This 这个
Try making a folder outside your sources then put the icon image in there. 尝试在源外部创建一个文件夹,然后在其中放置图标图像。 Then, use this code to load your icon. 然后,使用此代码加载您的图标。
b.setIconImage(ImageIO.read(new File("res/icon.png")));
I use this and it works every time. 我用它,它每次都起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.