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
Related
I have a JFrame with three JPanel objects. I have a problem with two of the panels. I can see in my frame, the panel JPanelProduit with object but for the panel, JPanelInformations and JPanelVentes, I see nothing. Where is my error?
My Code
package IHM;
import javax.swing.*;
import Donnees.Categories;
import Donnees.CategoriesCellRenderer;
import Donnees.CategoriesListModel;
import Donnees.Marques;
import Donnees.MarquesCellRenderer;
import Donnees.MarquesListModel;
import Donnees.Produits;
import Donnees.ProduitsCellRenderer;
import Donnees.ProduitsListModel;
import Fabriques.FabCategories;
import Fabriques.FabMarques;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Fenetre {
static Connection conn;
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.hsqldb.jdbcDriver");
conn=DriverManager.getConnection("jdbc:hsqldb:file:BDD/bdd","sa","");
FabCategories.getInstance().demarrerConnexion(conn);
FabMarques.getInstance().demarrerConnexion(conn);
JFrame f = new JFrame("Gestion des Produits");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1,2,3, 3));
JPanelProduit jPanelProduit = new JPanelProduit();
JPanelInformations jPanelInformations = new JPanelInformations();
JPanelVentes jPanelVentes = new JPanelVentes();
jPanelProduit.setBackground(Color.GREEN);
jPanelProduit.setBackground(Color.YELLOW);
jPanelVentes.setBackground(Color.PINK);
f.add(jPanelProduit);
f.add(jPanelInformations);
f.add(jPanelVentes);
f.setSize(700,700);
f.pack();
f.setVisible(true);
}
}
class JPanelProduit extends JPanel {
public JPanelProduit() throws SQLException {
setLayout(new GridLayout(5,2,5,5));
String labelCat = "Categories";
String labelMark = "Marques";
String labelProd = "Produits";
JList<Categories> listCategories= new JList<Categories> ();
JList<Marques> listMarques= new JList<Marques> ();
JList<Produits> listProduits= new JList<Produits> ();
JScrollPane listCategoriesScrollPane = new JScrollPane (listCategories);
add(new JLabel(labelCat));
add(new JScrollPane(listCategoriesScrollPane));
listCategories.setCellRenderer(new CategoriesCellRenderer());;
listCategories.setModel(new CategoriesListModel());
add(new JLabel(labelMark));
JScrollPane listMarquesScrollPane = new JScrollPane (listMarques);
add(new JScrollPane(listMarquesScrollPane));
listMarques.setCellRenderer(new MarquesCellRenderer());
listMarques.setModel(new MarquesListModel());
add(new JLabel(labelProd));
JScrollPane listProduitScrollPane = new JScrollPane (listProduits);
add(new JScrollPane(listProduitScrollPane));
//listProduits.setCellRenderer(new ProduitsCellRenderer());
//listProduits.setModel(new ProduitsListModel());
}
}
class JPanelInformations extends JPanel {
public JPanelInformations() {
JPanel PanelInformation = new JPanel();
setLayout(new GridLayout(7,1,5,5));
JLabel labelInfo = new JLabel ("INFORMATION");
JLabel labelPrix = new JLabel ("Prix");
JLabel labelDesc = new JLabel ("Description");
JLabel labelQuant = new JLabel ("Quantite");
JTextField fieldPrix = new JTextField (20);
JTextArea fieldDesc = new JTextArea (20, 20);
JTextField fieldQuantite = new JTextField (20);
PanelInformation.add(labelInfo);
PanelInformation.add(labelPrix);
PanelInformation.add(fieldPrix);
PanelInformation.add(labelDesc);
PanelInformation.add(fieldDesc);
PanelInformation.add(labelQuant);
PanelInformation.add(fieldQuantite);
}
}
class JPanelVentes extends JPanel {
public JPanelVentes() {
JPanel PanelVentes = new JPanel();
setLayout(new GridLayout());
JLabel labelVendre = new JLabel ("VENDRE");
JLabel labelQte = new JLabel ("Quantite");
JLabel labelPromo = new JLabel ("Promotion");
JLabel labelTot = new JLabel ("Total");
JTextField fieldQte = new JTextField (20);
JTextField fieldPromoEuros = new JTextField (20);
JTextField fieldPromoPourcent = new JTextField (20);
JTextField fieldTotal = new JTextField (20);
PanelVentes.add (labelVendre);
PanelVentes.add (labelQte);
PanelVentes.add (fieldQte);
PanelVentes.add (labelPromo);
PanelVentes.add (fieldPromoEuros);
PanelVentes.add (fieldPromoPourcent);
PanelVentes.add (labelTot);
PanelVentes.add (fieldTotal);
}
}
The JPanelInformations in the constructor creates a local instance JPanel PanelInformation = new JPanel(); which is not added to main panel.
You should either add it to this or get rid of it at all and add all the labels to this directly.
The same with JPanelVentes
Inside JPanelInformations class you are creating new JPanel class PanelInformation and adding other elements in it. You should just call add() as JPanelInformations already extends JPanel and you are creating instance of JPanelVentes class.
So follow same JPanel logic you have used in JPanelProduit class.
Same goes for JPanelVentes as well.
Also take care of naming conventions. Makes life easy
JPanel panelVentes = new JPanel();
Try out this:
public JPanelInformations() {
//JPanel PanelInformation = new JPanel(); remove new instance of panel
setLayout(new GridLayout(7,1,5,5));
JLabel labelInfo = new JLabel ("INFORMATION");
JLabel labelPrix = new JLabel ("Prix");
JLabel labelDesc = new JLabel ("Description");
JLabel labelQuant = new JLabel ("Quantite");
JTextField fieldPrix = new JTextField (20);
JTextArea fieldDesc = new JTextArea (20, 20);
JTextField fieldQuantite = new JTextField (20);
add(labelInfo); //remove PanelInformation.
add(labelPrix);//remove PanelInformation.
add(fieldPrix);//remove PanelInformation.
add(labelDesc);//remove PanelInformation.
add(fieldDesc);//remove PanelInformation.
add(labelQuant);//remove PanelInformation.
add(fieldQuantite);//remove PanelInformation.
}
AND
public JPanelVentes() {
//JPanel PanelVentes = new JPanel(); remove the new instance of JPanel
setLayout(new GridLayout());
JLabel labelVendre = new JLabel ("VENDRE");
JLabel labelQte = new JLabel ("Quantite");
JLabel labelPromo = new JLabel ("Promotion");
JLabel labelTot = new JLabel ("Total");
JTextField fieldQte = new JTextField (20);
JTextField fieldPromoEuros = new JTextField (20);
JTextField fieldPromoPourcent = new JTextField (20);
JTextField fieldTotal = new JTextField (20);
add (labelVendre); //remove PanelVentes
add (labelQte);//remove PanelVentes
add (fieldQte);//remove PanelVentes
add (labelPromo);//remove PanelVentes
add (fieldPromoEuros);//remove PanelVentes
add (fieldPromoPourcent);//remove PanelVentes
add (labelTot);//remove PanelVentes
add (fieldTotal);//remove PanelVentes
}
For some reason my action listener isn't working correctly. When I add the first number to it it works fine, but when I continue to add numbers it stops working correctly. Any ideas on why this happens would be appreciated!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculatorFinal extends JFrame{
private JLabel additionLabel;
private JTextField additionField;
private JButton additionButton;
private JPanel multiplication;
private JLabel multiplicationLabel;
private JTextField multiplicationField;
private JButton multiplicationButton;
private JPanel total;
private JLabel totalLabel;
private JTextField totalField;
private JButton stopButton;
public BabyCalculatorFinal(){
setDefaultCloseOperation(EXIT_ON_CLOSE);// 1st thing to do
setName("Baby Calculator Final"); // 2nd thing to do
setLayout(new GridLayout(3,0)); //sets grid layout for the entire thing with 3 rows
// Create Action Event
BabyCalculatorListener listener = new BabyCalculatorListener();
//Addition
//Addition Set Layout
JPanel addition = new JPanel(new BorderLayout());
//Addition Features
additionLabel = new JLabel("Amount to add"); //Create label
additionField = new JTextField(10);
additionButton = new JButton("Add");
//Organize Addition Panel
addition.add(additionLabel, BorderLayout.WEST);//IMPORTANT FORMAT
addition.add(additionField, BorderLayout.CENTER);
addition.add(additionButton, BorderLayout.EAST);
//Add addition Panel to Frame
add(addition);
additionButton.addActionListener(listener);
//Multiplictation
//Multiplication Set Layout
multiplication = new JPanel();
multiplication.setLayout(new BorderLayout());//Trying a different way of setting the layout
//Multiplication Features
multiplicationLabel = new JLabel("Amount to Multiply"); //Create label
multiplicationField = new JTextField(10);
multiplicationButton = new JButton("Multiply");
//Organize Multiplication Panel
multiplication.add(multiplicationLabel, BorderLayout.WEST);
multiplication.add(multiplicationField, BorderLayout.CENTER);
multiplication.add(multiplicationButton, BorderLayout.EAST);
//Add Multiplication Panel to Frame
add(multiplication);
multiplicationButton.addActionListener(listener);
//Total
total = new JPanel(new FlowLayout());
totalLabel = new JLabel("Total");
totalField = new JTextField();
totalField.setText("0.0");
totalField.setEditable(false);
stopButton = new JButton("Stop");
total.add(totalLabel);
total.add(totalField);
total.add(stopButton);
//Add Total Panel to Frame
add(total);
pack();
setVisible(true);
}
public static void main(String[] args){
JFrame myFrame = new BabyCalculatorFinal();
}
public class BabyCalculatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String totalText = totalField.getText();
double totalAmount = Double.parseDouble(totalText);
if (e.getSource() == additionButton){
String additionText = additionField.getText();
double addAmount = Double.parseDouble(additionText);
totalAmount += addAmount;
}
else{
String multiplicationText = multiplicationField.getText();
double multiplicationAmount = Double.parseDouble(multiplicationText);
totalAmount *= multiplicationAmount;
}
totalField.setText(totalAmount + "");
}
}
}
Your code works fine for me. It could be a repaint issue that you're experiencing. Try resizing the frame when you stop seeing the "total" change. If that works, you could try a repaint() after setting the totalField text.
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
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);
}
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.