Trying to print image without frame - java

public class Main{
public static void main(String []args){
JLabel c=new JLabel();
c.setIcon(new ImageIcon("picture.png"));
JFrame frame = new JFrame();
frame.setBackground(Color.WHITE);
frame.setUndecorated(true);
frame.getContentPane().add(c);
frame.pack();
BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = bi.createGraphics();
c.print(graphics);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
graphics.dispose();
frame.dispose();
}
}
Hi all! I am simply trying to print an image without any frame onto the screen. This code should, I think, print the image to the screen; wait two seconds and then dispose of it. What am I doing wrong?
B.T.W I get no errors whatsoever, the program just stays alive for 2 seconds then dies.

Your image is in your JLabel. Why should it be printed on your screen if the frame where JLabel is is not showing?
You are already setting the frame undecorated. Setting visible on the frame, will work.

You don't need the Graphics part at the end and also you forgot to call setVisible(true);
public class Main{
public static void main(String []args){
JLabel c=new JLabel();
c.setIcon(new ImageIcon("picture.png"));
JFrame frame = new JFrame();
frame.setBackground(Color.WHITE);
frame.setUndecorated(true);
frame.getContentPane().add(c);
frame.pack();
frame.setVisible(true);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
frame.dispose();
}
}

Related

Why does the image not show up on the JPanel?

I want to draw an image on a JPanel which is displayed on a JFrame. I tested the paint method without the frame and it seemed to work, but as soon as I added the image on the frame it won't get shown. Instead I only see a very small square which displays a small area of the image.
Here's my code so far:
TestFrame class:
public class TestFrame extends JFrame {
private JFrame frame = new JFrame();
private JPanel jp = new JPanel();
public MyFrame() {
frame.setTitle("test");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new BorderLayout());
jp.setBackground(Color.YELLOW);
frame.add(jp, BorderLayout.CENTER);
jp.add(new DrawPanel());
jp.repaint();
frame.setVisible(true);
}
}
DrawPanel class:
public class DrawPanel extends JPanel {
private BufferedImage img;
public DrawPanel() {
try {
img = ImageIO.read(getClass().getResourceAsStream("/resources/heart.jpg"));
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
}
Try with this in the method paintComponent():
g.drawimage(img.getImage(), 0, 0, null);

Paint component not being called

I'm trying to code a little maze runner program, and have run into some trouble relating to the paintComponent(). I have gone through the debug and for some reason my paintComponent() is never called, even with the repaint() which is being called by my timer.
private void jpanelinit() {
JPanel Background = new JPanel (new BorderLayout());
JPanel Menu = new JPanel (new BorderLayout());
JPanel Maze = new JPanel (new GridLayout(arow, acolumn));
Background.setPreferredSize(new Dimension(850,850));
Menu.setPreferredSize(new Dimension(850, 100));
Maze.setPreferredSize(new Dimension(850,750));
frame.add(Background);
comboboxinit();
Background.add(Menu, BorderLayout.NORTH);
Background.add(Maze, BorderLayout.SOUTH);
Menu.add(Startpause, BorderLayout.WEST);
Menu.add(Reset, BorderLayout.EAST);
Menu.add(Intervalpick, BorderLayout.CENTER);
Intervalpick.setVisible(true);
Intervalpick.addActionListener(this);
Startpause.setVisible(true);
Startpause.addActionListener(this);
Reset.setVisible(true);
Reset.addActionListener(this);
Maze.setVisible(true);
}
private static void frameinit() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(850,850);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
Those are my frame and jpanel init methods.
#Override
public void paintComponent(Graphics g){
System.out.println("Entered Graphics");
super.paintComponent(g);
g.drawImage(biWall,0,100,850,750, this );
}
This is my paintComponent, the image is indeed buffered and has been stored.
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Intervalpick)
timecheck(); //Checks if the time was changed
if(e.getSource()==Startpause||e.getSource()==Reset)
buttoncheck(e); //Checks if the buttons were pressed
if(t.isRunning())
mazeupdate();
}
private void mazeupdate() {
repaint();
}
That is my actionPerformed which is called with my timer which is set to a 5 sec interval at default.
public class mazerunner extends JPanel implements ActionListener {
static JButton Startpause = new JButton("Start");
static JButton Reset = new JButton("Reset");
static JComboBox Intervalpick= new JComboBox();
static JFrame frame=new JFrame ("Maze Runner");
static int arow=0, acolumn=0, icurrenttime=5000;
static boolean gameplaying=false;
static Timer t;
static BufferedImage biWall, biFloor, biMouse, biCheese;
public static void main(String[] args) {
mazerunner mr= new mazerunner();
filereader(); //Reads the file
imagebuffer(); //Buffers the images
mr.jpanelinit(); //Inits the gui
frameinit(); //Inits the frame
mr.timerinit(); //Inits the timer
}
private static void imagebuffer() {
try{
biWall=ImageIO.read(new File("cobblewall.jpg"));
}
catch(IOException e){}
try{
biFloor=ImageIO.read(new File("woodenfloor.jpg"));
}
catch(IOException e){}
try{
biCheese=ImageIO.read(new File("chest_cheese.jpg"));
}
catch(IOException e){}
try{
biMouse=ImageIO.read(new File("lara_mouse.jpg"));
}
catch(IOException e){}
}
private void timerinit() {
t=new Timer(icurrenttime,this);
}
private void jpanelinit() {
JPanel Background = new JPanel (new BorderLayout()); //Inits all the JPanels
JPanel Menu = new JPanel (new BorderLayout());
JPanel Maze = new JPanel (new GridLayout(arow, acolumn));
Background.setPreferredSize(new Dimension(850,850)); //Sets the size of the panels
Menu.setPreferredSize(new Dimension(850, 100));
Maze.setPreferredSize(new Dimension(850,750));
frame.add(Background); //Adds background into the frame
comboboxinit();
Background.add(Menu, BorderLayout.NORTH); //Adds the other panels into the background
Background.add(Maze, BorderLayout.SOUTH);
Menu.add(Startpause, BorderLayout.WEST); //Adds the menu's components into the menu panel
Menu.add(Reset, BorderLayout.EAST);
Menu.add(Intervalpick, BorderLayout.CENTER);
Intervalpick.setVisible(true); //Sets the components to visible and adds actionlistener
Intervalpick.addActionListener(this);
Startpause.setVisible(true);
Startpause.addActionListener(this);
Reset.setVisible(true);
Reset.addActionListener(this);
Maze.setVisible(true);
}
private static void comboboxinit() {
for(int a=5;a<=30;a=a+5){ //Sets the text inside the combobox
Intervalpick.addItem(a+" Seconds");
}
DefaultListCellRenderer dlcr = new DefaultListCellRenderer(); //Centers the text inside the combobox
dlcr.setHorizontalAlignment(DefaultListCellRenderer.CENTER);
Intervalpick.setRenderer(dlcr);
}
private static void frameinit() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Inits the jframe
frame.setResizable(false);
frame.setSize(850,850);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
private static void filereader() {
try{
FileReader fr=new FileReader("maze.txt");
BufferedReader br= new BufferedReader(fr);
String LineIn=br.readLine();
int num, row=0;
arow=Integer.parseInt(LineIn);
LineIn=br.readLine();
acolumn=Integer.parseInt(LineIn);
int Maze[][]=new int[arow][acolumn]; //inits the maze itself
LineIn=br.readLine();
do{ //stores the maze from the file into the arrray
int collumn=0;
StringTokenizer tokens=new StringTokenizer(LineIn);
while (tokens.hasMoreTokens()){
num=Integer.parseInt(tokens.nextToken());
Maze[row][collumn]=num;
collumn++;
}
LineIn=br.readLine();
row++;
}while(LineIn!=null);
br.close();
fr.close();
}
catch(FileNotFoundException e){
System.err.println("file not found");
}
catch(IOException e){
System.err.println("read failed");
}
}
#Override
public void paintComponent(Graphics g){
System.out.println("Entered Graphics");
super.paintComponent(g);
g.drawImage(biWall,0,100,850,750, this );
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Intervalpick)
timecheck(); //Checks if the time was changed
if(e.getSource()==Startpause||e.getSource()==Reset)
buttoncheck(e); //Checks if the buttons were pressed
if(t.isRunning())
mazeupdate();
}
private void mazeupdate() {
repaint();
}
private void buttoncheck(ActionEvent e) {
if(e.getSource()==Startpause){ //Starts and pauses the simulation
if(gameplaying==false){
gameplaying=true;
t.start();
Startpause.setText("Pause");
}
else if(gameplaying==true){
gameplaying=false;
t.stop();
Startpause.setText("Start");
}
}
else if(e.getSource()==Reset){ //Resets the maze to the original maze
if(t.isRunning())
t.stop();
gameplaying=false;
Startpause.setText("Start");
filereader();
// t.repaint();
}
}
private void timecheck() {
int boxtime= Integer.parseInt(((String) Intervalpick.getSelectedItem()).split(" ")[0])*1000; //Turns Intervalpick into a milisecond amount
if(boxtime!=icurrenttime){ //Checks if the selected delay is equal to the actual delay
boolean gamerunning=false;
icurrenttime=boxtime;
if(t.isRunning()){ //Stops timer if running
t.stop();
gamerunning=true;
}
t.setDelay(icurrenttime); //Changes delay
if(gamerunning==true) //If timer was running it turns it back on
t.start();
}
}
}
That is my full code if you're interested. My question is why I can't get the image to draw onto the Maze panel.
paintComponent won't be called for three basic reasons.
The component isn't attached to a valid native peer (ie, it's not attached to a window directly or indirectly that is visible on the screen)
or it doesn't have a size greater than 0x0
or it's not visible...
Skimming through your code, I can't find anywhere an instance of mazerunner is actually added to the frame...
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Thread not wanting to work

If so someone could explain how to get this to paint and why it isn't painting that would be awesome!!!
public class Main extends JPanel implements Runnable {
public void run() {
System.out.println("g");
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(50, 50, 200, 200);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Physics!");
frame.setSize(500, 500);
frame.setBackground(Color.BLUE);
frame.setVisible(true);
Main physics = new Main();
Thread t = new Thread(physics);
t.start();
}
}
You never add physics to the JFrame
Main physics = new Main();
JFrame frame = new JFrame("Physics!");
frame.add(physics);
Side Note
When painting on JPanel override getPreferredSize() so the panel has a preferred size, then you can just pack() the frame, as you should be doing, instead of setting it's size
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
...
frame.pack();
// frame.setSize(500, 500);
Also, paintComponent should be protected not public
Also see Initial Threads for running Swing apps on the Event Dispatch Thread
You have to add the JPanel to the JFrame:
JFrame frame = new JFrame("Physics!");
Main physics = new Main();
Thread t = new Thread(physics);
t.start();
frame.setContentPane(physics); // Add it like this
frame.setSize(500, 500);
frame.setBackground(Color.BLUE);
frame.setVisible(true);
Try putting t.join() in the main method after t.start() .. Your main method should wait for the thread to finish.

JFrame not displaying contents

I know this question has been asked a lot, but ive read through about 10 different articles, all reccomending to different things such as "frame = this" nad frame.add(d)" Im not sure why, but none of these have been working. I typed something and the program worked fine, except the Jbuttons wouldnt show up until i clicked on the JFrame a few times. After some tweaking of that code, im back to the start. Now i just get a error:
Exception in thread "main" java.lang.NullPointerException
at Guis.Dynamic_JFrame.<init>(Dynamic_JFrame.java:37)
at Guis.Dynamic_JFrame.main(Dynamic_JFrame.java:46)
Heres my code:
public class Dynamic_JFrame extends JFrame{
static JFrame frame;
Graphics g;
Handler handler = new Handler();
JButton red = new JButton();
JButton green = new JButton();
JButton orange = new JButton();
public Dynamic_JFrame(){
red.setText("RED");
green.setText("GREEN");
orange.setText("orange");
add(green);
add(red);
add(orange);
red.addActionListener(handler);
green.addActionListener(handler);
orange.addActionListener(handler);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setPreferredSize(new Dimension(500,500));
frame.setMaximumSize(new Dimension(500,500));
frame.setMinimumSize(new Dimension(500,500));
frame.setLayout(new FlowLayout());
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class Handler implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource()==red){
getContentPane().setBackground(Color.RED);
}
if(e.getSource()==green){
getContentPane().setBackground(Color.GREEN);
}
if(e.getSource()==orange){
getContentPane().setBackground(Color.ORANGE);
}
}
}
}
New code, Minor Changes. Program works as intended except for the buttons not updating until i click where they should be:
JFrame frame;
public Dynamic_JFrame(){
frame = new JFrame();
frame = this;
red.setText("RED");
green.setText("GREEN");
frame.add(green);
frame.add(red);
frame.setVisible(true);
}
public static void main(String[] args){
Dynamic_JFrame d = new Dynamic_JFrame();
d.frame.setPreferredSize(new Dimension(500,500));
d.frame.setMaximumSize(new Dimension(500,500));
d.frame.setMinimumSize(new Dimension(500,500));
d.frame.setLocationRelativeTo(null);
d.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.frame.setLayout(new FlowLayout());
}
A number of things...
Firstly, Dynamic_JFrame extends from JFrame so I don't know why you've then gone and create another frame...
Secondly, when Dynamic_JFrame calls frame.setVisible in the constructor, frame is null as it has not being initialised.
From my perspective, the simplest solution would be to extend Dynamic_JFrame from something like JPanel instead and simply add it to an instance of JFrame
For example...
public class Dynamic_JFrame extends JPanel {
static JFrame frame;
// Not sure that this is a good idea...
Graphics g;
//...
public Dynamic_JFrame(){
// Don't use this...
//frame.setVisible(true);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
Dynamic_JFrame d = new Dynamic_JFrame();
frame = new JFrame("Changing colors");
frame.setLayout(new FlowLayout());
frame.add(d);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}

Not able to repaint in java

I am not able to dynamically repaint() inside the Jframe.
public static BufferedImage createBufferedImage(BufferedImage image)
{
ColorModel cm = image.getColorModel();
boolean premultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = image.copyData(image.getRaster());
return new BufferedImage(cm, raster, premultiplied, null);
}
public static void main(String[] args) {
BufferedImage img = new BufferedImage(old_width_i, old_height_i, BufferedImage.TYPE_INT_RGB);
img=createBufferedImage(img_white_screen);
JFrame frame=new JFrame();
JLabel label = new JLabel(new ImageIcon(img));
frame.getContentPane().add(label, BorderLayout.WEST);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
img.flush();
img=createBufferedImage(img_black_screen);
// frame.removeAll();
// frame.revalidate();
// label.removeAll();
// label = new JLabel(new ImageIcon(img));
// frame.getContentPane().add(label, BorderLayout.WEST);
frame.repaint();
}
It basically, creates a screen with the first assignment to the "img" (i.e. img_white_screen) variable and does not change to the second assignment i.e. img_black_screen
don't to use Thread.sleep(1000);, this code line lock Event Dispatch Thread,
no idea for why reason you need to pause code execution for one second, use Swing Timer instead
for showing the Image in Java to use
XxxImage as Icon /IconImage to JLabel
paintComponent() for JComponent or JPanel
don't paint XxxImage or Icon / ImageIcon directly to the JFrame, use JPanel / JComponent or JLabel

Categories

Resources