Reputation:
So I was making Java, and made a nice little program. 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. I want to add in a png or gif or ico image. Where should I place it? Where does the code go and how can it look like?
Upvotes: 2
Views: 1052
Reputation:
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.
Upvotes: 0
Reputation: 159754
You do in fact use JFrame.setIconImage()
. Here is an example of code which could appear in the constructor of your JFrame
or even better in an initComponents
method:
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. This
Upvotes: 3