How do I set an image to a background - java

I'm trying to create a simple JFrame with the content pane JPanel. I want to know how to set an IMAGE as a background. I know that a lot of people have a already asked this, but I get unresolved compilation errors whenever I try.
In the end, I created a whole new class in my class, but that had errors too.
How do I do this? Please help.
package menu;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import models.AskTheAdmiralFrame;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
/**
*
* #author Russell
*
*/
public class HistoraskMenu extends JFrame {
private static final long serialVersionUID = 8106152174535131551L;
private static JPanel panel;
private JButton ATA = new JButton("Ask The Admiral");
public Color oldPaper = new Color(255, 230, 179);
private JLabel label = new JLabel();
private final JLabel label_1 = new JLabel("");
private final ImageIcon bg = new ImageIcon("/Users/Russell/Desktop/Russell/Java/Coding"
+ "/eclipse workspace/Historask/resources/bg.jpg");
Image img = bg.getImage();
public HistoraskMenu(){
setBounds(50, 50, 700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Historask");
panel = new JPanel();
setContentPane(panel);
label.setHorizontalAlignment(SwingConstants.CENTER); //Sets position of Historask sign
label.setVerticalAlignment(SwingConstants.TOP);
label.setBackground(new Color(238, 232, 170)); //Sets the colour of the foreground and background of Historask sign
label.setForeground(oldPaper);
label.setIcon(new ImageIcon("/Users/Russell/Desktop/Russell/Java/Coding"
+ "/eclipse workspace/Historask/resources/title.png"));
label.setOpaque(true);
label.setBounds(50, 10, 500, 50);
getContentPane().add(label);
panel.add(label_1);
ATA.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) { //What happens when you press ATA button
new AskTheAdmiralFrame();
}
});
getContentPane().add(ATA);
setVisible(true);
}
public class panel extends JPanel{
setLayout(new GridLayout(0, 1, 0, 0));
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, this);
super.paintComponents(g);
}
}

If you are referring to panel object in the HistoraskMenu() constructor it wont draw image because you are innitializing this to JPanel directly. Rather try panel = new panel();

Related

Why doesn't a panel with GridBagLayout show the content?

I wrote a little something here. It's working if I don't backPanel.setLayout(new GridBagLayout);
But without the grid bag, the content stays in the top left I maximise the screen.
With the grid bag I only get the red backPanel in the frame. Well, there is a gray pixel in the middle of the screen. I'm assuming that's my panel, but I can't make it bigger. I tried setSize but it doesn't change. Also, I had the panel.setBounds(0, 0, getWidth(),getHeight());. I'm not sure why I removed it.
My main is in the other file. The only thing it does at the moment is to call the LoginFrame.
Here is the code:
package first;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField textField;
private JPasswordField passwordField;
public LoginFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 300);
JPanel backPanel = new JPanel(new GridBagLayout());
backPanel.setBackground(Color.RED);
JPanel panel = new JPanel();
panel.setSize(500, 300);
panel.setBackground(Color.LIGHT_GRAY);
panel.setLayout(null);
JLabel label;
panel.add(label = new JLabel("Username:"));
label.setBounds(20, 100, 100, 25);
panel.add(textField = new JTextField());
textField.setBounds(140, 100, 200, 25);
panel.add(label = new JLabel("Password:"));
label.setBounds(20, 145, 100, 25);
panel.add(passwordField = new JPasswordField());
passwordField.setBounds(140, 145, 200, 25);
panel.add(label = new JLabel("CTC Bank"));
label.setFont(new Font("New Times Roman", Font.BOLD, 50));
label.setBounds(0, 0, getWidth(), 100);
label.setHorizontalAlignment(JLabel.CENTER);
JButton button;
panel.add(button = new JButton("Login"));
button.setBounds(140, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
panel.add(button = new JButton("Register"));
button.setBounds(240, 200, 100, 25);
button.addActionListener(this);
button = defaultActionKeyEnter(button, KeyEvent.VK_ENTER);
//add(panel);
backPanel.add(panel);
add(backPanel, BorderLayout.CENTER);
revalidate();
repaint();
setLocationRelativeTo(null);
setVisible(true);
}
public static JButton defaultActionKeyEnter(JButton button, int desiredKeyCode) {
InputMap inputMap = button.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke spaceKeyPressed = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false);
KeyStroke spaceKeyReleased = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true);
KeyStroke desiredKeyPressed = KeyStroke.getKeyStroke(desiredKeyCode, 0, false);
KeyStroke desiredKeyReleased = KeyStroke.getKeyStroke(desiredKeyCode, 0, true);
inputMap.put(desiredKeyPressed, inputMap.get(spaceKeyPressed));
inputMap.put(desiredKeyReleased, inputMap.get(spaceKeyReleased));
inputMap.put(spaceKeyPressed, "none");
inputMap.put(spaceKeyReleased, "none");
return button;
}
// Unfinished code dont worry bout it...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
if (textField.getText().equals("Heinz")
&& (new String(passwordField.getPassword()).equals("password123"))) {
// color = Color.GREEN;
} else {
JOptionPane.showMessageDialog(this, "Wrong Username or Password", "Error", JOptionPane.WARNING_MESSAGE);
// color = Color.RED;
}
} else {
JOptionPane.showMessageDialog(this, "Cya");
dispose();
setVisible(false);
}
// panel.setBackground(color);
}
}
I have seen questions about this but none of the answers were helpful in my case.
Calling the following didn't help.
revalidate();
repaint();
Did I maybe add it in the wrong order?
And how does the code look like to you? Would you consider this clean?
The layout of backPanel will mis-calculate the dimensions of "panel" because "panel" does not participate in layout management properly, without a layout manager of its own.
One solution to this is to use setLayout(null) also on the "backPanel", or add "panel" directly to the JFrame.
With the first suggestion ("backPanel.setLayout(null);" just after it is created), plus the following main method:
public static void main(String[] args) {
new LoginFrame();
}
I get this:

CardLayout showing blank JPanel in Java

I've searched up different tutorials and looked at the Class Profile for CardLayout and JPanel but I can't seem to get my window to show up. Currently it opens a frame with the proper dimensions and title but nothing in the actual container.
This is the code I have(P.S. I know it's a hot mess)
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class Casino extends JFrame implements ActionListener {
private JButton start, settings, scenario, music;
/**
* Constructor method
*/
public Casino(){
JPanel mainUI, startUI, settingsUI, scenarioUI, blackjackUI, oddorevenUI, tcmUI, overorunderUI, slotsUI;
JPanel menus = new JPanel(new CardLayout());
CardLayout GUI = (CardLayout) menus.getLayout();
mainUI = new JPanel();
getContentPane().add(mainUI);
mainUI.setBackground(new Color(53, 9, 9));
//Background items
JLabel title = new JLabel(new ImageIcon("title.png"));
title.setBounds(0,-280,780,700);
mainUI.add(title);
JLabel border = new JLabel(new ImageIcon("mainscreenborder.png"));
border.setBounds(0, 180, 780, 700);
mainUI.add(border);
//Main menu buttons
settings = new JButton();
ImageIcon s = new ImageIcon("settings-button.png");
settings.setBounds(320, 200, 122, 63);
settings.setIcon(s);
mainUI.add(settings);
music = new JButton();
ImageIcon m = new ImageIcon("music-button.png");
music.setBounds(320, 268, 122, 63);
music.setBackground(new Color(53, 9, 9));
music.setIcon(m);
mainUI.add(music);
scenario = new JButton();
ImageIcon sc = new ImageIcon("scenario-button.png");
scenario.setBounds(320, 336, 122, 63);
scenario.setBackground(new Color(53, 9, 9));
scenario.setIcon(sc);
mainUI.add(scenario);
start = new JButton();
ImageIcon st = new ImageIcon("start-button.png");
start.setBounds(320, 404, 122, 63);
start.setBackground(new Color(53, 9, 9));
start.setIcon(st);
mainUI.add(start);
menus.add(mainUI, "Main Menu");
GUI.show(menus, "Main Menu");
setSize(780, 700);
setResizable(false);
setLayout(GUI);
setTitle("White Lily Casino");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Casino wlc = new Casino();
}
}
Note: It worked before when I was using the Container c method instead of using a JPanel and CardLayout. I am trying to switch it to card layout now because I want to use buttons to navigate to multiple screens
Try adding the mainUI to the JFrame
getContentPane().add(mainUI)
or
add(mainUI)

JLabel unusable from other class

I got a problem with two problematics classes. One for drawing things, and other for implementing pan and zoom onto the previously drawn objects.
Imagine my interface as only two spitted panels, one empty(top) and one with a slider(bot):
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JSplitPane;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JSlider;
import java.awt.FlowLayout;
public class Interface {
private JFrame mainFrame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {Interface window = new Interface();window.mainFrame.setVisible(true);
} catch (Exception e) { e.printStackTrace();}
}
});
}
public Interface() {initialize();}
private void initialize() {
mainFrame = new JFrame();
mainFrame.setTitle("LXView");
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setExtendedState(mainFrame.getExtendedState()| JFrame.MAXIMIZED_BOTH);
mainFrame.getContentPane().setBackground(Color.WHITE);
mainFrame.getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPane.setOneTouchExpandable(true);
splitPane.setBackground(Color.WHITE);
mainFrame.getContentPane().add(splitPane, BorderLayout.CENTER);
splitPane.setResizeWeight(0.99);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setEnabled(false);
splitPane.setLeftComponent(scrollPane);
Render topPane = new Render();
scrollPane.setViewportView(topPane);
topPane.setLayout(new BoxLayout(topPane, BoxLayout.X_AXIS));
JPanel botPane = new JPanel();
splitPane.setRightComponent(botPane);
botPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel zoomLevel = new JLabel("Zoom level:");
botPane.add(zoomLevel);
JSlider slider = new JSlider(JSlider.HORIZONTAL, 25, 100, 100);
slider.setMajorTickSpacing(15);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setPreferredSize(new Dimension(600,40));
botPane.add(slider);
PanAndZoom zoomer=new PanAndZoom(topPane.getLabel());
slider.addChangeListener(zoomer);
}
The top panel uses the render class which was made to draw graphics. Simplifying:
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Render extends JPanel {
JLabel envContainer;
Render() {
super();
ImageIcon imageIcon = new ImageIcon("/path/to/img1");
JLabel envContainer = new JLabel(imageIcon);
super.add(envContainer);
}
#Override
public void paint(Graphics g) {
super.paint(g);
/*Render stuff*/
}
public JLabel getLabel() {
return envContainer;
}
}
And the third class which is giving me the trouble, listens on the slider and sets the JLabel icon according to it:
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class PanAndZoom implements ChangeListener {
private JLabel label;
private BufferedImage image;
public PanAndZoom(JLabel lab){
this.label=lab;
try {
image = ImageIO.read(new File("/path/to/img1"));
} catch (IOException e) {
e.printStackTrace();
}
label.setIcon(new ImageIcon("/path/to/img2"));//To test another img. It gives runtime errors.
}
public void stateChanged(ChangeEvent e) {
int value = ((JSlider) e.getSource()).getValue();
double scale = value / 100.0;
BufferedImage scaled = getScaledImage(scale); // It also gives runtime errors.
System.out.println("Scale:"+scale+" Value:"+value);
label.setIcon(new ImageIcon(scaled));
label.revalidate();
}
private BufferedImage getScaledImage(double scale) {
int w = (int) (scale * image.getWidth());
int h = (int) (scale * image.getHeight());
BufferedImage bi = new BufferedImage(w, h, image.getType());
Graphics2D g2 = bi.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
g2.drawRenderedImage(image, at);
g2.dispose();
return bi;
}
}
Why cant i use the JLabel if it was successfully returned by the getLabel method?
You're local version of envContainer in class Render's constructor is overriding the class instance envContainer.
public class Render extends JPanel {
JLabel envContainer; //<---- class instance
Render() {
super();
ImageIcon imageIcon = new ImageIcon("/path/to/img1");
JLabel envContainer = new JLabel(imageIcon); //<---- overriden by local instance, hence class instance remains null
super.add(envContainer);
}
My guess is that you didn't mean to make it a local version since you're not using it within the constructor for anything. Make the following change to your Render constructor.
Render() {
..
this.envContainer = new JLabel(imageIcon);
...
}

How to correctly update an Image in a JLabel?

I'm French so my English is quite bad but I have a real problem with java:
I'm trying to show an Image built manually with some fillRect & co.
It works. Next, I want to update this image as a function of the text I enter in the text field. And there is the problem: it doesn't change anything, and if I manually rescale the window of the JFrame, the image shows totally deformed or scaled badly.
I'm a beginner and I have difficulties with GUI, moreso when I want to couple it with Images.
Can you help me? Why doesn't it work as I want? This is my code below, a bit long but actually quite simple ! Thanks :)
I've changed it a bit, this is the 2e VERSION.
Now the problem s that I can't change a condition in order to modify the color of a simple rectangle, try "lol" in the entry field !
CODE VERSION 2
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class Fenetre extends JFrame {
private JFrame frame;
private JPanel container = new JPanel();
private JTextField jtf;
private JLabel label = new JLabel("Commandes ");
private JButton b = new JButton ("OK");
private Graphics graph;
private Image img;
private JLabel screen;
private boolean color;
/**
* Constructeur de l'objet
*/
public Fenetre(){
color = true;
frame = new JFrame();
frame.setTitle("Animation");
frame.setSize(1000, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf = new JTextField();
jtf.setPreferredSize(new Dimension(800, 30));
b.addActionListener(new BoutonListener());
frame.setContentPane(top);
frame.setVisible(true);
paintComponent(graph);
screen = new JLabel( new ImageIcon(img));
top.add(screen);
top.add(label);
top.add(jtf);
top.add(b);
frame.setContentPane(top);
}
class BoutonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(jtf.getText().equals("lol")) lol();
System.out.println("Entry : " + jtf.getText());
}
}
public void paintComponent(Graphics g)
{
if(img == null) {
img = frame.createImage(1000,300);
g = img.getGraphics();
}
g.setColor(Color.white);
g.fillRect(0,0,1000,300);
if(color) g.setColor(Color.orange); else g.setColor(Color.blue);
g.fillRect(8,25,200,100);
g.setColor(Color.green);
g.drawString("Text",10,10);
}
public void lol()
{
if(color) color = false; else color = true;
}
}
PREVIOUS CODE
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
public class Fenetre extends JFrame {
private JPanel container = new JPanel();
private JTextField jtf;
private JLabel label = new JLabel("Commandes ");
private JButton b = new JButton ("OK");
private Graphics g;
private Image img;
private JLabel screen;
/**
* Constructeur de l'objet
*/
public Fenetre(){
this.setTitle("Animation");
this.setSize(1000, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf = new JTextField();
jtf.setPreferredSize(new Dimension(800, 30));
b.addActionListener(new BoutonListener());
this.setContentPane(top);
this.setVisible(true);
paint(g);
screen = new JLabel( new ImageIcon(img));
top.add(screen);
top.add(label);
top.add(jtf);
top.add(b);
this.setContentPane(top);
}
class BoutonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("Entry : " + jtf.getText());
if(jtf.getText().equals("lol")) lol();
}
}
#Override
public void paint(Graphics g)
{
if(img == null) {
img = createImage(1000,300);
g = img.getGraphics();
}
g.setColor(Color.white);
g.fillRect(0,0,1000,300);
g.setColor(Color.orange);
g.fillRect(8,25,200,100);
g.setColor(Color.green);
g.drawString("Text",10,10);
}
#Override
public void update(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(8,25,300,100);
}
public void lol()
{
g.setColor(Color.blue);
g.fillRect(8,25,200,100);
}
}
I see several problems in your code:
You are confusing your g member variable with the g parameter of the paint method. When lol is called, g is null and you get a NullPointerException
You should never grab a hold on Graphics (only in really rare cases). Instead you override properly paintComponent() and you use the Graphics parameter to draw what you want. When you want to update the component, you call repaint()
Don't override paint, but override paintComponent()
Don't override paint of JFrame. Use a dedicate component for that. No need to use a JLabel for that, a simple JComponent is enough.
Don't extend JFrame if you are not extending its functionality.
After adding components to the component hierarchy, call revalidate()
Fix those issues and come back with another question if you still have problems.
You should probably consider reading this tutorial and the few next steps. It will show you basic examples of things similar to what you are trying to do.
EDIT:
I took your V2 code and patched it as I could. This is very far from perfect but you should get the gist of how you can do this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Fenetre extends JComponent {
private boolean color;
/**
* Constructeur de l'objet
*/
public Fenetre() {
color = true;
setPreferredSize(new Dimension(1000, 300));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0, 0, 1000, 300);
if (color) {
g.setColor(Color.orange);
} else {
g.setColor(Color.blue);
}
g.fillRect(8, 25, 200, 100);
g.setColor(Color.green);
g.drawString("Text", 10, 10);
}
public void lol() {
if (color) {
color = false;
} else {
color = true;
}
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
protected static void initUI() {
JFrame frame = new JFrame();
frame.setTitle("Animation");
frame.setSize(1000, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel container = new JPanel();
final JTextField jtf = new JTextField();
final Fenetre fenetre = new Fenetre();
JLabel label = new JLabel("Commandes ");
JButton b = new JButton("OK");
container.setBackground(Color.white);
container.setLayout(new BorderLayout());
JPanel top = new JPanel();
jtf.setPreferredSize(new Dimension(800, 30));
class BoutonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (jtf.getText().equals("lol")) {
fenetre.lol();
}
System.out.println("Entry : " + jtf.getText());
}
}
b.addActionListener(new BoutonListener());
top.add(fenetre);
top.add(label);
top.add(jtf);
top.add(b);
top.revalidate();
frame.setContentPane(top);
frame.setVisible(true);
}
}
Your Swing graphics programming has several significant problems, and I urge you to go through the tutorials to learn how to do this better. For example, you are
calling the paint method directly -- something you should almost never do except in very special situations (this is not one of them)
Drawing directly in the JFrame's paint(...) method. Instead you will want to draw in the paintComponent(...) method override of a class derived from JComponent such as JPanel.
Calling update unnecessarily as if this were an AWT program. You don't do this in Swing unless you're changing the Look & Feel.
Again, take a look at the tutorials on this -- you will not regret doing this, trust me.
edit -- too slow! 1+ to Guillaume

How to close main frame when open new one

Ive created two frames my main frame is Home and the second one is Selectie
On home there is a button which open the frame selectie, but i want when i click this button the main frame home wil dissapear and only selectie will be shown. The code for the button ive make in a other package and i dont want it in the same class as my main (home)
Code from Home:
package View;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import Controller.HomeController;
import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
Controller = new HomeController();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
addHomeListener(new HomeController());
}
}
Code from the button:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import View.Home;
import View.Selectie;
public class HomeController implements ActionListener {
public void actionPerformed (ActionEvent e){
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}
Please do give valid attention to what #kleopatra and #mKorbel, has to say, they are very much right in pointing that out to you to make things easier.
Here I had added some comments in the code, do check this out :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//import Controller.HomeController;
//import music.PlaySound;
public class Home extends JFrame {
private JLabel label, label1, label2;
private JPanel panel;
private JButton logo, logo1, logo2, logo3, logo4, logo5, selectie;
private Container window = getContentPane();
private HomeController Controller;
public Home (){
initGUI();
}
public void addHomeListener(ActionListener a){
selectie.addActionListener(a);
}
public void initGUI(){
setLayout(null);
setTitle("");
setPreferredSize(new Dimension(800,600));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.WHITE);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(267, 0, 266, 800);
label1.setBackground(Color.RED);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(533, 0, 266, 800);
label2.setBackground(Color.WHITE);
label2.setOpaque(true);
window.add(label2);
logo = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
logo.setBorderPainted(false);
logo.setBounds(40, 150, 188, 188);
label1.add(logo);
logo1 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo1.setBorderPainted(false);
logo1.setBounds(10, 50, 82, 82);
label1.add(logo1);
logo2 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo2.setBorderPainted(false);
logo2.setBounds(92, 20, 82, 82);
label1.add(logo2);
logo3 = new JButton(new ImageIcon("../Ajax/src/img/Ster.png"));
logo3.setBorderPainted(false);
logo3.setBounds(174, 50, 82, 82);
label1.add(logo3);
logo4 = new JButton(new ImageIcon("../Ajax/src/img/shirt.png"));
logo4.setBorderPainted(false);
logo4.setBounds(50, 50, 135, 182);
label.add(logo4);
logo5 = new JButton(new ImageIcon("../Ajax/src/img/uitshirt.png"));
logo5.setBorderPainted(false);
logo5.setBounds(65, 50, 138, 190);
label2.add(logo5);
selectie = new JButton("Selectie");
selectie.setBounds(60, 500, 99, 25);
selectie.setActionCommand("selectie");
label.add(selectie);
pack();
/*
* You are making a new object again,
* when you already had declared it as
* an instance Variable. So I used the
* one declared as instance variable..
* To this we will send the object of Home
* class, means the object of this class..
* And as we know that object of the
* class we are in is by default known
* as this, so passing this to HomeController class.
*/
Controller = new HomeController(this);
addHomeListener(Controller);
setVisible(true);
}
public static void main(String... args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Home();
}
});
}
}
class HomeController implements ActionListener {
/*
* Here we declared a Home class's variable,
* that we will use to dispose that JFrame.
*/
private Home home;
public HomeController(Home home)
{
this.home = home;
}
public void actionPerformed (ActionEvent e){
home.dispose();
Selectie selectie = new Selectie();
selectie.setVisible(true);
}
}
class Selectie extends JFrame
{
public Selectie()
{
initGUI();
}
public void initGUI()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(300, 300);
}
}
I'd suggest to use CardLayout, most easiest, very confortable for (+1 for SSCCE) your code posted here
never create, re_create bunch of another JFrames, only in the cases that you have got very important reasons, then use JDialog with parent to the JFrame

Categories

Resources