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.
Related
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
I'm trying to create a game in Java - the game is going to be a 2-D scrolling game. I have a class called CornPanel which extends JPanel and shows a corn plant - the CornPanel's are what will be moved across the screen. I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
Here's my CornPanel class (abbreviated - I took out the stuff I'm pretty sure isn't causing the problem):
package game;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class CornPanel extends JPanel{
BufferedImage cornImage;
public CornPanel(){
loadImages();
}
public void loadImages(){
try{
cornImage = ImageIO.read(new File("src\\cornBasic.png"));
} catch(IOException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
g.drawImage(cornImage, 0, 0, cornImage.getWidth(), cornImage.getHeight(), this);
}
}
My Game class:
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame{
ArrayList<CornPanel> cornPanels;
JPanel gameContainer;
public Game(){
cornPanels = new ArrayList<CornPanel>();
gameContainer = new JPanel();
setSize(1000, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(new Color(98, 249, 255));
setExtendedState(JFrame.MAXIMIZED_BOTH);
getContentPane().add(gameContainer);
addCornPanel();
setVisible(true);
}
public void addCornPanel(){
CornPanel cornPanel = new CornPanel();
cornPanels.add(cornPanel);
gameContainer.add(cornPanel);
cornPanel.setVisible(true);
getContentPane().repaint();
repaint();
}
public static void main(String[] args) {
Game game = new Game();
}
}
Note: I got it to work by setting the LayoutManager for both the JFrame and gameContainer to new GridLayout(1,1), but the problem is that then I can't use setLocation() on the CornPanel in order to make it animate. If there's a way to do it without setLocation() let me know. Also, I took out a lot of code I don't think is necessary for diagnosing the problem - hopefully I didn't take out too much.
Your corn panel doesn't specify a prefered size, so the layout manager probably is just setting it to 0x0.
There is an easier way to add an icon into a pane. JLabel::JLabel(Icon) will create a label that has the image icon specified, and is of the right size to hold it.
If you do need something more complex than a single image, then your JComponent implementation should override getPreferredSize().
You also should call "pack" on your jframe, so that it can figure out the ideal size for display.
A few other comments not related to your original question:
You shouldn't extend JFrame for the main frame, just create a new JFrame instance, and configure it.
You should do the work in the Event Dispatch Thread. See EventQueue and more specifically read through Lesson: Concurrency in Swing
I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
The layout of the content pane of a frame is BorderLayout, the default constraint is CENTER which stretches a component to fill the space.
The default layout of a panel is FlowLayout which ..doesn't stretch the component to fit.
The best way to fix this is to (firstly) override the getPreferredSize() method of CornPanel to return a sensible size, then add it to a layout/constraint that has the behavior required when it has more space than it needs.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui_Window extends JFrame {
private JLabel Main_L;
public Gui_Window() {
setLayout(new FlowLayout());
Main_L = new JLabel("Did you know it is possible to bind keys?");
add(Main_L);
}
public static void main (String args[]) {
Gui_Window gui = new Gui_Window();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300,300);
gui.setVisible(true);
gui.setTitle("Gamers AudioMute");
gui.setResizable(true);
}
}
I would like to know how to move my "Did you know" Label around. Could you also state how to align left, right, middle and how to move it around by its coordinates?
You can use methods included in Swing classes. Try
mainL.setHorizontalAlignment(SwingConstants.LEFT);
mainL.setVerticalAlignment(SwingConstants.BOTTOM);
The two methods setHorizontalAligment and setVeritcalAlignment both take integers that will set the start of either the horizontal or vertical component of the label to that pixel integer within the Swing window.
You should also read up on SwingConstants which allow you to plug in pre-defined integers by Swing that will align your texts to desirable locations within the panel. Here's a link
http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingConstants.html
They are also useful when manipulating different layouts such as BorderLayout and GridLayout.
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.
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);
}
}