I am currently having a problem with JFrame and Images. This program uses an Applet then adds it to a JFrame in a different class, so it can be ran as either an Applet or an Application. Currently, the frame holds only a handful of images, and no components. I recently attempted to add a JTextField using absolute positioning (LayoutManger is null) and it works fine, except all the images are removed, leaving me with just a JTextField. Why is this happening? How can I fix it? My code is posted below. Thanks!
The Main Class (Creates the Applet and Images):
package net.xenix.src;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.Timer;
public class XenixMain extends JApplet implements ActionListener
{
private static final long serialVersionUID = 1L;
private static int pixelSize = 2;
public static Dimension size = new Dimension(1600, 900);
public static Dimension pixel = new Dimension(size.width / pixelSize, size.height / pixelSize);
public static String name = "Xenix";
public static final int WIDTH = 1600;
public static final int HEIGHT = 900;
//Finding player Windows name
static String username = System.getProperty("user.name");
public static int secondsCount = 0;
//Shortcut to image directory
public static String imagePath = "C:\\Users\\" + username + "\\Desktop\\Xenix Dev\\Xenix\\resources\\graphics\\";
private static PaintSurface canvas;
public static ImageIcon XenixBackgroundIcon = new ImageIcon(imagePath + "XenixBackground.png");
public static Image XenixBackground = XenixBackgroundIcon.getImage();
public static ImageIcon XenixLogoIcon = new ImageIcon(imagePath + "XenixLogo.png");
public static Image XenixLogo = XenixLogoIcon.getImage();
public static ImageIcon HeartContainerFullIcon = new ImageIcon(imagePath + "HeartContainerFull.png");
public static Image HeartContainerFull = HeartContainerFullIcon.getImage();
public static ImageIcon HeartContainer9Icon = new ImageIcon(imagePath + "HeartContainer9.png");
public static Image HeartContainer9 = HeartContainer9Icon.getImage();
public static ImageIcon HeartContainer8Icon = new ImageIcon(imagePath + "HeartContainer8.png");
public static Image HeartContainer8 = HeartContainer8Icon.getImage();
public static ImageIcon HeartContainer7Icon = new ImageIcon(imagePath + "HeartContainer7.png");
public static Image HeartContainer7 = HeartContainer7Icon.getImage();
public static ImageIcon HeartContainer6Icon = new ImageIcon(imagePath + "HeartContainer6.png");
public static Image HeartContainer6 = HeartContainer6Icon.getImage();
public static ImageIcon HeartContainer5Icon = new ImageIcon(imagePath + "HeartContainer5.png");
public static Image HeartContainer5 = HeartContainer5Icon.getImage();
public static ImageIcon HeartContainer4Icon = new ImageIcon(imagePath + "HeartContainer4.png");
public static Image HeartContainer4 = HeartContainer4Icon.getImage();
public static ImageIcon HeartContainer3Icon = new ImageIcon(imagePath + "HeartContainer3.png");
public static Image HeartContainer3 = HeartContainer3Icon.getImage();
public static ImageIcon HeartContainer2Icon = new ImageIcon(imagePath + "HeartContainer2.png");
public static Image HeartContainer2 = HeartContainer2Icon.getImage();
public static ImageIcon HeartContainer1Icon = new ImageIcon(imagePath + "HeartContainer1.png");
public static Image HeartContainer1 = HeartContainer1Icon.getImage();
public static ImageIcon HeartContainerDepletedIcon = new ImageIcon(imagePath + "HeartContainerDepleted.png");
public static Image HeartContainerDepleted = HeartContainerDepletedIcon.getImage();
public static ImageIcon HealthTextIcon = new ImageIcon(imagePath + "HealthText.png");
public static Image HealthText = HealthTextIcon.getImage();
public static ImageIcon ForwardSlashIcon = new ImageIcon(imagePath + "ForwardSlash.png");
public static Image ForwardSlash = ForwardSlashIcon.getImage();
public Timer timer = new Timer(1000, this);
public void start()
{
timer.setInitialDelay(0);
timer.start();
}
public void stop()
{
timer.stop();
}
public void actionPerformed(ActionEvent e)
{
secondsCount++;
System.out.println(secondsCount);
}
public void init()
{
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
ScheduledThreadPoolExecutor executor =
new ScheduledThreadPoolExecutor(3);
executor.scheduleAtFixedRate(
new AnimationThread(this),
0L, 20L, TimeUnit.MILLISECONDS);
}
}
class AnimationThread implements Runnable
{
JApplet c;
public AnimationThread(JApplet c)
{
this.c = c;
}
public void run()
{
c.repaint();
}
}
class PaintSurface extends JComponent
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape screenDisplay = new Rectangle2D.Float(
450, 175, 700, 500);
g2.setColor(Color.DARK_GRAY);
g2.fill(screenDisplay);
/*
* START TITLE SCREEN CREATION
*/
if(XenixMain.secondsCount > 0)
{
g.drawImage(XenixMain.XenixLogo, 500, 500, this);
}
g.drawImage(XenixMain.XenixBackground, 0, 0, this);
/*
* END TITLE SCREEN CREATION
*/
}
}
JFrame Class (Creates JFrame and adds the Applet):
package net.xenix.src ;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class XenixApplicationWindow extends JFrame
{
private static final long serialVersionUID = 1L;
static XenixMain xenix = new XenixMain();
static ImageIcon xenixIcon = new ImageIcon(XenixMain.imagePath + "XenixIcon.png");
public static void main(String[] args)
{
new XenixApplicationWindow();
}
public XenixApplicationWindow()
{
JFrame frame = new JFrame();
JTextField userInput = new JTextField(15);
JPanel panel1 = new JPanel(null);
frame.add(xenix);
frame.setSize(1600, 900);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setResizable(true);
frame.setIconImage(xenixIcon.getImage());
userInput.setBounds(0, 0, 120, 10);
panel1.add(userInput);
frame.add(panel1);
frame.setContentPane(panel1);
frame.setLocationRelativeTo(null);
frame.setTitle("Xenix");
xenix.init();
xenix.start();
frame.setVisible(true);
}
}
Have a look at this example and see if this helps a bit. For some information on the said topic, please see this link. Let me know, if still thingies are unclear.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class BackgroundExample {
private JTextField tField;
private JButton button;
private CustomPanel contentPane;
private void displayGUI() {
JFrame frame = new JFrame("Background Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new CustomPanel();
contentPane.setLayout(new GridBagLayout());
JPanel componentPanel = new JPanel();
componentPanel.setOpaque(false);
tField = new JTextField("Nothing to display yet...", 20);
button = new JButton("Click me not!");
componentPanel.add(tField);
componentPanel.add(button);
contentPane.add(componentPanel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new BackgroundExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel {
private BufferedImage bImage;
public CustomPanel() {
try {
bImage = ImageIO.read(new URL("http://i.imgur.com/fHiBMwI.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return (bImage != null ? new Dimension(
bImage.getWidth(), bImage.getHeight()) : new Dimension(400, 400));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bImage, 0, 0, this);
}
}
Related
I tried to add an image to my window and make it the same size as the window but the project won't run and no image comes up, when I had the image working before it wouldn't be the size of the screen even thought I used WIDTH and HEIGHT which is what I used for the window.
import javax.swing.*;
public class Main {
public static int WIDTH = 1000;
public static int HEIGHT = 368;
public static JFrame window = new JFrame();
public static void main(String[] args) {
CreateWindow();
}
public static void CreateWindow() {
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setSize(WIDTH, HEIGHT);
BackgroundImage();
window.setVisible(true);
}
public static void BackgroundImage() {
ImageIcon image = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
window.add(image)
image.setSize(WIDTH, HEIGHT);
}
}
Use JLabel to show your image and with getScaledInstance() method you can resize it.
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Main {
public static int WIDTH = 1000;
public static int HEIGHT = 368;
public static JFrame window = new JFrame();
public static void main(String[] args) {
CreateWindow();
}
public static void CreateWindow() {
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setSize(WIDTH, HEIGHT);
BackgroundImage();
window.pack();
window.setVisible(true);
}
public static void BackgroundImage() {
ImageIcon imageIcon = new ImageIcon("C:\\Users\\SamBr\\Pictures\\image.png");
ImageIcon scaledImage = new ImageIcon(
imageIcon.getImage().getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH));
JLabel label = new JLabel();
label.setIcon(scaledImage);
window.add(label);
}
}
im new programming, im trying to get some values from jtextfield and then convert them into int to use them as a paramter to draw a polygon, but im having trouble converting the strings into int, please help me, what is the best way t do this this is my code:
this is where im getting the data from textfield
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Shape;
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;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Transformacion extends JFrame {
Transformacion_R2 grafico= new Transformacion_R2();
public Transformacion()
{
// Use helper methods
createpuntosx();
createpuntosy();
createButton();
xa=puntoFieldx1.getText();
xb=puntoFieldx2.getText();
xc=puntoFieldx3.getText();
xd=puntoFieldx4.getText();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createButton()
{
graficar = new JButton("Grafica");
class PoligonoListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JFrame frame = new JFrame(Transformacion_R2.TITLE);
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
ActionListener listener = new PoligonoListener();
graficar.addActionListener(listener);
}
public void createpuntosx()
{
puntosx = new JLabel("Puntos x: ");
final int FIELD_WIDTH = 4;
puntoFieldx1 = new JTextField(FIELD_WIDTH);
puntoFieldx2 = new JTextField(FIELD_WIDTH);
puntoFieldx3 = new JTextField(FIELD_WIDTH);
puntoFieldx4 = new JTextField(FIELD_WIDTH);
}
public void createpuntosy()
{
puntosy = new JLabel("Puntos y: ");
final int FIELD_WIDTH = 4;
puntoFieldy1 = new JTextField(FIELD_WIDTH);
puntoFieldy2 = new JTextField(FIELD_WIDTH);
puntoFieldy3 = new JTextField(FIELD_WIDTH);
puntoFieldy4 = new JTextField(FIELD_WIDTH);
}
public void createPanel()
{
JPanel northPanel = new JPanel();
northPanel.add(puntosx);
northPanel.add(puntoFieldx1);
northPanel.add(puntoFieldx2);
northPanel.add(puntoFieldx3);
northPanel.add(puntoFieldx4);
northPanel.add(puntosy);
northPanel.add(puntoFieldy1);
northPanel.add(puntoFieldy2);
northPanel.add(puntoFieldy3);
northPanel.add(puntoFieldy4);
add(northPanel,BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
add(centerPanel,BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.add(graficar);
add(southPanel,BorderLayout.SOUTH);
}
private JLabel puntosx;
private JTextField puntoFieldx1;
private JTextField puntoFieldx2;
private JTextField puntoFieldx3;
private JTextField puntoFieldx4;
private JLabel puntosy;
private JTextField puntoFieldy1;
private JTextField puntoFieldy2;
private JTextField puntoFieldy3;
private JTextField puntoFieldy4;
private JButton graficar;
public static String xa;
public static String xb;
public static String xc;
public static String xd;
public static String ya;
public static String yb;
public static String yc;
public static String yd;
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 200;
and this is where i'm converting them into string
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
/** Test applying affine transform on vector graphics */
#SuppressWarnings("serial")
public class Transformacion_R2 extends JPanel{
public static final int CANVAS_WIDTH = 1000;
public static final int CANVAS_HEIGHT = 1200;
public static final String TITLE = "Tranformacion Lineal R2";
//DECLARO PUNTOS DEL POLIGONO
int a=Integer.parseInt (Transformacion.xa);
int b=Integer.parseInt (Transformacion.xb);
int c=Integer.parseInt (Transformacion.xc);
int d=Integer.parseInt (Transformacion.xd);
int[] polygonXs = { a, b, c, d};
int[] polygonYs = { 80, 70, 80, 40};
Shape shape = new Polygon(polygonXs, polygonYs, polygonXs.length);
/** Constructor to set up the GUI components */
public Transformacion_R2() {
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
/** Custom painting codes on this JPanel */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D)g;
AffineTransform saveTransform = g2d.getTransform();
AffineTransform identity = new AffineTransform();
g2d.setTransform(identity);
g2d.setColor(Color.GREEN);
g2d.fill(shape);
//TRANSFORMACIONES
double x = 200.0, y = -500.0;
g2d.translate(x, y);
g2d.rotate(Math.toRadians(30.0));
g2d.scale(10, 9);
g2d.setColor(Color.RED);
g2d.fill(shape);
g2d.setTransform(saveTransform);
}
/** The Entry main method */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(TITLE);
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
thank you for your help
Your xa is always going to be null unless the constructor of Transformacion runs.
In this code constructor and initializations for Transformacion_R2 run before constructor of Transformacion. So make sure you call the constructor of Transformacion before Transformacion_R2. To remove cyclic initalization remove Transformacion_R2 grafico= new Transformacion_R2(); from Transformacion Eg. code could be
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame(TITLE);
Transformacion trns = new Transformacion();
frame.setContentPane(new Transformacion_R2());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
int number = Integer.parseInt(jTextField.getText());
The typical method of doing it can be found at
How to convert a String to an int in Java?
which you seem to be doing properly. What issues are you running into, more specifically?
If the jtextField is not set, you need to handle the possiblity of error.
int number;
try {
number = Integer.parseInt(jTextField.getText());
} catch(NumberFormatException e) {
number = 0; // Handle the error or give a default value
}
The image isn't being painted when this is run with WordGen, how do i fix this?
When I run this without wordgen I can get the image to appear. I'm not sure what i'm doing wrong since i'm not getting any errors.
Any help is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tfot extends JComponent{
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
JFrame window = new JFrame("Window");
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("Pictures/background1.png"), 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text","hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}
First...
Don't load resources or perform long running tasks within the paint methods, these may be called a number of times in quick succession. Instead, load the images before hand and paint them as needed...
public Tfot() {
setLayout(new BorderLayout());
try {
background = ImageIO.read(new File("pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, this);
}
}
Generally, you are discouraged from overriding paint and instead should use paintComponent, lots of reasons, but generally, this is where the background is painted...
Second...
You need to add Tfot to something that is displayable, otherwise it will never be painted
JFrame window = new JFrame("Window");
window.setContentPane(new Tfot());
window.add(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
Thrid...
JPanel by default is not transparent, you need to set it's opaque property to false
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
//...
JPanel content = new JPanel();
content.setOpaque(false);
Then it will allow what ever is below it to show up (ie, the background image)
Take a look at Painting in AWT and Swing, Performing Custom Painting and Reading/Loading an Image for more details
Fourth...
You need to learn the language basics for embarking on advance topics like GUI and custom painting, without this basic knowledge, this topics will bite you hard.
You need to declare background as a instance field of the class Tfot
private BufferedImage background;
public Tfot() {
Updated - Fully runnable example
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
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.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Tfot extends JComponent {
private static final long serialVersionUID = 1L;
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI(args);
}
});
}
public static void showGUI(String[] args) {
JPanel displayPanel = new JPanel();
displayPanel.setOpaque(false);
JButton okButton = new JButton("Did You Know?");
okButton.setFont(new Font("Times", Font.TRUETYPE_FONT, 100));
final JLabel jLab = new JLabel();
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jLab.setText(wordGen());
}
});
JPanel content = new JPanel();
content.setOpaque(false);
content.setLayout(new BorderLayout());
content.add(displayPanel, BorderLayout.CENTER);
content.add(okButton, BorderLayout.SOUTH);
content.add(jLab, BorderLayout.NORTH);
Tfot tfot = new Tfot();
tfot.setLayout(new BorderLayout());
tfot.add(content);
JFrame window = new JFrame("Window");
window.setContentPane(tfot);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(800, 600);
window.setLocation(400, 300);
window.setVisible(true);
}
private BufferedImage background;
public Tfot() {
try {
background = ImageIO.read(new File("Pictures/background1.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, this);
}
public static String wordGen() {
String[] wordListOne = {"generic text", "hi",};
int oneLength = wordListOne.length;
int rand1 = (int) (Math.random() * oneLength);
String phrase = wordListOne[rand1] + " ";
return phrase;
}
}
I have one class Names and it has a JTextField. I am trying to place getText from this textfield and save it in the variable nameString1. I then want the other class Game to call Names and place the string collected from ``the JTextField onto a label. For some reason it is not displaying. Please let me know if there are any rookie errors, I am only year 10.
Names
package com.aqagame.harrykitchener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Names
{
private JLabel player1Label;
private JTextField player1Input;
private JButton nextButton;
public String nameString1;
public Names()
{
final JFrame window = new JFrame("Player 1 username");
JPanel firstPanel = new JPanel(new GridLayout(3,2));
player1Label = new JLabel("Player 1");
player1Input = new JTextField();
nextButton = new JButton("Next");
firstPanel.add(player1Label);
firstPanel.add(player1Input);
firstPanel.add(nextButton);
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nameString1 = player1Input.getText();
System.out.print(nameString1);
Names2 names2Call = new Names2();
window.dispose();
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(250, 150);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Names();
}
});
}
}
Game
package com.aqagame.harrykitchener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Game
{
private JLabel player1Str, player2Str;
public Game()
{
JFrame window = new JFrame ("Main Game");
JPanel drawPanel = new JPanel(new GridLayout(3, 1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() / 4;
int height = getHeight() / 11;
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
}
};
Names namesCall2 = new Names();
player1Str = new JLabel(namesCall2.nameString1);
drawPanel.add(player1Str);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(drawPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
}
The problem is that you are setting the label without getting the textfield text. The JLabel on your Game wont change by the time you click the button..
Okie I made some change in you classes What I did is that I maid an interface which will be called when your button is pressed
Here is the interface:
public interface Lawl {
public void changename(String name);
}
I then implemented this interface to the game:
public class Game implements Lawl
{
private JLabel player1Str, player2Str;
JPanel drawPanel;
Names namesCall2;
public Game()
{
JFrame window = new JFrame ("Main Game");
drawPanel = new JPanel(new GridLayout(3, 1))
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
int width = getWidth() / 4;
int height = getHeight() / 11;
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
for(int i = 0; i<4; i++)
{
g.drawLine(i * width, 0, i * width, 700);
}
}
};
// Names namesCall2 = new Names(this);
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
namesCall2 = new Names(Game.this);
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(drawPanel);
window.setSize(700, 600);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Game();
}
});
}
#Override
public void changename(String name) {
System.out.println("I am clicked");
player1Str = new JLabel(name);
drawPanel.add(player1Str);
drawPanel.revalidate();
}
}
In the names class:
public class Names
{
private JLabel player1Label;
private JTextField player1Input;
private JButton nextButton;
public String nameString1;
public Names(){}
public Names(final Lawl game)
{
final JFrame window = new JFrame("Player 1 username");
JPanel firstPanel = new JPanel(new GridLayout(3,2));
player1Label = new JLabel("Player 1");
player1Input = new JTextField();
nextButton = new JButton("Next");
firstPanel.add(player1Label);
firstPanel.add(player1Input);
firstPanel.add(nextButton);
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nameString1 = player1Input.getText();
System.out.print(nameString1);
game.changename(nameString1);
// Names2 names2Call = new Names2();
window.dispose();
}
});
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(firstPanel);
window.setSize(250, 150);
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
How it works??
I created an interface and implemented it to the game class then pass the reference of the interface to the Names class which will then be called when button is clicked..
when it is called game.changename(nameString1);by the button clicked it will then be called on the game class as you could see there is an method from the implemented inteface in the game class that will be called when you click the button..
If you want to chain data dont create a new Main thread to just execute a new Window.. just use the one I did in the code..
replace
public final static JTextField player1Input;
instead of
private JTextField player1Input;
import javax.swing.*;
import java.awt.*;
public class Main
{
public static void main(String[] args)
{
//load the card image from the gif file.
final ImageIcon cardIcon = new ImageIcon("cardimages/tenClubs.gif");
//create a panel displaying the card image
JPanel panel = new JPanel()
{
//paintComponent is called automatically by the JRE whenever
//the panel needs to be drawn or redrawn
public void paintComponent(Graphics g) {
super.paintComponent(g);
cardIcon.paintIcon(this, g, 20, 20);
}
};
//create & make visible a JFrame to contain the panel
JFrame window = new JFrame("Title goes here");
window.add(panel);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBackground(new Color(100, 200, 102));
window.setPreferredSize(new Dimension(200,200));
window.pack();
window.setVisible(true);
}
}
I am trying to make a java project that will display all 52 cards on a window. I have the window working but I cant get a card to appear on the window.
I am using eclipse for OSX, inside the project src file I have a (default package) container with my Main.java file. Then I have my cardimages folder in the same src file.
How can I get the image to show in the window?
You should try to get the image as a URL, as a resource again using the Class method getResource(...). For example, test this:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class DefaultFoo {
public static void main(String[] args) throws IOException {
String resource = "/cardimages/tenClubs.gif";
URL url = Class.class.getResource(resource);
BufferedImage img = ImageIO.read(url);
Icon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
}
}
Also, don't use the default package like you're doing. Put your class into a valid package.
Then try something like this:
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class PlayWithImages extends JLayeredPane {
private static final String RESOURCE = "/cardimages/tenClubs.gif";
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private static final int CARD_COUNT = 8;
public PlayWithImages() throws IOException {
URL url = getClass().getResource(RESOURCE);
BufferedImage img = ImageIO.read(url);
Icon icon = new ImageIcon(img);
for (int i = 0; i < CARD_COUNT; i++) {
JLabel label = new JLabel(icon);
label.setSize(label.getPreferredSize());
int x = PREF_W - 20 - i * 40 - label.getWidth();
int y = 20;
label.setLocation(x, y);
add(label);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
PlayWithImages mainPanel = null;
try {
mainPanel = new PlayWithImages();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("PlayWithImages");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}