I'm trying to find a way to replace all the contents of a JDialog to simply an image.
It's for the about page of a project I'm working on and I want when the user clicks on the About section, an image to popup in the style of a JDialog(and to disappear when focus is lost).
Example: http://www.tecmint.com/wp-content/uploads/2012/08/About-Skype.jpg
There Skype displays only an image they've created as their "About" page.
How can I make an "image dialog" in Java(swing)?
How can I make an "image dialog" in Java(swing)?
Use an undecorated JDialog with a JLabel containing an ImageIcon:
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
JLabel label = new JLabel( new ImageIcon(...) );
dialog.add( label );
dialog.pack();
dialog.setVisible(true);
BufferedImage image = ImageIO.read(new File("myfile.png"));
JLabel picLabel = new JLabel(new ImageIcon(image));
JOptionPane.showMessageDialog(null, picLabel, "About", JOptionPane.PLAIN_MESSAGE, null);
Here you go, I have annotated the code for you
import javax.swing.JOptionPane; //imports
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Toolkit;
import java.awt.Dimension;
public class img{
public static void main(String[] args){
JFrame f = new JFrame(); //creates jframe f
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //this is your screen size
f.setUndecorated(true); //removes the surrounding border
ImageIcon image = new ImageIcon(diceGame.class.getResource("image.png")); //imports the image
JLabel lbl = new JLabel(image); //puts the image into a jlabel
f.getContentPane().add(lbl); //puts label inside the jframe
f.setSize(image.getIconWidth(), image.getIconHeight()); //gets h and w of image and sets jframe to the size
int x = (screenSize.width - f.getSize().width)/2; //These two lines are the dimensions
int y = (screenSize.height - f.getSize().height)/2;//of the center of the screen
f.setLocation(x, y); //sets the location of the jframe
f.setVisible(true); //makes the jframe visible
}
}
[[OLD]]
The code below will do what you're looking for.
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class img{
public static void main(String[] args){
JLabel lbl = new JLabel(new ImageIcon(diceGame.class.getResource("image.png")));
JOptionPane.showMessageDialog(null, lbl, "ImageDialog",
JOptionPane.PLAIN_MESSAGE, null);
}
}
Related
I am using VS Code and my folder contains one Java file and one image only.
I was trying to set image in JLabel, so first I access the image by:
ImageIcon img = new ImageIcon(getClass().getResource("img_flag.png"));
Then I set this to JLabel but nothing appears on my screen.
JLabel label = new JLabel(img);
To confirm that I am accessing the correct image, I set it to the logo of the window and the logo was showing properly.
setIconImage(img.getImage());
I can't figure out why label can't show the image.
Here is my full code:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Mylable extends JFrame{
Mylable(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
ImageIcon img = new ImageIcon(getClass().getResource("img_flag.png"));
setIconImage(img.getImage()); //working
JLabel label = new JLabel(img); //not working
add(label);
}
public static void main(String[] args) {
new Mylable();
}
}
I am currently still learning Java GUI and stumped on this problem. I just wonder why can't i load it anywhere except on center and how do i load my image anywhere else?
import java.awt.*;
import javax.swing.*;
public class GUI {
public static void main(String[] args) {
GUI gui = new GUI();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Player player = new Player();
panel.setBackground(Color.darkGray);
JButton button = new JButton("shock me");
panel.add(button);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.getContentPane().add(BorderLayout.NORTH, player);
//frame.getContentPane().add(BorderLayout.CENTER, player);
frame.setSize(200,200);
frame.setVisible(true);
}
}
Here's my player class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.*;
public class Player extends JPanel{
public void paintComponent(Graphics g) {
Image image = new ImageIcon("Source/hero.jpg").getImage();
g.drawImage(image, 3, 4 , this);
}
}
Player does not override getPreferredSize() to return a value. Since it does not do that, the BorderLayout will not assign it any height in the PAGE_START or PAGE_END constraints, and no width in the LINE_START and LINE_END constraints. The component is being added, it just has no width/height.
The CENTER will stretch both a component's width and height to the available space, that is why it is visible there.
I am trying to change the image icon on a JFrame and it is not showing up. I have tried both the absolute path to my desktop and then the path that I have in Eclipse. Why is this not working. I have looked on stackoverflow and this is how it looks like that it is probably done, but for some reason the code below is not working.
code:
package TestMenu;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TestJFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public TestJFrame() {
ImageIcon img = new ImageIcon("C:\\Users\\itpr13266\\workspace\\TestMenu\\src\\TestMenu\\img\\s.jpg");
setIconImage(img.getImage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(117, 105, 10, 10);
contentPane.add(panel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestJFrame frame = new TestJFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
No exception was thrown.
The code is fix now. I had the wrong image format type.
Code that does not work:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
public class MenuLookDemo {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
menuBar = new JMenuBar();
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(menuItem);
ImageIcon icon = createImageIcon("src\\TestMenu\\img\\stop.jpg");
menuItem = new JMenuItem("Both text and icon", icon);
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(icon);
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"This menu does nothing");
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MenuLookDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MenuLookDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
MenuLookDemo demo = new MenuLookDemo();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Error: (From the above example and it is just like the example above which I got to work)
Couldn't find file: src\TestMenu\img\stop.jpg
May be that BMP is not supported. If you follow the Java source code from the constructor of ImageIcon you end up at:
(java.awt.Toolkit.java)
/**
* Returns an image which gets pixel data from the specified file,
* whose format can be either GIF, JPEG or PNG.
* ...
*/
public abstract Image getImage(String filename);
According to this article, ImageIcon supports GIF, JPEG, or PNG. Try converting your image to another format using something like GIMP or Paint and see if you get the same results.
http://docs.oracle.com/javase/7/docs/api/java/awt/Toolkit.html#getImage%28java.lang.String%29
It worked for me, I substituted a jpeg on my c drive and changed the path accordingly. It placed the icon in the upper left corner of the frame. Try simplifying your path to C:\filename and see if it works.
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Swing {
public static void main(String[] args) {
////jframe = a GUI(graphical user interface) window to add components
JFrame frame = new JFrame();//we are creating a new frame
frame.setVisible(true);//this helps to make the frame visible
frame.setSize(500, 500);//this is for resizing our window into any size
frame.setTitle("Manoj sai");//to set the title for the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//normally when we hit X button it will hide but it will not close so to close that we have to give that when we press X exit_on_close
frame.setResizable(false);//this makes the window not resizeable we cant resize the window
//ImageIcon will help to keep images in GUI(its a separate class)
ImageIcon image = new ImageIcon("C:\\Users\\manoj\\Pictures\\logos\\logo.jpg");//creates an image icon
frame.setIconImage(image.getImage());//sets the selected image for icon for our window
}
}
here use the file path which is in your computer then u will get ur icon displayed after importing to the eclipse use the path which is in ur local disc c ex:"C:\\Users\\manoj\\Pictures\\logos\\logo.jpg"
I am writing a small program that converts files, and I wanted to have a box pop up that asks the user to please wait while the program loops through and converts all the relevant files, but I am running into a small problem. The box that pops up should have a JLabel and a JButton, while the user is "waiting" I wanted to display a message that says please wait, and a disabled "OK" JButton, and then when its finished I wanted to set the text of the JLabel to let them know that It successfully converted their files, and give them a count of how many files were converted. (I wrote a method called alert that sets the text of the label and enables the button.) The problem is That while the program is running, the box is empty, the Label and the Button are not visible, when it finishes, label appears with the final text that I want and the button appears enabled. I am not sure exactly what is going on, I tried changing the modifiers of the JLabel and JButton several times but I cant seem to get it to work correctly. Here is the code for the box that pops up, any help is greatly appricated.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends javax.swing.JFrame{
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel("Please Wait while I convert your files");
private static JButton OK = new JButton("OK");
public PleaseWait(){
// creates the main window //
JFrame mainWindow = new JFrame();
mainWindow.setTitle("Chill For A Sec");
mainWindow.setSize(width, height);
mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
mainWindow.add(mainLayout);
// sets everything visible //
mainWindow.setVisible(true);
}
public static void alert(){
OK.setEnabled(true);
String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + total + " files Converted");
}
}
Okay here's the issue. You are extending the JFrame . That means your class IS a JFrame.
When you create the PleaseWait frame you don't do anything to it. This is the empty box you are seeing. You are instead creating a different JFrame in your constructor. Remove your mainWindow and instead just use this. Now all of your components will be added to your PleaseWait object. That should fix your blank box issue.
You need an application to create your frame first. This is a simple example of such application.
import javax.swing.UIManager;
import java.awt.*;
public class Application {
boolean packFrame = false;
//Construct the application
public Application() {
PleaseWait frame = new PleaseWait();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.convert();
}
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application();
}
}
You have to slightly modify your frame to add controls to the content pane. You can do some work after frame is created, then call alert.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends JFrame {
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel();
private static JButton OK = new JButton("OK");
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane;
int count;
public PleaseWait(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(width, height));
this.setTitle("Chill For A Sec");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
contentPane.add(mainLayout);
}
public void convert(){
count = 0;
for (int i = 0; i <10; i++){
System.out.println("Copy "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
}
alert();
}
public void alert(){
OK.setEnabled(true);
// String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + count + " files Converted");
}
}
I have a JLabel that contains variable text in a certain location in my GUI. The problem is that the text gets displayed at the bottom of the space where the JLabel is located. This does not convey to the end user the relevant information about the other contents of the GUI. Instead, I need the text of the JLabel to be printed in the middle of the vertical axis of the JLabel. A simplified version of my code is below. Can anyone show me how to alter it so that the text displays in the middle of the vertical axis instead of the bottom?
Main.java:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(400, 300);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}
VerticalLabel.java:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel {
public VerticalLabel(String labelText) {
Dimension myDim = new Dimension(15, 250);
this.setPreferredSize(myDim);
this.setHorizontalAlignment(LEFT);
this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
this.setUI(new VerticalLabelUI(false));
this.setBorder(new EtchedBorder());
}
}
Hardcoding a random preferred size is not a good idea.
You wrote a custom UI, so it is the responsibility of the UI to paint the text in the proper position.
Instead of creating a custom UI you can use the Text Icon approach to display vertical text. Create the label as follows:
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
TextIcon labelIcon = new TextIcon(label, "Hello", TextIcon.Layout.VERTICAL);
label.setIcon( vIcon );
Add the label to the CENTER of a panel using a BorderLayout and the vetical text will be centered vertically and horizontally.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel{
public VerticalLabel(String labelText){
this.setHorizontalAlignment(LEFT);
this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
//this.setUI( new VerticalLabelUI(false) );
this.setBorder( new EtchedBorder() );
}
public static void main(String[] args){
// should be done on the EDT.
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout( new GridBagLayout() );
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(200,150);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}