When Loading Image Using BufferdImage and ImageIO it Clears my Whole Frame and Does Not Display Image - image

I and making a program using basic GUI involving buttons, frames, and panels, and everything was fine until I tried to load an image from my project folder. When i add the line of code
try{
titleImage = ImageIO.read(new File("mouse_title_resize.png"));
}
catch(Exception e){}
After I run the program my whole frame just becomes blank whereas before I had some JButtons on it.All the code I had before the try-catch line worked perfectly fine and I tested to see that the only thing that breaks it is this line of code. I receive no errors or anything and I have the image in my project folder and it seems that the image loaded fine, except it wont show up on the frame, and everything else on the frame disappears. I just don't understand why it clears my whole frame when i load the image.
Here is the full code:
This is the class that extends JFrame
package mouse.click.game;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class MouseClickGame extends JFrame {
//Constants to define the frame width and height including borders
public final int FRAME_WIDTH = 600;
public final int FRAME_HEIGHT = 600;
//Dimension from Toolkit to be able to get width and height of screen
public Dimension sizeTool = Toolkit.getDefaultToolkit().getScreenSize();
//Using sizeTool to get width of screen
public double xResolution = sizeTool.getWidth();
//Using sizeTool to get height of screen
public double yResolution = sizeTool.getHeight();
//Creating a point object that is defined as the center of the screen
public Point middleOfScreen = new Point((int) (xResolution / 2) - (FRAME_WIDTH / 2), (int) (yResolution / 2) - (FRAME_HEIGHT / 2));
public MouseClickGame() {
super("WELCOME :D");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocation(middleOfScreen);
add(new MouseClickPanel());
}
public static void main(String[] args) {
//Calling constructor
MouseClickGame mainClickGame = new MouseClickGame();
}
}
And here is the class that extends JPanel (these are the only two classes in my project)
package mouse.click.game;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MouseClickPanel extends JPanel {
JButton buttonPlay = new JButton("Play");
JButton buttonContinue = new JButton("Continue");
JButton buttonOptions = new JButton("Options");
JButton buttonExit = new JButton("Exit");
BoxLayout boxLay = new BoxLayout(this, BoxLayout.Y_AXIS);
Dimension menuButtonSize = new Dimension(300, 30);
Dimension spacingBetweenButtons = new Dimension(0, 30);
BufferedImage titleImage;
public MouseClickPanel() {
try {
titleImage = ImageIO.read(new File("C:\\Users\\Justin\\Desktop\\mouse_title.png"));
} catch (IOException e) {
}
setLayout(boxLay);
add(Box.createVerticalGlue());
add(new JLabel(new ImageIcon(titleImage)));
//Adding glue to force buttons away from top of panel
add(Box.createVerticalGlue());
add(buttonPlay);
//Vertical spacing between buttons
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonContinue);
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonOptions);
add(Box.createRigidArea(spacingBetweenButtons));
add(buttonExit);
//Adding glue to force buttons away from bottom of panel
add(Box.createVerticalGlue());
//Aligning all buttons to centered horizontally
buttonPlay.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonContinue.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonOptions.setAlignmentX(Box.CENTER_ALIGNMENT);
buttonExit.setAlignmentX(Box.CENTER_ALIGNMENT);
//Setting button sizes
buttonPlay.setMaximumSize(menuButtonSize);
buttonContinue.setMaximumSize(menuButtonSize);
buttonOptions.setMaximumSize(menuButtonSize);
buttonExit.setMaximumSize(menuButtonSize);
}
}
Literally if i get ride of the titleImage = and add(new JLabel) lines everything goes back to normal

My guess is that you've just got the path wrong -- a common mistake. In that case, you should be getting an exception like:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at jonathanrmiproject.MyProject.main(JonathanRmiProject.java:24)
This simple example works for me:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.naming.NamingException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyProject {
public static void main(String[] args) throws NamingException, IOException {
BufferedImage img = ImageIO.read(new File("myimage.jpg"));
JLabel label = new JLabel(new ImageIcon(img));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200, 200);
f.setVisible(true);
}
}
I am using Netbeans IDE, and I have saved the image file to "C:\Users\David.Sharpe\MyProject\myimage.jpg".
I should add that if this is not the case, and you do have the correct path, then you need to post a more detailed question so that someone can help you. Include the code to reproduce the problem.

UPDATE: Wow literally the reason it wasn't showing up was because i called setVisble(true) too early. I can't believe it was something that simple. I guess that explains why one time everything would show up and it would be fine but then every time after nothing showed up.
So in my constructor I had
public class MouseClickGame extends JFrame {
public MouseClickGame() {
super("WELCOME :D");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(middleOfScreen);
setVisible(true);
add(new MouseClickPanel());
}
public static void main(String[] args) {
//Calling constructor
MouseClickGame mainClickGame = new MouseClickGame();
}
}
when all I had to do was put the setVisble() after the add(newMouseClickPanel())
Thank you DavidS for your suggestions :D

Related

Dr. Java: Static Error: This class does not have a static void main method accepting String[] when running program

I am taking my second Java class ever, and was told by my professor to use Dr. Java. We have started learning GUI, and he has given us some sample code as examples:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.collections.*;
public class HelloWorldMain extends Application{
public void start(Stage primaryStage){
FlowPane pane = new FlowPane();
// put all controls on 'pane'
Label lblHello = new Label("Hello");
pane.getChildren().add(lblHello);
Button btnHello = new Button("Hello World");
pane.getChildren().add(btnHello);
TextField txtHello = new TextField("Hello");
pane.getChildren().add(txtHello);
PasswordField pass = new PasswordField();
pane.getChildren().add(pass);
CheckBox cbHello = new CheckBox("Hello");
pane.getChildren().add(cbHello);
RadioButton rbMale= new RadioButton("Male");
RadioButton rbFemale = new RadioButton("Female");
pane.getChildren().add(rbMale);
pane.getChildren().add(rbFemale);
ToggleGroup group = new ToggleGroup();
rbMale.setToggleGroup(group);
rbFemale.setToggleGroup(group);
ChoiceBox cbColors = new ChoiceBox();
cbColors.setItems(FXCollections.observableArrayList("Red", "Green", "Blue"));
pane.getChildren().add(cbColors);
Scene scene = new Scene(pane, 300, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
}
However, when I try to run this in Java, I get the following error:
Static Error: This class does not have a static void main method accepting String[].
Professor is not able to help me, and I don't see an answer to this exact question. Any help is appreciated!

TableView columns position and TabbedPane tabs start from Right Side instead of left in JavaFX?

i've been searching for hours and could not find any way to make the tableView columns and tabs of a TabbedPane start from the right side instead of left.
As we can see in the picture java by default create them from the left side to the right, and leave empty space on the right side. Is there any way to do this vice versa ?
Thank you
see image here
Use setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
import javafx.application.Application;
import javafx.geometry.NodeOrientation;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class NodeOrientationTest extends Application {
#Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
Tab tab1 = new Tab("Tab 1");
Tab tab2 = new Tab("Tab 2");
tabPane.getTabs().addAll(tab1, tab2);
TableView<Void> table = new TableView<>();
table.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT);
table.getColumns().add(new TableColumn<Void, Void>("Column 1"));
table.getColumns().add(new TableColumn<Void, Void>("Column 2"));
tab1.setContent(table);
Scene scene = new Scene(tabPane, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Note that the table view will, by default, inherit this from its parent, so you can omit the call to table.setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT); and achieve the same result. (Or just set it on the scene.)

How to add an inline image to the end of a string in a TextArea in JavaFX?

I am trying to add an emoji to my chat program when my client types :)
I am trying to add this in the FXML controller. I have captured when the user types :) using the following code snippet :
if(chat.contains(":)")) {
...
}
My chat is printed into a textarea named taChat
taChat.appendText(chat + '\n');
Any help is appreciated!
A better approach would be to use TextFlow instead of using TextArea.
Advantages :
Individual Text are treated as children to the TextFlow. They can be added and accessed individually.
ImageView can be added directly to the TextFlow as a child.
A simple chat window with support for smiley :)
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class ChatWindowWithSmiley extends Application {
public void start(Stage primaryStage) {
TextFlow textFlow = new TextFlow();
textFlow.setPadding(new Insets(10));
textFlow.setLineSpacing(10);
TextField textField = new TextField();
Button button = new Button("Send");
button.setPrefWidth(70);
VBox container = new VBox();
container.getChildren().addAll(textFlow, new HBox(textField, button));
VBox.setVgrow(textFlow, Priority.ALWAYS);
// Textfield re-sizes according to VBox
textField.prefWidthProperty().bind(container.widthProperty().subtract(button.prefWidthProperty()));
// On Enter press
textField.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.ENTER) {
button.fire();
}
});
button.setOnAction(e -> {
Text text;
if(textFlow.getChildren().size()==0){
text = new Text(textField.getText());
} else {
// Add new line if not the first child
text = new Text("\n" + textField.getText());
}
if(textField.getText().contains(":)")) {
ImageView imageView = new ImageView("http://files.softicons.com/download/web-icons/network-and-security-icons-by-artistsvalley/png/16x16/Regular/Friend%20Smiley.png");
// Remove :) from text
text.setText(text.getText().replace(":)"," "));
textFlow.getChildren().addAll(text, imageView);
} else {
textFlow.getChildren().add(text);
}
textField.clear();
textField.requestFocus();
});
Scene scene = new Scene(container, 300, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output
For unicode Emoji support, please visit How to support Emojis

Swing apllication with embedded JavaFX WebView won't play html5 video only sound

In my Swing application I needed support for rendering html. So I embedded a JavaFX WebView in my Swing application. Now on some html pages I use the new html5 -Tag to play a video. This works perfectly on Windows and Linux. But on MacOS I only hear the sound and see a black video frame and the time track in the bottom.
Here is an SSCCE I got from github. I just changed the url to one that contains a html5 video-tag example. Would be great, if you MacOS users could try it and tell me if the same happens on you computer. And of course any idea to fix this is appreciated.
SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.sun.javafx.application.PlatformImpl;
/**
* SwingFXWebView
*/
public class JavaFXTest extends JPanel
{
private Stage stage;
private WebView browser;
private JFXPanel jfxPanel;
private JButton swingButton;
private WebEngine webEngine;
private Object geo;
public JavaFXTest()
{
this.initComponents();
}
public static void main(final String... args)
{
// Run this later:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
final JFrame frame = new JFrame();
frame.getContentPane().add(new JavaFXTest());
frame.setMinimumSize(new Dimension(640, 480));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
private void initComponents()
{
this.jfxPanel = new JFXPanel();
this.createScene();
this.setLayout(new BorderLayout());
this.add(this.jfxPanel, BorderLayout.CENTER);
this.swingButton = new JButton();
this.swingButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(final ActionEvent e)
{
Platform.runLater(new Runnable()
{
#Override
public void run()
{
JavaFXTest.this.webEngine.reload();
}
});
}
});
this.swingButton.setText("Reload");
this.add(this.swingButton, BorderLayout.SOUTH);
}
/**
* createScene Note: Key is that Scene needs to be created and run on
* "FX user thread" NOT on the AWT-EventQueue Thread
*/
private void createScene()
{
PlatformImpl.startup(new Runnable()
{
#Override
public void run()
{
JavaFXTest.this.stage = new Stage();
JavaFXTest.this.stage.setTitle("Hello Java FX");
JavaFXTest.this.stage.setResizable(true);
final Group root = new Group();
final Scene scene = new Scene(root, 80, 20);
JavaFXTest.this.stage.setScene(scene);
// Set up the embedded browser:
JavaFXTest.this.browser = new WebView();
JavaFXTest.this.webEngine = JavaFXTest.this.browser.getEngine();
JavaFXTest.this.webEngine.load("http://camendesign.com/code/video_for_everybody/test.html");
final ObservableList<Node> children = root.getChildren();
children.add(JavaFXTest.this.browser);
JavaFXTest.this.jfxPanel.setScene(scene);
}
});
}
}
Here is a semi-answer, which might help:
The oracle website states:"At this time, Online Installation and Java Update features are not available for 64-bit architectures"
For me this caused lots of problems, because Java seems up to date, but actually isn't. On some machines I could solve the actual issue by just manually updating the Java 64bit VM. On Mac however, the video still isn't playing, only sound.
The 64bit/32bit issue gets even worse, since a double click on a jar might start it in the 64bit JVM, but via console it is started in 32bit JVM. So if you do a "java -version" in console, the output might be "1.7.0 u45 32-bit", but as soon as you start the jar via double click it is started in an outdated 64bit JVM.
So if you ever run in an JavaFX issue (especially with UnsatisfiedLinkError) and you have a 64bit computer, just install the latest 64bit java and hope that it solves the problem.

Images in runnable jar are not working - NullPointer is thrown

I've seen this question all over this website. And I've read almost every response. I feel like I'm doing exactly what is required, but I just can't get it to work! I'm trying to package some images into a Runnable Jar so that my program is self-contained. When I run the code in Eclipse, it works as intended. But when I use the executable Jar, the program will not launch. It gives me a NullPointerException on the line where I create the image. The files are in a folder called Resources in the source folder of the project. Here is the code. It is incomplete because this is just a test program that I've been trying to get working.
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class testgui extends JFrame{
private static JLabel label = new JLabel();
private static testgui gui = new testgui();
private static ArrayList<ImageIcon> sprites;
public static void main(String[] args) {
// TODO Auto-generated method stub
sprites = getImages();
BufferedImage backgroundImage;
try {
backgroundImage = ImageIO.read(new testgui().getClass().getClassLoader().getResource("resources/runescapemap.png"));
gui.setContentPane(gui.new ImagePanel(backgroundImage));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
gui.setLayout(new GridLayout(1,2));
label.setIcon(sprites.get(0));
gui.add(label);
gui.setSize(1000,900);
gui.setVisible(true);
}
private static ArrayList<ImageIcon> getImages(){
ImageIcon autoTalkerLogo = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/autotalker-logo.png"));
ImageIcon meterNormal = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter.png"));
ImageIcon meterSafe = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter-safe.png"));
ImageIcon meterNotSafe = new ImageIcon(new testgui().getClass().getClassLoader().getResource("Resources/meter-notsafe.png"));
ArrayList<ImageIcon> sprites = new ArrayList<ImageIcon>();
sprites.add(autoTalkerLogo);
sprites.add(meterNormal);
sprites.add(meterSafe);
sprites.add(meterNotSafe);
return sprites;
}
class ImagePanel extends JComponent {
private Image backgroundImage;
public ImagePanel(Image image) {
this.backgroundImage = image;
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
}
}
If the folder is genuinely called Resources rather than resources, that could be the problem. While the Windows file system is case-insensitive, jar files aren't.
Try
...getResource("Resources/runescapemap.png")
I note that your later calls to getResource do use Resources rather than resources.
Of course, it could be the other way round - maybe your folder is actually resources, and it's the first call that's okay and the other four should use resources. Either way, it's unlikely that both are correct...

Resources