how to import icons from other packages in java - java

Ok so I use use this code to import an icon from the same file that the class is in and assign it a JLabel,
JLabel label1;
Icon iron_ore = new ImageIcon(getClass().getResource("icon_ore"));
label1 = new JLabel(iron_ore);
But what code do I have to add if I want to put the icon in a file different from witch the class is in? Thank you.

If the image is in the package foo.bar.baz, you use
getClass().getResource("/foo/bar/baz/the-icon.png")
as explained in the javadoc, of course.

Related

How to use another classes' functions in Java

First time using the stackoverflow. So, please don't be too harsh :)
I have a little Java project. We are learning how to built GUI with swing. I am stuck with methodology.
I have a JFrame for GUI and I am creating 4 JPanels for:
Menu (Menu Class)
Buttons (Buttons Class)
ActionArea (ActionArea Class)
Statusbar (StatusBar Class)
I have been asked to have same options in the Menu and Buttons. i.e. New File or Open File options will be available in the Menu and Buttons sections.
I don't want to duplicate the code and copy into Menu Class and Buttons Class. I believe there is a way to use only one function from both classes.
Could somebody help me to achieve this?
Here is main code:
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class GUI extends JFrame {
private Menu menu;
private Buttons buttons;
private ActionArea actionArea;
private StatusBar statusBar;
public GUI() {
super("New GUI");
this.setSize(800, 600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout (new BorderLayout());
this.menu = new Menu();
this.buttons = new Buttons();
this.actionArea = new ActionArea();
this.statusBar = new StatusBar();
this.setJMenuBar(this.menu);
add(this.toolbar, BorderLayout.NORTH);
add(this.actionArea, BorderLayout.CENTER);
add(this.statusBar, BorderLayout.SOUTH);
}
}
lets say the function name is newFile();
I don't want to write this function one for menu class and one for buttons class.
Thanks in advance to all
EDIT:
this.menu = new Menu(); creates menuitems with required actions in Menu class
this.buttons = new Buttons(); creates jbuttons with required actions in Buttons class
actions are exactly same. Code is doubled. This is the problem.
Use a Swing Action. See How to use Actions for details on using them in buttons and menu items.
you can use Action class which is an extension of ActionListener....there are several properties you can set in objects of these class...you can check out the line:
Tutorial for Using Action classes
and for API: Action classes API
it may help you..
You can make your Button class to take the object of Menu class as parameter in its constructor. Now, with this object, you can get access to the Action classes of your Menu class, and then, you can use them for your button.
If you still can't understand, please provide the code of your Button and Menu classes.

Simple Java GUI, cards not appearing

import javax.swing.*;
public class SlideShow {
JFrame slide = new JFrame("Slide Show");
public SlideShow(){
slide.setSize(300,400);
slide.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
slide.setVisible(true);
slide.setLocationRelativeTo(null);
JPanel panel = new JPanel();
JLabel label = new JLabel(new ImageIcon("Images/picture1"));
panel.add(label);
slide.add(panel);
}
public static void main(String[] args){
SlideShow slide = new SlideShow();
}
}
I have to create a simple Java GUI that displays some cards. First, I just wanted to test it by displaying one card. For some reason I can't seem to figure out why nothing is being displayed.
You haven't actually used a proper file name "Images/picture1". Should be something like "Images/picture1.png" with the file format
Also image files, generally should be read from the class path, if you plan on having them embedded to the program. To do so, you will first need to put the file in the class path. With most IDE build configurations it's as simple as placing the image in the src. So
ProjectRoot
src
images
picture1.png
Then you would read it like
new ImageIcon(getClass().getResource("/images/picture1.png"));
A better approach would be to use ImageIO.read(). If the file path is incorrect, it will throw an exception, so you know where you're going wrong
Image image = ImageIO.read(getClass().getResource("/images/picture1.png"));
ImageIcon icon = new ImageIcon(image);
You will need to put it in the try/catch block
Also do what codeNinja said about the setVisible() after adding component. Also preferably pack() the frame, instead of setSize()
You need to set the Frame visible after you add all necessary components to it. Move slide.setVisible(true); Down to the bottom of the constructor like this:
...
slide.add(panel);
slide.setVisible(true);
Alternatively you can add slide.revalidate(); at the bottom of your constructor.

How to change java icon in a JFrame

Ok so I've been researching this one quiet a bit. I am fairly new to java but thought that this one would be easy. Ive tried just about every way that has been answered on this site and still no luck, and usually when I look here I am able to find a answer that fits what I am looking for. Does anyone know how to change the Java icon in the top corner of the JFrame. I'm pretty positive that its not my file path either because all my images are in the same folder and they all work, this is the only one that I can't seem to get to work.
This is the first part my code for the main menu of my program, everything works except when i try to add the icon image. The code I've entered below does not have anything in it for the JFrame IconImage, I removed it since it didn't work. So if there is someone who knows how to get it working with this code that would be highly appreciated, thank you very much in advanced!
public class MainFrame
{
private MyPanel main;
private MyPanel2 create;
private MyPanel3 update;
private MyPanel4 find;
JFrame frame = new JFrame("Main Menu:");
public void displayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
main = new MyPanel(contentPane, this);
create = new MyPanel2(contentPane);
update = new MyPanel3(contentPane);
find = new MyPanel4(contentPane);
contentPane.add(main, "Main Menu");
contentPane.add(create, "Create Part");
contentPane.add(update, "Update Part");
contentPane.add(find, "Find Part");
frame.setLocation(200, 200);
frame.setSize(700, 580);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
I have an answer for you. First, make sure that the images are in a folder, not a package. Next, insert this line of code:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("path/to/image.png"));
ImageIcon icon = new ImageIcon( );
setIconImage(icon.getImage());
This code gets the image from the class path, and returns it as a image icon, and then it sets it. This should add the image icon to the application. If it doesn't, then tell me.
EDIT: After you told me that that didn't work then I decided to take a second crack at it...
First, put your images into a completely separate folder. I usually call this /res. Next, put your image in there. Now, for loading I took a completely different route. I decided to use ImageIO instead of default loading. To load the image, you use this code:
try {
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
}
catch (IOException exc) {
exc.printStackTrace();
}
ImageIO works a lot better for loading images. If this still doesn't work then please tell me.
If you want to export this as a JAR then put a folder the same name as you used in the program in the same directory as the JAR.
For example in a NetBeans project, create a resources folder in the src folder.
Put your images (jpg, ...) in there.
Whether you use ImageIO or Toolkit (including getResource),
you must include a leading / in your path to the image file:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/agfa_icon.jpg"));
setIconImage(image);
If this code is inside your JFrame class, the image is added to the frame as an icon in your title bar.
This works pretty fine for me.
Just add this after you've created your JFrame.
try {
Image image = new ImageIcon("/icons/image.jpg").getImage();
frame.setIconImage(image);
}catch(Exception e){
System.out.println("Application icon not found");
}
Paste your image icon (fav.png) in the same package first,
Write following code in constructor of JFrame:
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("fav.png")));
Note:- fav.png is the name of icon
this.setIconImage(new ImageIcon(getClass().getResource("/iconsfolder/iconsname.jpg")).getImage());
// sets the Global icon for the system
try this code put after this code:
public void displayGUI()
{

Using JLabel for a background image

When I run the code it just opens an empty window
I also important whatever is necessary
relevant parts of the code:
public class Game extends JFrame implements ActionListener,KeyListener{
private JLabel background;
....
public Game(){
background=new JLabel(new ImageIcon("/graphics/board.gif"));
...
this.add(background);
this.setSize(800,600);
this.setVisible(true);...
I tried adding the JLabel to a JPanel and then add it to the frame but it still shows nothing in the window
Originally the code was:
JLabel background = new JLabel("/graphics/board.gif");
This would not set the image at the path described, Suggest that the following method is used (this could be simplified to just use a different JLabel constructor but steps shown for clarity)
Create and load the image and then set the icon for the Label As follows
ImageIcon icon = new ImageIcon("/graphics/board.gif");
JLabel background = new JLabel();
background.setIcon(icon);
Link to ImageIcon Java Doc
It is important to set in the layout the order in which the elements are displayed , maybe you have something that is displayed over the label..
I'm guessing you have a directory structure something like:
-c:\java
- source (for source and class files)
- graphic (for your images)
background=new JLabel(new ImageIcon("/graphics/board.gif"));
Don't specify the leading "/" in the file name. That tells Java to look at the root of the C drive, not at the directory where your class is executing from.
Also, don't use:
this.setSize(800,600);
The image does not stretch to fill the size of the frame. Intead you should be using:
this.pack();
so the frame will be the size of the image.

How to modularize panels in GWT

Suppose I have the following layout for my page:
vertical panel mainbody = new VerticalPanel;
//beginning of 1st sub-vertical panel
VerticalPanel first_panel = new verticalPanel();
first_panel.add(...);
//other such stuff, end of first_panel
mainbody.add(first_panel);
//beginning of 2nd sub-vertical panel
VerticalPanel second_panel = new verticalPanel();
second_panel.add(...);
//other such stuff, end of first_panel
mainbody.add(second_panel);
//beginning of 3rd sub-vertical panel
VerticalPanel third_panel = new verticalPanel();
third_panel.add(...);
//other such stuff, end of first_panel
mainbody.add(third_panel);
//end of mainbody
RootPanel.get().add(mainbody);
I want to modularize it, such that each sub panel (first_panel, second_panel and third_panel) belong to individual files, so that after some import, I can just code this in the main page to do the trick:
vertical panel mainbody = new VerticalPanel;
mainbody.add(first_panel);
mainbody.add(second_panel);
mainbody.add(third_panel);
//end of mainbody
RootPanel.get().add(mainbody);
The sub-panels themselves may use other sub-panels, for which the modularization should cascade. Now what do I need to do to enable this? The Google documentation is not quite clear to me. Specifically,
How do I define those panels in individual files (packages or folders) so that they can be imported into the main file?
How do I import them (somewhat like include in PHP)?
What changes do I need to make to the xml file (if any is needed)?
How to define the same set of rules for the imported files also, so that the imports cascade? That is, if a imports b, and b imports c and d to construct itself, both c and d are imported into the main file dutring import?
Will the CSS rules in the main CSS file be enough for all imported panels?
If someone can explain this from the viewpoint of the default StockWatcher app which comes packaged with GWT (so that we can have some common ground for understanding the directory structure), it will be easy for me to understand.
You need to make a Widget out of the panels.
package com.example.widgets // Make this package whatever you want
import com.google.gwt.user.client.ui.Composite
public class FirstPanel extends Composite{
private VerticalPanel verticalPanel;
public FirstPanel(){
verticalPanel = new VerticalPanel();
// All composites must call initWidget() in their constructors.
initWidget(verticalPanel);
// For your CSS
setStyleName("example-SomeStyle");
// Continue constructing object ...
}
}
The initWidget() needs to be called exactly once every time the constructor is used. It sets the widget to be wrapped by the composite. Check the documentation here.
Then you'll be able to use it like so
VerticalPanel mainPanel = new VerticalPanel();
FirstPanel firstPanel = new FirstPanel();
mainPanel.add(firstPanel);
The above should answer point 1
If your Widget isn't in the same package as the code above you'll need to import it. For the example above: import com.example.widget.FirstPanel
No changes need to be made in the XML file
Yes, the imports will cascade as you described.
The CSS Rule in the main CSS should be enough as long as you declare the style names in the widgets. You can do that by calling setStyleName("example-SomeStyle"); as you can see in the example above.
What you are asking about is called custom widgets. You can create a custom widget to represent first_panel, another one to represent second_panel, etc. Then you can make widgets that consist of other widgets, if necessary. Each custom widget is a separate class - it will be represented by a separate file (or two files if you use Ui:Binder for your custom widget).
You can read more about custom widgets here:
https://developers.google.com/web-toolkit/doc/latest/DevGuideUiCustomWidgets

Categories