Why is the background not displaying? - java

I tried this code and all it was showing was the text. The Main script is:
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Main extends JFrame{
public static void main(String[] args) {
DisplayMode dm = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
Main m = new Main();
m.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial",Font.PLAIN,24));
Screen s = new Screen();
try {
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
s.RestoreScreen();
}
}
public void paint(Graphics g){
g.drawString("hello", 200, 200);
}
}
The other screen class is:
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JFrame;
public class Screen {
private GraphicsDevice gc;
public Screen(){
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
gc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window){
window.setUndecorated(true);
window.setResizable(false);
gc.setFullScreenWindow(window);
if (dm != null && gc.isDisplayChangeSupported()){
try{
gc.setDisplayMode(dm);
}catch(Exception ex){}
}
}
public Window getFullScreenWindow(){
return gc.getFullScreenWindow();
}
public void RestoreScreen(){
Window w = gc.getFullScreenWindow();
if(w != null){
w.dispose();
}
gc.setFullScreenWindow(null);
}
}
My code is word for word to a tutorial I watched:
https://thenewboston.com/videos.php?cat=30&video=17934
and his worked. Also, when I switch it to 16 bit graphics, the paint method does not even work. Please Help!

In your class Main, in public void run type:
Screen s = new Screen();
try {
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
s.RestoreScreen();
}

You forgot to set the JFrame visible
In your fullscreen method add this
window.setVisible(true);

Related

Java's drawImage method doesn't show the image

I'm just beginner at Java Programming and am using NetBeans. The code below runs and No Error is displayed but no image is seen! This image is in the "frame" package beside this two classes.
package frame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Screen extends JPanel{
private BufferedImage image;
public Screen(){
try {
System.out.println("OK");
image = ImageIO.read(getClass().getResourceAsStream("phantomPDF.png"));
} catch(IOException e) {
e.printStackTrace();
}
repaint();
}
public void paint(Graphics g){
g.drawImage(image, 100, 100, null);
System.out.println("Yes");
}
}
and this is my frame and main method :
package frame;
import java.awt.GridLayout;
import javax.swing.*;
public class Frame extends JFrame{
Screen s;
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 600);
setResizable(false);
setTitle("Graphics");
setVisible(true);
init();
}
public void init(){
setLocationRelativeTo(null);
setLayout(new GridLayout(1, 1, 0, 0));
s = new Screen();
add(s);
}
public static void main(String[] args){
new Frame();
}
}
I had to put "try - catch" statement into "paint" class so that works fine now ... but why should i do that?

Screen not created for drawstring text to display

I am working on Java Game Development Tutorials given on buckysroom.org. I am creating a Screen class, which allows me to go full screen. Then, when I try to paint it with text, the screen does not appear, and only the text is shown on my working window (Eclipse) If I comment out the paint method or make it paintComponent, the red screen appears, but without any text. Can anyone help me on how to deal with this?
The Screen class:
import java.awt.*;
import javax.swing.JFrame;
public class Screen {
private GraphicsDevice vc;
public Screen() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
vc.setFullScreenWindow(window);
if (dm != null && vc.isDisplayChangeSupported()) {
try {
vc.setDisplayMode(dm);
} catch (Exception ex) {
}
}
}
public Window getFullScreenWindow() {
return vc.getFullScreenWindow();
}
public void restoreScreen() {
Window w = vc.getFullScreenWindow();
if (w != null) {
w.dispose();
}
vc.setFullScreenWindow(null);
}
}
This is the class where I call it:
import java.awt.*;
import javax.swing.JFrame;
public class bucky extends JFrame {
public static void main(String[] args) {
DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
bucky m = new bucky();
m.run(dm);
}
public void run(DisplayMode dm) {
this.getContentPane().setBackground(Color.RED);
setForeground(Color.BLACK);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try {
s.setFullScreen(dm, this);
try {
Thread.sleep(5000);
} catch (Exception ex) {
}
} finally {
s.restoreScreen();
}
}
public void paint(Graphics g) {
g.drawString("This is awesome", 200, 200);
}
}
My suspicion is that the Thread.sleep is cause the Event Dispatching Thread to be put to sleep, preventing it from processing any paint events (or any other kind of events for that matter) and/or the paint method of the JFrame is not an appropriate method for performing paint in (generally it's not for a number of reasons)...
Instead, you should consider using something like javax.swing.Timer which you can use to set up an alarm for some time in the future and it will call you back.
You should also consider using something like a JPanel to perform your custom painting on, for example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class FullScreenTest {
public static void main(String[] args) {
new FullScreenTest();
}
public FullScreenTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TestPane());
DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
Screen.setFullScreen(null, frame);
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Screen.restoreScreen();
}
});
timer.start();
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setFont(new Font("Arial", Font.PLAIN, 24));
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g.drawString("This is awesome", 200, 200);
g2d.dispose();
}
}
public static class Screen {
public static GraphicsDevice getGraphicsDevice() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
return env.getDefaultScreenDevice();
}
public static void setFullScreen(DisplayMode dm, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
GraphicsDevice gd = getGraphicsDevice();
gd.setFullScreenWindow(window);
if (dm != null && gd.isDisplayChangeSupported()) {
try {
gd.setDisplayMode(dm);
} catch (Exception ex) {
}
}
}
public static Window getFullScreenWindow() {
GraphicsDevice gd = getGraphicsDevice();
return gd.getFullScreenWindow();
}
public static void restoreScreen() {
GraphicsDevice gd = getGraphicsDevice();
Window w = gd.getFullScreenWindow();
if (w != null) {
w.dispose();
}
gd.setFullScreenWindow(null);
}
}
}
Take a look at:
Concurrency in Swing
How to Use Swing Timers
Performing Custom Painting
For more details...
Also, because of the type of work it's doing, Screen could also be a fully static class. It maintains no contextual information and simply provides utility functionality - IMHO.
If you needed one for each GraphicsDevice, that would be another story ;)

Jbutton acction listener

I am trying to create a form. there is a button that when clicking the button, a photo which is specified would appear. my problem is, when I click the button, the picture pops up and if the cursor passes the form boundary, the image disappears. here is my code:
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SeamCarving extends JFrame
{
public static void main(String[] args) throws IOException {
final BufferedImage input = ImageIO.read(new File("path"));
final BufferedImage[] toPaint = new BufferedImage[]{input};
final Frame frame = new Frame("Seams") {
#Override
public void update(Graphics g) {
final BufferedImage im = toPaint[0];
if (im != null) {
g.clearRect(0, 0, getWidth(), getHeight());
g.drawImage(im, 0, 0, this);
}
}
};
frame.setSize(input.getWidth(), input.getHeight());
frame.setVisible(true);
frame.add(startButton);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedImage out = input;
out = deleteVerticalSeam(out);
toPaint[0] = out;
frame.repaint();
System.out.println("Do Something Clicked");
}
});
}
}
Don't override update, this isn't how painting is achieved in Swing. Attempting to paint directly to a top level container like JFrame is problematic at best.
Instead, start with a JPanel and use it's paintComponent method instead. Make sure you call super.paintComponent as well.
In fact, you could probably just use a JLabel to display the image instead.
Take a look at;
Performing Custom Painting
How to use labels
For more details
Updated with example
I still think a JLabel would be simpler solution, but what do I know.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SeamCarving {
public static void main(String[] args) {
new SeamCarving();
}
public SeamCarving() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage input;
private BufferedImage[] toPaint;
public TestPane() {
try {
input = ImageIO.read(new File("C:\\hold\\thumbnails\\2005-09-29-3957.jpeg"));
toPaint = new BufferedImage[1];
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedImage out = input;
out = input; //deleteVerticalSeam(out);
toPaint[0] = out;
repaint();
System.out.println("Do Something Clicked");
}
});
add(startButton);
}
#Override
public Dimension getPreferredSize() {
return input == null ? new Dimension(400, 400) : new Dimension(input.getWidth(), input.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (toPaint[0] != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(input, 0, 0, this);
g2d.dispose();
}
}
}
}
The problem with overriding update is the paint subsystem can choose to avoid calling and end up calling paint directly, circumventing your painting.
Painting also involves painting child components (like your button) and borders, which you've conveniently discarded by not calling super.update.

KeyListener Java

I am trying to use KeyListener in my code.... But it's not working, the KeyListener not responding I think...
If you guys see anything wrong please tell me. I don't know why it's not working.
Thanks in advance.
Here is the code.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Main extends JFrame {
static void drawFrame(JFrame frame) {
frame.setSize(610, 805);
frame.setLocation(145, 15);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame frame = new JFrame("PacMan");
drawFrame(frame);
MyPanel panel = new MyPanel();
panel.setBounds(00, 00, 610, 800);
frame.setLayout(null);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(panel);
}
}
MyPanel Class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyPanel extends JPanel implements KeyListener {
private int xpac = 285, ypac = 570;
public MyPanel() {
this.requestFocus();
this.requestFocusInWindow();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawMap1(g);
drawPacman(g);
addKeyListener(this);
}
void drawMap1(Graphics g) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("pacmap1.png"));
} catch (IOException e) {
System.out.println("Can't find the Image.");
}
setBackground(Color.BLACK);
g.drawImage(image, 0, 0, null);
}
void drawPacman(Graphics g) {
int x = xpac, y = ypac;
BufferedImage image = null;
try {
image = ImageIO.read(new File("pacright.png"));
} catch (IOException e) {
System.out.println("Can't find the Image.");
}
g.drawImage(image, x, y, null);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
}
You should just comment out the addKeyListener in the MyPanel class and do this in the Main class after you instantiate the MyPanel:
frame.addKeyListener(panel);
You should put the this.addKeyListener(this); in your MyPanel class constructor, not the paintComponent method.
Please always use a KeyBindings for such Tasks. See: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
As a little tip, I would recommend you to implement KeyListener as an AnonymousClass.

java - how to know if a window of an external program is open

I've some code that launch an external program (VLC) do some stuff and close the external program (VLC).
The problem is that I'm unable to know if VLC has been opened or it's still loading, is there any way in Java to know if the window of VLC has been opened?
EDIT:
here is the code
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class myClass extends JDialog {
public Dimension dim;
public Process pr;
public myClass(final JFrame parent, String title, String message) {
super(parent, title, true);
try {
Runtime rt = Runtime.getRuntime();
pr = rt.exec("C:\\Programmi\\VideoLAN\\VLC\\vlc.exe dshow:// --dshow-vdev=\"TridVid Capture\" --dshow-video-input=1 -Ihttp");
Thread.sleep(500); //this is a workaround
}
catch (Exception e) {
System.out.println(e.toString());
}
if (parent != null) {
Toolkit toolkit = Toolkit.getDefaultToolkit ();
dim = toolkit.getScreenSize();
Dimension parentSize = parent.getSize();
Point p = parent.getLocation();
setBounds(p.x + parentSize.width / 4, p.y + parentSize.height / 4, dim.width, dim.height);
}
JPanel messagePane = new JPanel();
Image image = new ImageIcon("targa_prova.jpg").getImage();
ImagePanel panel = new ImagePanel(image.getScaledInstance(dim.width, dim.height, Image.SCALE_SMOOTH));
messagePane.add(new JLabel(message));
getContentPane().add(panel);
Timer timer = new Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
pr.destroy();
parent.setVisible(false);
parent.dispose();
}
});
timer.setRepeats(false);
timer.start();
try {
Image backgroundImage = javax.imageio.ImageIO.read(new File("targa_prova.jpg"));
messagePane.paintComponents(backgroundImage.getGraphics());
}
catch (Exception e) {
System.out.println(e.toString());
}
setVisible(true);
}
public static void main(String[] a) {
new myClass(new JFrame(), "Configuring Cam", "Configurazione della telecamera in corso...\nAttendere.");
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
The above code launch vlc, open a dialog that cover the vlc window, than close vlc and the dialog, now i get it with delays, but it's horrible and could not work on some slow computers.

Categories

Resources