Adding background image in Java - java

How do I add background image on this code? i tried everything but the image just won't show.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class sampleProg extends JFrame {
private Image img;
public void sampleProg(){
ImageIcon icon = new ImageIcon("bg.jpg");
img=icon.getImage();
}
public void paint (Graphics g){
g.drawImage(img,0,0,getSize().width,getSize().height,this);
super.paint(g);
}
JButton button = new JButton ("Result");
JButton button2 = new JButton ("Clear");
JLabel label = new JLabel ("Full Name");
JLabel label2 = new JLabel ("Age");
JLabel label3 = new JLabel ("English");
JLabel label4 = new JLabel ("Mathematics");
JLabel label5 = new JLabel ("Science");
JLabel label6 = new JLabel ("Social Studies");
JLabel label7 = new JLabel ("Height in cm");
JLabel label8 = new JLabel ("Weight in lbs");
JLabel label9 = new JLabel ("Message");
JLabel label10 = new JLabel ("Average");
JLabel label11 = new JLabel ("Remarks");
JLabel label12 = new JLabel ("Laurize Albarracin");
JTextField text = new JTextField ("");
JTextField text2 = new JTextField ("");
JTextField text3 = new JTextField ("");
JTextField text4 = new JTextField ("");
JTextField text5 = new JTextField ("");
JTextField text6 = new JTextField ("");
JTextField text7 = new JTextField ("");
JTextField text8 = new JTextField ("");
JTextField text9 = new JTextField ("");
JTextField text10 = new JTextField ("");
JTextField text11 = new JTextField ("");
int average;
JPanel background = new JPanel();
JFrame frame = new JFrame();
public sampleProg (String str){
super(str);
background.setLayout (null);
background.setBounds (30,50,90,20);
button.setBounds(350,170,90,20);
button2.setBounds(450,170,90,20);
label.setBounds(30,90,90,20);
label2.setBounds(30,130,90,20);
label3.setBounds(30,170,90,20);
label4.setBounds(30,210,90,20);
label5.setBounds(30,250,90,20);
label6.setBounds(30,290,90,20);
label7.setBounds(350,90,90,20);
label8.setBounds(350,130,90,20);
label9.setBounds(350,210,90,20);
label10.setBounds(350,250,90,20);
label11.setBounds(350,290,90,20);
label12.setBounds(300,35,150,20);
text.setBounds(130,90,190,20);
text2.setBounds(130,130,190,20);
text3.setBounds(130,170,190,20);
text4.setBounds(130,210,190,20);
text5.setBounds(130,250,190,20);
text6.setBounds(130,290,190,20);
text7.setBounds(450,90,250,20);
text8.setBounds(450,130,250,20);
text9.setBounds(450,210,250,20);
text10.setBounds(450,250,250,20);
text11.setBounds(450,290,250,20);
button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e){
text9.setText("Hi! "+text.getText()+"you are"+text2.getText()+"years of age and now you stand"+text7.getText()+"in cm while you're weight is"+text8.getText()+"in lbs. These are your remark and average");
int English = Integer.parseInt (text3.getText());
int Mathematics = Integer.parseInt (text4.getText());
int Science = Integer.parseInt (text5.getText());
int SocialStudies = Integer.parseInt(text6.getText());
average = (English+Mathematics+Science+SocialStudies)/4;
text10.setText(Integer.toString(average));
}
}
);
button2.addActionListener (new ActionListener(){
public void actionPerformed(ActionEvent e){
text.setText("");
text2.setText("");
text3.setText("");
text4.setText("");
text5.setText("");
text6.setText("");
text7.setText("");
text8.setText("");
text9.setText("");
text10.setText("");
text11.setText("");
}
});
background.add(button);
background.add(button2);
background.add(label);
background.add(label2);
background.add(label3);
background.add(label4);
background.add(label5);
background.add(label6);
background.add(label7);
background.add(label8);
background.add(label9);
background.add(label10);
background.add(label11);
background.add(label12);
background.add(text);
background.add(text2);
background.add(text3);
background.add(text4);
background.add(text5);
background.add(text6);
background.add(text7);
background.add(text8);
background.add(text9);
background.add(text10);
background.add(text11);
getContentPane().add(background);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public sampleProg(){
setLayout(new FlowLayout());
}
public static void main (String[]args){
sampleProg frame = new sampleProg("Swing Application");
frame.setSize(730,350);
frame.show();
}
}

Your code never sets the img field. Move the code from the void sampleProg() method into your constructor. You should also set the background panel's background to a transparent color for the image to show through. Also, you should paint the image on the background panel rather than on the frame, otherwise it will always be covered up. You can create an anonymous panel and move your paint() code into it instead.
There are cleaner ways to do this found in the link Mondain provided.
public class sampleProg extends JFrame {
JPanel background = new JPanel() {
public void paint (Graphics g){
g.drawImage(img,0,0,getSize().width,getSize().height,this);
super.paint(g);
}
};
public sampleProg(string str) {
//...
ImageIcon icon = new ImageIcon("bg.jpg");
img=icon.getImage();
//...
Color transparent = new Color(0, true);
background.setBackground(transparent);
}
}

This may have the answer you are looking for: How to set background image in Java?

Background Panel gives a couple of solutions depending on your requirements.

Related

How do I align each Label next to its Textfield in Java?

Misaligned fields
What i want.
My code-
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Test2 extends JFrame {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Enter 1st Number");
JLabel label2 = new JLabel("Enter 2nd Number");
JLabel label3 = new JLabel("Press to add");
JLabel label4 = new JLabel("Check Answer");
JButton button = new JButton("Press");
JTextField text1 = new JTextField(50);
JTextField text2 = new JTextField(50);
public Test2() {
setTitle("Tutorial");
setVisible(true);
setSize(1080, 720);
setDefaultCloseOperation(EXIT_ON_CLOSE);
text1.setBounds(90,60,86,23);
text2.setBounds(233,60,92,23);
button.setBounds(161,109,89,23);
panel.add(text1);
panel.add(text2);
panel.add(button);
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
add(panel);
}
public static void main(String[] args) {
Test2 t = new Test2 ();
}
}
I am also going to write the code to add the 2 numbers and if a user enters letters, i am also gonna throw an exception. But i want them to align first. I can not use GUI form as this is for practice.
Don't use setBounds().
use Grid Layout of 4 rows and 2 columns
you need to use a Gridlayout with 2 columns and 4 rows to make them like that:
class Test2 extends JFrame {
JPanel panel = new JPanel();
JLabel label1 = new JLabel("Enter 1st Number");
JLabel label2 = new JLabel("Enter 2nd Number");
JLabel label3 = new JLabel("Press to add");
JLabel label4 = new JLabel("Check Answer");
JButton button = new JButton("Press");
JTextField text1 = new JTextField(50);
JTextField text2 = new JTextField(50);
public Test2() {
GridLayout gb = new GridLayout(4, 2);
panel.setLayout(gb);
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(label3);
panel.add(button);
panel.add(label4);
add(panel);
setTitle("Tutorial");
setVisible(true);
setSize(250, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Test2 t = new Test2();
}
}
output:

Nothing Displayed On Screen Java Swing Application

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimultaneousSolver extends JFrame implements ActionListener
{
JTextField tfEQ1X = new JTextField (20);
JTextField tfEQ1Y = new JTextField (20);
JTextField tfEQ1Num = new JTextField (20);
JTextField tfEQ2X = new JTextField (20);
JTextField tfEQ2Y = new JTextField (20);
JTextField tfEQ2Num = new JTextField (20);
JLabel lblX1 = new JLabel ("X₁");
JLabel lblY1 = new JLabel ("Y₁");
JLabel lblNum1 = new JLabel ("Number₁");
JLabel lblEqual1 = new JLabel ("=");
JLabel lblX2 = new JLabel ("X₂");
JLabel lblY2 = new JLabel ("Y₂");
JLabel lblNum2 = new JLabel ("Number₂");
JLabel lblEqual2 = new JLabel ("=");
JTextArea Empty = new JTextArea ("",1,20);
double X1, X2, Y1, Y2, Num1, Num2;
double SolX, SolY;
Font font = new Font("Comic Sans MS", Font.BOLD, 14);
SimultaneousSolver()
{
super ("Simultaneous Equation Solver");
setDesign();
setSize(700,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panelEquation1 = new JPanel(new GridLayout(1,7));
{
panelEquation1.add(lblX1);
panelEquation1.add(tfEQ1X);
panelEquation1.add(lblY1);
panelEquation1.add(tfEQ1Y);
panelEquation1.add(lblEqual1);
panelEquation1.add(lblNum1);
panelEquation1.add(tfEQ1Num);
}
JPanel panelEquation2 = new JPanel(new GridLayout(1,7));
{
panelEquation2.add(lblX2);
panelEquation2.add(tfEQ2X);
panelEquation2.add(lblY2);
panelEquation2.add(tfEQ2Y);
panelEquation2.add(lblEqual2);
panelEquation2.add(lblNum2);
panelEquation2.add(tfEQ2Num);
}
setVisible(true);
}
public final void setDesign()
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception e)
{
}
}
public static void main(String[] args)
{
new SimultaneousSolver();
}
}
Ok, So I am starting a new application development using pure swing if possible, so i set up my objects and stuff and when I try to run the application to see if it looks good, Nothing Shows up except an empty container.
Add these two lines at the end of constructor.
setLayout(new GridLayout()); // sets layout for frame - you can choose any one suitable layout
add(panelEquation1); // adds 1st panel
add(panelEquation2); // adds 2nd panel

Flipping the cards for memory card game isn't working in java (without applets)

I'm making a memory card game. I started by adding 5 ImageIcons with initial value(images) of the card in flipped state, added a button for flipping the cards through Action Listener but can't seem to get it flipped when I click the button.
I'm still a beginner to GUI and I don't want to use applets.
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.*;
//this class gonna control the basic ops of the game
public class MemoControl extends JFrame{
public JLabel label;
public JButton button;
//images
public ImageIcon image1;
public JLabel label1;
public ImageIcon image2;
public JLabel label2;
public ImageIcon image3;
public JLabel label3;
public ImageIcon image4;
public JLabel label4;
public ImageIcon image5;
public JLabel label5;
public MemoControl(){
setLayout(new FlowLayout());
image1 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label2 = new JLabel(image2);
add(label2);
image3 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label3 = new JLabel(image3);
add(label3);
image4 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label4 = new JLabel(image4);
add(label4);
image5 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label5 = new JLabel(image5);
add(label5);
/*label = new JLabel("Welcome to AMY Memo Game");
add(label);*/
/*textField = new JTextField(15);
add(textField);*/
button = new JButton("Flip");
add(button);
EventClass event = new EventClass();
button.addActionListener(event);
}//MyMemo constr end
private class EventClass implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == button){
image1 = new ImageIcon(getClass().getResource("deer_card.jpg"));
label1 = new JLabel(image1);}
}
}//Event class end
public static void main(String args[]){
MemoControl gui = new MemoControl();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
gui.setTitle("My Memo");
}//main end
}//AMYMemo class end
The updated code:
import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.*;
//this class gonna control the basic ops of the game
public class MemoControl extends JFrame{
public JLabel label;
public JButton button;
//images
public ImageIcon image1;
public JLabel label1;
public ImageIcon image2;
public JLabel label2;
public ImageIcon image3;
public JLabel label3;
public ImageIcon image4;
public JLabel label4;
public ImageIcon image5;
public JLabel label5;
public MemoControl(){
setLayout(new FlowLayout());
image1 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label2 = new JLabel(image2);
add(label2);
image3 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label3 = new JLabel(image3);
add(label3);
image4 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label4 = new JLabel(image4);
add(label4);
image5 = new ImageIcon(getClass().getResource("card_cover1.jpg"));
label5 = new JLabel(image5);
add(label5);
/*label = new JLabel("Welcome to AMY Memo Game");
add(label);*/
/*textField = new JTextField(15);
add(textField);*/
button = new JButton("Flip");
add(button);
EventClass event = new EventClass();
button.addActionListener(event);
}//MyMemo constr end
private class EventClass implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == button){
image1 = new ImageIcon(getClass().getResource("deer_card.jpg"));
label1.setIcon(image1);
}
}
}//Event class end
public static void main(String args[]){
MemoControl gui = new MemoControl();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
gui.setTitle("My Memo");
}//main end
}//AMYMemo class end
Try label1.setIcon(image1); instead of label1 = new JLabel(image1); in EventClass. Because you create a new instance of JLabel with new Icon which is not added to your JFrame.
Expanding on #alex2410's answer,
In java you need to understand the difference between a variable, a reference, and an object.
label1 is a variable. It's a variable that can hold a reference to a "JLabel".
new JLabel(..) creates an object and returns a reference to it.
so:
label1 = new JLabel() assigns a reference to newly created JLabel to label1.
When you add(label1) the value of label1 is passed to add. The value is a reference to the JLabel that you created earlier.
When you assign a reference of a new object to label1 after this, it doesn't change the object that was originally passed into add. Thus your screen will not change.
When you call label1.setIcon(...) you make a change to the object that label1 is pointing to. This object happens to be the same one that you added to the JFrame, so changing that object, will make a change to the screen.

Java grid layout GUI - how to enter new pane on event?

How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout

Unstable GUI in Java

I am writing a very simple GUI, that contains 3 buttons, 2 labels, 2 text fields and one text area. Strangely, the result is unstable: when running the class the GUI appears with random number of the controls. I tried various layout managers, changing the order among the control - nothing.
Can someone help?
package finaltestrunner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FinalTestGUI extends JFrame implements ActionListener
{
public Boolean startState = false;
JButton sofButton;
JButton startStopButton;
JButton exitButton;
JTextField loopCounts;
JTextField trSnField;
JTextArea resultField = null;
public FinalTestGUI()
{
// The constructor creates the panel and places the controls
super(); // Jframe constructor
JFrame trFrame = new JFrame();
trFrame.setSize(1000, 100);
trFrame.setVisible(true);
trFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trFrame.setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
// trFrame.setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
trFrame.add(trControlPanel);
// cpl.add(trResultField);
startStopButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trStartStopButton)
{
startState = !startState;
if (startState)
{
startStopButton.setText("Run ");
startStopButton.setForeground(Color.red);
}
else
{
startStopButton.setText("Stop");
startStopButton.setForeground(Color.green);
}
}
});
sofButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trSofButton)
{
loopCounts.setText("SOF\n");
}
});
exitButton.addActionListener (new ActionListener()
{
#Override
public void actionPerformed (ActionEvent trExitButton)
{
System.exit(0);
}
});
} // End of the constructor
#Override
public void actionPerformed (ActionEvent ae) { }
public void atpManager ()
{
String selectedAtp = "";
}
}
There are a couple of issues with this code:
You are already inheriting from JFrame, so you do not need to create yet another JFrame
You are showing your frame with setVisible(true) and afterwards adding components to it. This invalidates your layout, you need to revalidate afterwards (or move setVisible() to a position where you already added your components)
You are adding your components to the JFrame directly, but you need to use its contentpane. Starting with Java 1.5, the JFrame.add() methods automatically forward to the content pane. In earlier versions, it was necessary to retrieve the content pane with JFrame.getContentPane() to add the child components to the content pane.
Try this:
public FinalTestGUI() {
// The constructor creates the panel and places the controls
super(); // Jframe constructor
setSize(1000, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test runner");
setFont(new Font("SansSerif", Font.PLAIN, 14));
setLayout(new FlowLayout());
JPanel trControlPanel = new JPanel();
trControlPanel.setSize(1000, 100);
trControlPanel.setLayout(new GridLayout(1,7));
exitButton = new JButton("Exit");
trControlPanel.add(exitButton);
startStopButton = new JButton("Run ");
trControlPanel.add(startStopButton);
JLabel loopsLabel = new JLabel ("Loops count: ");
trControlPanel.add(loopsLabel);
loopCounts = new JTextField (5);
trControlPanel.add(loopCounts);
sofButton = new JButton("SoF");
trControlPanel.add(sofButton);
JLabel testLabel = new JLabel ("serial Number: ");
trControlPanel.add(testLabel);
trSnField = new JTextField (5);
trControlPanel.add(trSnField);
JTextArea trResultField = new JTextArea (80, 10);
// getContentPane().add(trControlPanel); // pre 1.5
add(trControlPanel); // 1.5 and greater
setVisible(true);
}

Categories

Resources