Icon in a JLabel - java

I used the following code:
JLabel jLabel = new JLabel(new ImageIcon(someImage));
I don't get it.. sometimes the image appears when I run the code and sometimes not.. I'm not always getting the same output. Anyone can explain why this could happen?!

Without more code for context it's hard to know for sure, but whenever I hear about a Swing problem that sometimes works, I tend to suspect threading problems; if your GUI is, say, a dialog that is not being built on the Event Dispatch Thread then this sort of randomness is common. If you are not sure about your threading, put this at the top of your method where this code is being executed:
System.out.println(String.format("This code %s running on the Event Dispatch Thread.", (javax.swing.SwingUtilities.isEventDispatchThread() ? "IS" : "IS NOT"));
and see what you get.

Here is simple example for you with JLabel and Icon, examine that :
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Example extends JFrame {
public Example() {
URL resource = getClass().getResource("image.png");
ImageIcon icon = new ImageIcon(resource);
JLabel l = new JLabel(icon);
add(l);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String... s){
new Example();
}
}
image.png is my image, that is placed in the same folder as the class.

Related

Add Textfields on Jframe at Runtime

I am trying to create text-fields on frame by getting input at run-time. Is it possible? Or I have to create another frame for that. I tried this code, but it's not working. Please Help me out, and tell me what's wrong with this code.
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Check extends JFrame implements ActionListener
{
JTextField txtqty;
JTextField[] tfArr;
JPanel p1,p2;
JButton bsmbt;
public Check()
{
GUIDesign();
}
public void GUIDesign()
{
p1 = new JPanel();
txtqty = new JTextField(10);
JButton bsmbt= new JButton("OK");
p1.add(txtqty);
p1.add(bsmbt);
p2=new JPanel();
p2.setLayout(null);
add(p1,BorderLayout.NORTH);
setSize(500, 500);
setVisible(true);
setLocation(100, 100);
bsmbt.addActionListener(this);
}
public static void main(String[] args)
{
new Check();
}
public void TFArray(JTextField[] temp)
{
int x,y,width,height;
x=10;y=30;width=50;height=20;
int no_of_textboxes = Integer.parseInt(txtqty.getText());
temp=new JTextField[no_of_textboxes];
for(int i=0;i<no_of_textboxes;i++)
{
temp[i]= new JTextField(10);
temp[i].setBounds(x, y, width, height);
x+=(width+10);
p2.add(temp[i]);
}
add(p2);
}
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(this, txtqty.getText());
TFArray(tfArr);
}
}
->Method TFArray() isn't working.
You have many errors in your code:
public void TFArray(JTextField[] temp): method names should start with lowerCamelCase
You're extending JFrame, you shouldn't extend JFrame, because when you extend it your class is a JFrame, JFrame is rigid so you can't place it inside anything else, instead you might consider creating a JFrame instance and if you ever need to extend JComponent extend from JPanel.
JButton bsmbt= new JButton("OK"); the variable bsmbt is a local variable inside your constructor, your global variable bsmbt is not used anywhere, and if you try to use it later you'll get a NullPointerException, instead change that line to:
bsmbt= new JButton("OK");
You're using null layout for p2, instead use a proper Layout manager and read Null layout is evil and Why is it frowned upon to use a null layout in swing?. Swing was designed to work with different PLAFs, screen sizes and resolutions, while pixel perfect GUIs (with setBounds()) might seem like the best and faster way to create a complex GUI in Swing, the more GUIs you make, the more errors you'll get due to this.
To solve your problem call revalidate() and repaint()
The above code creates 2 textfields. but when I again put some value and submit it, it doesn't seem to reflect any changes.
That might be because you're overriding x, y, height and width variables each time you enter TFArray method. But that is a guess, if you want a real answer, follow the suggestions above and post a proper and valid Minimal, Complete, and Verifiable example

How To Add JLabel to Already Existing Jframe?

lol i dont even know if i worded that right
i am a really new programmer and this is my code for the main class:
package culminatingnew;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class CulminatingNew {
public static void main(String[] args) {
Container container = null;
JFrame jframe = new JFrame("Math Adventure");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLocationRelativeTo(null);
jframe.setBounds (150, 0, 1000, 1000);
jframe.setBackground(Color.blue);
jframe.setVisible(true);
JLabel labelText = new JLabel("Welcome!");
jframe.getContentPane().add(new CharacterChoose());//
jframe.setVisible(true);
jframe.getContentPane().add(labelText);
jframe.setVisible(true);
So basically, I'm making a game. In another class in the assignment package is CharacterChoose, where the user is greeted with a picture of their character. All I want to do is add text to this same screen saying "Welcome", but whenever I try this it just ignores the CharacterChoose screen and opens a new blank frame that says "Welcome". Is there any way to fix this?
GUI's are not linear/procedural programs, the are event driven, that is, something happens and you respond to it.
Instead, maybe consider using a button saying "Continue" or something, which the user must press, once pressed, you can then present the next view.
I'd recommend having a look at CardLayout for easier management of switching between views.
See How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners and How to Use CardLayout for more details

why is my JLabel not producing an image?

I have gone over several tutorials and was wondering why my JLabel is not producing an image? I thought I had everything where I should be for the image to be displayed. Is it possible other graphics in my program are interfering? Is there any top-down layer system java uses to determine which images are on top of each other if you have multiple ones on top of each other??
package scratch;
import java.awt.Font;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
//import statements
//Check if window closes automatically. Otherwise add suitable code
public class okay extends JFrame {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
public okay(){
jl.setIcon(new ImageIcon("C:\\Users\\ShawnK\\Desktop\\cat.png"));
jp.add(jl);
add(jp);
validate();
}
public static void main(String args[]) {
JFrame window = new JFrame();
okay t1 = new okay();
window.setSize(640,800);
window.setTitle("lets do this");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
drawingComponent DC = new drawingComponent();
ai enemy = new ai();
window.add(DC);
window.add(t1);
}
}
You're just creating a plain vanilla JFrame:
JFrame window = new JFrame();
and you never create a new okay() object. Understand that it will not create itself by magic, and if you want it displayed, you have to do this in code.
As an aside, I have no idea in creation what a drawingComponent is:
drawingComponent DC = new drawingComponent();
since you never show the class code. Also you shouldn't set a JFrame visible until all the components have been added.
Also
Learn and follow Java naming conventions as doing this will help others (us!!) better understand your code. Variable names should all begin with a lower case letter while class names with an upper case letter.
Avoid extending JFrame. While this may be OK for trivial programs such as this, it does not scale well, meaning it makes your code more complicated and paints you in the corner in even slightly larger or more complex programs.
Instead gear your GUI's toward creating JPanels, panels that then can be placed in JFrames if desired, or JDialogs, or JOptionPanes, or other JPanels. This will give your code much greater flexibility.
Again, don't call setVisible(true) on a JFrame until all initial components have been added.
Yes, you're better off getting your image as a BufferedImage using ImageIO.read(...) and then placing this into your ImageIcon. It's a bit safer and (I think) allows for better caching of images.

Creating a Interactive GUI for a java game

Hey guys I'm creating a game similar to farmville in java and I'm just wondering how would I implement the interactive objects/buttons that the user would usually click to interact with the game client.
I do not want to use the swing library (generic windows looky likey objects), I would like to import custom images for my buttons and assign button like properties to those images which would be used for the GUI.
Any advice? Any pointers? I can't seem to find that information through youtube or some other java gaming sites as they're only showing simple example using swing.
Any help would be deeply appreciated thanks!
Regards
Gareth
Do you really not want to use Swing, or do you just not want the default look and feel of a JButton and other swing controls? What does " (generic windows looky likey objects), " mean?
There are many sources out there that describe customizing buttons to include images on top of them:
Creating a custom button in Java
JButton and other controls have all the events and methods associated with adding click listeners, etc. You probably don't want to create your own control. We do not have enough information to go off of, for example what does "interactive objects" mean?
If you simply want to add an icon to a JButton, use the constructor that takes an Icon.
You can use JButton, just override the paint function. and draw what ever you want there. It takes a while until you get it at the first time how this works. I recommend you to read a little about the event-dispatching thread (here is java's explanation)
And here is some code that I wrote so you have a simple reference.
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JButton implements ActionListener{
private static final long serialVersionUID = 1L;
Image img;
/** constuctor **/
public Test(String tImg, JFrame parent){
this.img = new ImageIcon(tImg).getImage();
this.addActionListener(this);
}
/*********** this is the function you want to learn ***********/
#Override
public void paint(Graphics g){
g.drawImage(this.img, 0, 0, null);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO do some stuff when its clicked
JOptionPane.showMessageDialog(null, "you clicked the button");
}
public static void main(String[] args) {
JFrame f = new JFrame();
Test t = new Test("pics.gif", f);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1, 1));
f.add(t);
f.setSize(400,600);
f.setVisible(true);
}
}

Java SWING: adding a JTextField (never used anywhere) randomly makes the screen go white

I'm developing on ubuntu 10.04 with using Eclipse, and when I add a JTextField into the following code (that I don't use anywhere, or make visible!) the window, instead of displaying the images like it's supposed to, goes blank.
Anyone have any idea what's causing this?
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Testi {
public static void main(String[] args) {
ImageIcon icon1 = new ImageIcon("background.jpg");
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,500);
JPanel panel = new JPanel();
panel.setSize(600, 600);
panel.setOpaque(false);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel label = new JLabel();
label.setSize(500, 500);
label.setIcon(icon1);
label.setLayout(new FlowLayout(FlowLayout.CENTER));
// FOLLOWING LINE IS THE PROBLEM: when in code, the screen goes white
JTextArea text1 = new JTextArea("asd");
label.add(panel);
frame.add(label);
}
}
Works for me, which makes me think it is a EDT issue. Move your call to setVisible to the end of your main method.
From this link: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
This method is thread safe, although most Swing methods are not.
An application's GUI can often be constructed and shown in the main thread: The following typical code is safe, as long as no components (Swing or otherwise) have been realized:
public class MyApplication {
public static void main(String[] args) {
JFrame f = new JFrame("Labels");
// Add components to
// the frame here...
f.pack();
f.show();
// Don't do any more GUI work here...
}
}
All the code shown above runs on the "main" thread. The f.pack() call realizes the components under the JFrame. This means that, technically, the f.show() call is unsafe and should be executed in the event-dispatching thread. However, as long as the program doesn't already have a visible GUI, it's exceedingly unlikely that the JFrame or its contents will receive a paint() call before f.show() returns. Because there's no GUI code after the f.show() call, all GUI work moves from the main thread to the event-dispatching thread, and the preceding code is, in practice, thread-safe.
I had the same problem.
For me the fix was to move the call to frame.setVisible() below the part where I added my components.

Categories