Blank Frame for no apperent reason [duplicate] - java

This question already has answers here:
Java null layout results in a blank screen
(2 answers)
Closed 8 years ago.
Program is Compiling and running but it is not displaying anything on the frame just a blank screen.
i am making main menu for my game using cardLayout, i have made different classes for every panel and then added them in cardlayout in Frame
Kindly some one please pinpoint the mistake i am doing i cant find it..
thankyou
enter code here
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class MainMenu extends JFrame implements ActionListener{
static CardLayout cl2;
static JPanel cardPanel;
Name p1;
MainM p2;
Robot p3;
High p4;
Inst p5;
gamepanel gp;
public static int height;
public static int width;
public static void main(String args[]){
MainMenu cl = new MainMenu();
cl.What();
}
public void What() {
// get the screen size as a java dimension
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setTitle("EROBOT");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// get height, and width
height = screenSize.height ;
width = screenSize.width ;
// set the jframe height and width
setSize(new Dimension(width, height));
cardPanel = new JPanel();
p1= new Name();
p2= new MainM();
p3= new Robot();
p4= new High();
p5= new Inst();
gp= new gamepanel();
cl2 = new CardLayout();
cardPanel.setLayout(cl2);
cardPanel.add(p1, "name");
cardPanel.add(p2, "menu");
cardPanel.add(p3, "robo");
cardPanel.add(p4, "inst");
cardPanel.add(p5, "high");
cardPanel.add(gp, "start");
getContentPane().add(cardPanel);
//name
Name.done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
// Main
MainM.newg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
MainM.high.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "high" );
}
});
MainM.robo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "robo" );
}
});
MainM.inst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "inst" );
}
});
/////////////////////
//Robot
Robot.go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
Robot.back1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//high score
High.back2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//how to play
Inst.back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
}
public void actionPerformed(ActionEvent e){}
}
class Name extends JPanel{
JLabel enter;
static JButton done;
JTextField name;
JPanel side;
JPanel up;
JLabel title;
Name(){
Color h3= new Color(255,229,204);
side= new JPanel();
up= new JPanel();
setLayout(null);
MainMenu mm= new MainMenu();
setBackground(h3);
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title.setBounds(520, 100, 300, 50);
enter= new JLabel("ENTER YOUR NAME HERE");
enter.setFont(new Font("Ravie", Font.PLAIN, 20));
enter.setForeground(Color.orange);
enter.setBounds(370, 200, 350, 50);
name = new JTextField();
name.setBounds(390, 250, 150, 25);
done= new JButton("DONE");
done.setFont(new Font("Ravie", Font.PLAIN, 20));
done.setForeground(Color.orange);
done.setBackground(Color.YELLOW);
done.setOpaque(false);
done.setBorder(null);
done.setBounds(400, 280, 150, 30);
side.setBounds(0,40,mm.width,60);
up.setBounds(40,0,40,mm.height);
side.setBackground(Color.ORANGE);
up.setBackground(Color.ORANGE);
side.add(title);
add(enter);
add(name);
add(done);
add(side);
add(up);
}
}
class MainM extends JPanel{
JPanel l1;
JPanel l2;
JPanel l3;
JPanel l4;
JPanel contain;
JPanel side1;
JPanel up1;
static JButton newg;
static JButton high;
static JButton robo;
static JButton inst;
JLabel title;
MainM(){
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
setBackground(h3);
l1= new JPanel();
l2= new JPanel();
l3= new JPanel();
l4= new JPanel();
contain= new JPanel();
side1= new JPanel();
up1= new JPanel();
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40));
title.setForeground(Color.WHITE);
title.setBounds(520, 100, 300, 50);
//custom colors
Color b1= new Color(99,230,199);
Color h= new Color(132,234,23);
Color h1= new Color(45,99,120);
Color h2= new Color(0,0,101);
Color h4= new Color(154,0,0);
l1.setBounds(480,200,10,525);
l1.setBackground(h4);
l2.setBounds(465,210,565,10);
l2.setBackground(h4);
l3.setBounds(1000,200,10,525);
l3.setBackground(h4);
l4.setBounds(465,690,565,10);
l4.setBackground(h4);
// settings style amd font of buttons
newg = new JButton("New Game");
newg.setFont(new Font("Ravie", Font.PLAIN, 25));
newg.setBackground(Color.YELLOW);
newg.setOpaque(false);
newg.setBorder(null);
newg.setForeground(h2);
high = new JButton("High Scores");
robo= new JButton("Select your Robot");
inst = new JButton("How to Play");
high.setFont(new Font("Ravie", Font.PLAIN, 25));
high.setBackground(Color.YELLOW);
high.setOpaque(false);
high.setBorder(null);
high.setForeground(h1);
robo.setFont(new Font("Ravie", Font.PLAIN, 25));
robo.setBackground(Color.YELLOW);
robo.setOpaque(false);
robo.setBorder(null);
robo.setForeground(h);
inst.setFont(new Font("Ravie", Font.PLAIN, 25));
inst.setBackground(Color.YELLOW);
inst.setOpaque(false);
inst.setBorder(null);
inst.setForeground(Color.MAGENTA);
contain.setBounds(490,220,490,460);
contain.setLayout(new GridLayout(4,1));
side1.setBounds(0,40,mm.width,60);
up1.setBounds(40,0,40,mm.height);
side1.setBackground(h4);
up1.setBackground(h4);
//adding all the JComponents to the screen
side1.add(title);
contain.add(newg);
contain.add(high);
contain.add(robo);
contain.add(inst);
add(l1);
add(l2);
add(l3);
add(l4);
add(side1);
add(up1);
add(contain);
}
}
class Robot extends JPanel{
ImageIcon a;
ImageIcon b;
ImageIcon c;
JPanel side2;
JPanel up2;
static JButton r1;
static JButton r2;
static JButton r3;
static JButton back1;
static JButton go;
JLabel title1;
Robot(){
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
Color h4= new Color(154,0,0);
side2= new JPanel();
up2= new JPanel();
r1= new JButton();
r2= new JButton();
r3= new JButton();
back1= new JButton("Back");
go= new JButton("LEt's go");
a = new ImageIcon(getClass().getResource("a.gif"));
b = new ImageIcon(getClass().getResource("b.gif"));
c = new ImageIcon(getClass().getResource("c.gif"));
//adding the ImageIcons to the JButtons
r1 = new JButton(a);
r1.setBounds(120,120,300,300);
r1.setBackground(Color.YELLOW);
r1.setOpaque(false);
r1.setBorder(null);
r2 = new JButton(b);
r2.setBounds(460,120,300,300);
r2.setBackground(Color.YELLOW);
r2.setOpaque(false);
r2.setBorder(null);
r3 = new JButton(c);
r3.setBounds(890,120,300,300);
r3.setBackground(Color.YELLOW);
r3.setOpaque(false);
r3.setBorder(null);
back1 = new JButton("Let's Go!");
back1.setBounds(520, 500, 170, 60);
back1.setFont(new Font("Ravie", Font.PLAIN, 25));
back1.setBackground(Color.YELLOW);
back1.setOpaque(false);
back1.setBorder(null);
setLayout(null);
title1 = new JLabel("E-ROBOT");
title1.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
// title1.setBounds(520, 100, 300, 50);
side2.setBounds(0,40,mm.width,60);
up2.setBounds(40,0,40,mm.height);
side2.setBackground(h);
up2.setBackground(h);
side2.add(title1);
add(side2);
add(up2);
add(r1);
add(r2);
add(r3);
add(back1);
add(go);
}
}
class High extends JPanel{
JLabel title3;
static JButton back2;
JPanel side4;
JPanel up4;
High()
{
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
side4 = new JPanel();
up4= new JPanel();
Color h1= new Color(45,99,120);
setLayout(null);
title3 = new JLabel("E-ROBOT");
title3.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title3.setBounds(520, 100, 300, 50);
back2= new JButton("Back");
back2.setBounds(500,500,120,30);
back2.setFont(new Font("Ravie", Font.PLAIN, 25));
back2.setBackground(Color.YELLOW);
back2.setOpaque(false);
back2.setBorder(null);
side4.setBounds(0,40,mm.width,60);
up4.setBounds(40,0,40,mm.height);
side4.setBackground(h1);
up4.setBackground(h1);
side4.add(title3);
add(side4);
add(up4);
add(back2);
}
}
class Inst extends JPanel{
JLabel jl1;
JLabel jl2;
JLabel jl3;
JLabel jl4;
JLabel jl5;
JLabel title2;
JPanel side3;
JPanel up3;
static JButton back;
JPanel contain2;
Inst(){
MainMenu mm= new MainMenu();
contain2= new JPanel();
side3= new JPanel();
up3= new JPanel();
Color h= new Color(132,234,23);
Color h3= new Color(255,229,204);
jl1= new JLabel("Welcome aboard\n !");
jl2 = new JLabel("So the game is simple.\n");
jl3 = new JLabel("You have to catch even number only\n.");
jl4 = new JLabel("A life ends if you catch an odd number.\n");
jl5 = new JLabel("Oh and also the game gets more difficult when your lives end!\n");
jl1.setFont(new Font("Ravie", Font.PLAIN, 20));
jl2.setFont(new Font("Ravie", Font.PLAIN, 20));
jl3.setFont(new Font("Ravie", Font.PLAIN, 20));
jl4.setFont(new Font("Ravie", Font.PLAIN, 20));
jl5.setFont(new Font("Ravie", Font.PLAIN, 20));
jl1.setForeground(Color.magenta);
jl2.setForeground(Color.magenta);
jl3.setForeground(Color.magenta);
jl4.setForeground(Color.magenta);
jl5.setForeground(Color.magenta);
title2 = new JLabel("E-ROBOT");
title2.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title2.setBounds(520, 100, 300, 50);
back = new JButton("Back");
back.setFont(new Font("Ravie", Font.PLAIN, 15));
back.setBackground(Color.YELLOW);
back.setOpaque(false);
back.setBorder(null);
setLayout(null);
contain2.setBounds(80,200,800,400);
contain2.setBackground(h3);
side3.setBounds(0,40,mm.width,60);
up3.setBounds(40,0,40,mm.height);
side3.setBackground(Color.MAGENTA);
up3.setBackground(Color.MAGENTA);
side3.add(title2);
contain2.add(jl1);
contain2.add(jl2);
contain2.add(jl3);
contain2.add(jl4);
contain2.add(jl5);
contain2.add(back);
add(contain2);
add(side3);
add(up3);
}
}

I'm not sure whether it helps (sorry but your code is too large and bad formatted, so I cannot understand it), but you can try to revalidate and repaint the root pane or content pane of JFrame each time when you update your GUI.
Something like this
public static void updateRootPane(JComponent aComponent) {
Window w = SwingUtilities.windowForComponent(aComponent);
if (w instanceof JFrame) {
((JFrame) w).getRootPane().revalidate();
((JFrame) w).getRootPane().repaint();
} else if (w instanceof JDialog) {
((JDialog) w).getRootPane().revalidate();
((JDialog) w).getRootPane().repaint();
}
}

Related

My content pane show only white even if it has components on it

I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the JPanel has components in it.
I've tried adding the components on the frame but I get an error: >Cannot read field "parent" because "comp" is null.
I've tried other layout on JFrame and JPanel and still it didn't show.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class test implements ActionListener{
public static void main(String [] args) {
new test();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public test(){
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080,720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void cubePanel(){
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.decode("#FAF7FH"));
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == sphereButton){
new sphereFrame();
frame.dispose();
}
if(e.getSource() == rightCylinderButton){
new rightCylinderFrame();
frame.dispose();
}
if(e.getSource() == rightConeButton){
new rightConeFrame();
frame.dispose();
}
if(e.getSource() == rectangularPrismButton){
new rectangularPrismFrame();
frame.dispose();
}
if(e.getSource() == triangularPrismButton){
new triangularPrismFrame();
frame.dispose();
}
if(e.getSource() == cubeButton){
frame.getContentPane().removeAll();
frame.add(cubePanel);
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Here's the GUI I created.
Press the "Cube" button to bring up the page for the cube calculation.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The JFrame has a default BorderLayout and holds the main JPanel. The main JPanel uses a CardLayout to display the various calculation JPanels. Using a CardLayout is much easier than managing multiple JFrames and provides a nicer user experience.
I used Swing layout managers to position the Swing components on the various JPanels.
The start JPanel consists of two subordinate JPanels. The title JPanel uses a FlowLayout to display the title. The button JPanel uses a GridLayout to display the various calculation JButtons. You can create complex JPanels by nesting multiple simple JPanels.
The cube calculation JPanel was the only one you had in your code, so it was the only one I created. I made it a method, but you can create a separate class for each of the calculations. The cube calculation JPanel uses a GridBagLayout to create a form-like JPanel. I used lambda expressions to create the ActionListener for each of the JButtons, since they were so simple.
I made the start JPanel button ActionListener a separate class just to get the code away from the for loop that creates the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
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.JTextField;
import javax.swing.SwingUtilities;
public class CardLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutGUI());
}
private CardLayout cardLayout;
private JTextField edgeTextField, surfaceAreaSolutionTextField;
private JPanel mainPanel;
#Override
public void run() {
JFrame frame = new JFrame("Calculating for Surface Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createStartPanel(), "Start");
panel.add(createCubeCalculationPanel(), "Cube");
return panel;
}
private JPanel createStartPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(Font.DIALOG, Font.PLAIN, 36);
JLabel label = new JLabel("Calculator for the Surface Area of:");
label.setFont(font);
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
String[] text = { "Sphere", "Right Cylinder", "Right Cone",
"Rectangular Prism", "Triangular Prism", "Cube",
"Square Pyramid", "Rectangular Pyramid", "Ellipsoid",
"Tetrahedron" };
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(null, Font.PLAIN, 24);
ButtonListener listener = new ButtonListener();
for (String s : text) {
JButton button = new JButton(s);
button.addActionListener(listener);
button.setFont(font);
panel.add(button);
}
return panel;
}
private JPanel createCubeCalculationPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font titleFont = new Font(null, Font.PLAIN, 32);
Font font = new Font(null, Font.PLAIN, 16);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.weighty = 1.0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("SA = 6a²");
label.setFont(titleFont);
panel.add(label, gbc);
gbc.gridwidth = 1;
gbc.gridy++;
label = new JLabel("Edge:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
edgeTextField = new JTextField(10);
edgeTextField.setFont(font);
panel.add(edgeTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("SA:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
surfaceAreaSolutionTextField = new JTextField(10);
surfaceAreaSolutionTextField.setFont(font);
surfaceAreaSolutionTextField.setEditable(false);
panel.add(surfaceAreaSolutionTextField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(event -> {
double edge = Double.valueOf(edgeTextField.getText());
double sa = 6.0 * edge * edge;
surfaceAreaSolutionTextField.setText(Double.toString(sa));
});
calculateButton.setFont(font);
panel.add(calculateButton, gbc);
gbc.gridy++;
JButton backButton = new JButton("Back");
backButton.addActionListener(event -> {
cardLayout.show(mainPanel, "Start");
});
backButton.setFont(font);
panel.add(backButton, gbc);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
cardLayout.show(mainPanel, text);
}
}
}
Try this :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class Test2 implements ActionListener {
public static void main(String[] args) {
new Test2();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public Test2() {
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public Container cubePanel() {
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.getColor("#FAF7FH"));
return container;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sphereButton) {
new sphereFrame();
frame.dispose();
}
if (e.getSource() == rightCylinderButton) {
new rightCylinderFrame();
frame.dispose();
}
if (e.getSource() == rightConeButton) {
new rightConeFrame();
frame.dispose();
}
if (e.getSource() == rectangularPrismButton) {
new rectangularPrismFrame();
frame.dispose();
}
if (e.getSource() == triangularPrismButton) {
//new triangularPrismFrame();
frame.dispose();
}
if (e.getSource() == cubeButton) {
frame.getContentPane().removeAll();
frame.add(cubePanel());
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
}

How to switch between two JPanels without CardLayout?

I build a game in swing and I have two JPanels for menu and the game itself. I want to switch from the menu panel to the game panel and from the game to the menu using JButtons. but every time I switch from the menu to the game, I want to start over the game and send the name of the player from some textField in the menu panel. so I need to make now instance of the game panel. How can I do this?
Here's the menu panel:
public class MenuPanel extends JPanel {
private JPanel contentPane;
private JTextField txtName;
public MenuPanel(JPanel panel) {
setLayout(null);
contentPane = panel;
JButton btnStart = new JButton("Click to start the game");
btnStart.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, "Game Panel");
}
});
btnStart.setFont(new Font("Baskerville Old Face", btnStart.getFont().getStyle(), 25));
btnStart.setBounds(290, 510, 290, 70);
add(btnStart);
txtName = new JTextField();
txtName.setBounds(450, 460, 160, 20);
add(txtName);
txtName.setColumns(10);
JLabel lblName = new JLabel("Enter your name:");
lblName.setForeground(SystemColor.text);
lblName.setFont(new Font("Bradley Hand ITC", Font.BOLD, 20));
lblName.setBounds(260, 460, 180, 20);
add(lblName);
JLabel lblGame = new JLabel("RUMMIKUB GAME");
lblGame.setForeground(new Color(0, 0, 0));
lblGame.setHorizontalAlignment(SwingConstants.CENTER);
lblGame.setFont(new Font("Goudy Old Style", lblGame.getFont().getStyle(), 50));
lblGame.setBounds(180, 100, 500, 140);
add(lblGame);
}
}
Here's the game panel:
public class GamePanel extends JPanel {
private JPanel contentPane;
private JButton btnReturnToMenu;
private TileButton[][] buttons = new TileButton[Constants.ROWS_IN_PLAYER_BOARD][Constants.COLUMNS_IN_PLAYER_BOARD];
private JLabel lblHello;
private TileButton btnThrownByPlayer;
private TileButton btnThrownByOpponent;
private Point clickedButton;
private JButton btnPullFromPool;
private JButton btnFinish;
private Game game;
public GamePanel(String firstPlayerName, String secondPlayerName, JPanel panel) {
setLayout(null);
contentPane = panel;
clickedButton = null;
game = new Game(firstPlayerName, secondPlayerName);
lblHello = new JLabel("hello " + firstPlayerName + " and " + secondPlayerName);
lblHello.setBounds(10, 10, 250, 40);
add(lblHello);
//initiate exit button.
btnReturnToMenu = new JButton("Return To Menu");
btnReturnToMenu.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, "Menu Panel");
}
});
btnReturnToMenu.setFont(new Font("Mongolian Baiti", Font.BOLD, 16));
btnReturnToMenu.setBounds(10, 70, 200, 40);
add(btnReturnToMenu);
// initiate finish button.
btnFinish = new JButton("Finish");
btnFinish.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (btnFinish.isEnabled()) {
if (game.finish()) {
JOptionPane.showMessageDialog(null,
"You finish the game.\nCongratulations, you are the winner!!!");
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, "Finish Panel");
} else {
btnFinish.setEnabled(false);
JOptionPane.showMessageDialog(null, "You didn't finish the game yet");
}
}
}
});
btnFinish.setFont(new Font("Mongolian Baiti", Font.BOLD, 16));
btnFinish.setBounds(750, 50, 100, 40);
add(btnFinish);
}
}
Here's the frame:
public class MainFrame extends JFrame {
private JPanel contentPane;
private GamePanel gamePanel;
private MenuPanel menuPanel;
private FinishPanel finishPanel;
private MainFrame() {
//super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(233, 55, 900, 627);
setResizable(false);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new CardLayout());
menuPanel = new MenuPanel(contentPane);
gamePanel = new GamePanel("", "", contentPane);
finishPanel = new FinishPanel(contentPane);
contentPane.add(menuPanel, "Menu Panel");
contentPane.add(gamePanel, "Game Panel");
contentPane.add(finishPanel, "Finish Panel");
getContentPane().add(contentPane, BorderLayout.CENTER);
pack();
setLocationByPlatform(true);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
}
Thanks for the help!

Overlay a picture over background picture

I'm making a street fighter game in java, I have all the background pictures finished, and I'm trying to add the characters onto the background, but in the output the character picture keeps appearing next to the background instead of on top of it. I want the character to appear on top of the background, just like a normal street fighter game.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.Border;
import java.awt.Image;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class CastleFighter extends JFrame {
Image image;
public static void main(String[] args) {
CastleFighter angela = new CastleFighter();
angela.runIt();
}
public void runIt() {
final JFrame frame = new JFrame("Castle Fighter");
frame.setSize(500, 477);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pa = new JPanel();
JButton ba1 = new JButton("Start");
ba1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
final JFrame frame2 = new JFrame("Menu");
frame2.setDefaultCloseOperation(HIDE_ON_CLOSE);
JPanel pa2 = new JPanel();
frame2.add(pa2);
ImageIcon iii = new ImageIcon(this.getClass().getResource("fight.gif"));
JLabel imageLabel2 = new JLabel();
imageLabel2.setIcon(iii);
pa2.add(imageLabel2, java.awt.BorderLayout.CENTER);
frame2.setVisible(true);
frame2.pack();
frame2.requestFocus();
imageLabel2.setLayout(new GridLayout(3, 0));
JButton ba2 = new JButton("How to play");
ba2.setFont(new Font("Merriweather", Font.PLAIN, 28));
imageLabel2.add(ba2, BorderLayout.SOUTH);
ba2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame3 = new JFrame("How to play");
frame3.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa3 = new JPanel();
frame3.add(pa3);
JButton ba5 = new JButton("Return to menu");
ba5.setFont(new Font("Merriweather", Font.PLAIN, 28));
ba5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame3.dispose();
frame2.setVisible(true);
}
});
pa3.setLayout(new BorderLayout());
pa3.add(ba5, BorderLayout.SOUTH);
ImageIcon iiiii = new ImageIcon(this.getClass().getResource("ezgif.com-crop-7.gif"));
JLabel imageLabel4 = new JLabel();
imageLabel4.setIcon(iiiii);
pa3.add(imageLabel4, java.awt.BorderLayout.CENTER);
frame3.setVisible(true);
frame3.pack();
frame3.requestFocus();
}
});
JButton ba3 = new JButton("Start game");
ba3.setFont(new Font("RussoOne", Font.PLAIN, 28));
imageLabel2.add(ba3, BorderLayout.CENTER);
ba3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame2.dispose();
final JFrame frame4 = new JFrame("Level one");
frame4.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JPanel pa4 = new JPanel();
frame4.add(pa4);
ImageIcon iiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-7.gif"));
JLabel imageLabel3 = new JLabel();
imageLabel3.setIcon(iiii);
pa4.add(imageLabel3, java.awt.BorderLayout.CENTER);
ImageIcon i14 = new ImageIcon(this.getClass().getResource("fightercharacter.gif"));
JLabel imageLabel14 = new JLabel();
imageLabel14.setIcon(i14);
pa4.add(imageLabel14, java.awt.BorderLayout.NORTH);
JButton ba6 = new JButton("menu");
ba6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
frame2.setVisible(true);
}
});
pa4.add(ba6);
JButton ba7 = new JButton("Level two");
ba7.setSize(400, 200);
pa4.add(ba7);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame4.dispose();
final JFrame frame6 = new JFrame("Level two");
frame6.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame6.setVisible(true);
JPanel pa6 = new JPanel();
frame6.add(pa6);
ImageIcon iiiiiii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-6.gif"));
JLabel imageLabel6 = new JLabel();
imageLabel6.setIcon(iiiiiii);
pa6.add(imageLabel6, BorderLayout.CENTER);
frame6.pack();
frame6.requestFocus();
JButton ba7 = new JButton("menu");
pa6.add(ba7, BorderLayout.SOUTH);
ba7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame2.setVisible(true);
}
});
JButton ba9 = new JButton("Level one");
pa6.add(ba9, BorderLayout.SOUTH);
ba9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame6.dispose();
frame4.setVisible(true);
}
});
frame6.setVisible(true);
frame6.pack();
frame6.requestFocus();
}
});
frame4.setVisible(true);
frame4.pack();
frame4.requestFocus();
}
});
JButton ba4 = new JButton("Quit game");
ba4.setFont(new Font("MerriWeather", Font.PLAIN, 28));
imageLabel2.add(ba4, BorderLayout.WEST);
ba4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame2.requestFocus();
ba2.setOpaque(false);
ba2.setContentAreaFilled(false);
ba2.setBorderPainted(false);
ba2.setForeground(Color.WHITE);
ba3.setOpaque(false);
ba3.setContentAreaFilled(false);
ba3.setBorderPainted(false);
ba3.setForeground(Color.WHITE);
ba4.setOpaque(false);
ba4.setContentAreaFilled(false);
ba4.setBorderPainted(false);
ba4.setForeground(Color.WHITE);
}
});
ba1.setPreferredSize(new Dimension(100, 100));
ba1.setFont(new Font("RussoOne", Font.PLAIN, 28));
ba1.setBackground(Color.BLUE);
ba1.setOpaque(true);
frame.add(pa);
pa.setLayout(new BorderLayout());
pa.add(ba1, BorderLayout.SOUTH);
ImageIcon ii = new ImageIcon(this.getClass().getResource("ezgif.com-add-text-2.gif"));
JLabel imageLabel = new JLabel();
imageLabel.setIcon(ii);
pa.add(imageLabel, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
frame.pack();
frame.requestFocus();
}
}

Problems with having a "this" statement in my source

so this is the current code and it has been so far working except for the background color, anything that has "//" before it is what causes errors between other things
package com.Luminate.luminatemedia;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame implements ActionListener{
static JFrame mediaform = new JFrame();
public static void main(String[] args) {
}
public static void load() {
ImageIcon fileIcon = new ImageIcon ("assets/icon.png");
ImageIcon exitIcon = new ImageIcon ("assets/exit.png");
JButton exitButton = new JButton();
JLabel text = new JLabel("Luminate Media");
JPanel panel = new JPanel();
mediaform.add(panel);
panel.add(exitButton);
panel.add(text);
mediaform.setTitle("Luminate");
mediaform.setIconImage(fileIcon.getImage());
mediaform.setBounds(0, 688, 1366, 40);
//mediaform.setLayout(null);
mediaform.setUndecorated(true);
mediaform.setResizable(false);
mediaform.setVisible(true);
mediaform.setAlwaysOnTop(true);
//mediaform.getContentPane().setBackground(Color.DARK_GRAY);
mediaform.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text.setFont(new Font("dandelion in the spring", Font.PLAIN, 32));
text.setBounds(0, 0, 0, 0);
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setSize(0, 0);
text.setForeground(Color.black);
text.setHorizontalAlignment(0);
exitButton.setBorder(null);
exitButton.setBounds(1326, 0, 40, 40);
exitButton.addActionListener(null);
exitButton.setIcon(exitIcon);
//BELOW IS MY ISSUE
exitButton.addActionListener(this);
panel.setLayout(null);
panel.setBackground(DARK_GRAY);
}
#Override
public void actionPerformed(ActionEvent e) {
//code to close the whole program
}
}
so there's an error with the emphasized text where it says "this"
also what would the code be to close the main class at the click of the button and am I doing this correctly ?
Try this
public class Window extends JFrame implements ActionListener{
public static void main(String[] args) {
new Window();
}
public Window() {
ImageIcon fileIcon = new ImageIcon ("assets/icon.png");
ImageIcon exitIcon = new ImageIcon ("assets/exit.png");
JButton exitButton = new JButton("Label");
JLabel text = new JLabel("Luminate Media");
JPanel panel = new JPanel();
setTitle("Luminate");
setIconImage(fileIcon.getImage());
setBounds(0, 688, 1366, 40);
setLayout(null);
setUndecorated(true);
setResizable(false);
setVisible(true);
setAlwaysOnTop(true);
getContentPane().setBackground(Color.DARK_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text.setFont(new Font("dandelion in the spring", Font.PLAIN, 32));
text.setBounds(0, 0, 0, 0);
text.setHorizontalAlignment(SwingConstants.CENTER);
text.setSize(0, 0);
text.setForeground(Color.black);
text.setHorizontalAlignment(0);
exitButton.setBorder(null);
exitButton.setBounds(1326, 0, 40, 40);
exitButton.setIcon(exitIcon);
exitButton.addActionListener(this);
panel.setLayout(null);
panel.setBackground(DARK_GRAY);
panel.add(exitButton);
panel.add(text);
add(panel);
}
#Override
public void actionPerformed(ActionEvent e) {
//code to close the whole program
}
}

How Do I get the buttons to work? Java Programming

I created an Address Book GUI, I just don't understand How to make the save and delete buttons to work, so when the user fills the text fields they can click save and it saves to the JList I have created and then they can also delete from it. How Do I Do this?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddressBook {
private JLabel lblFirstname,lblSurname, lblMiddlename, lblPhone,
lblEmail,lblAddressOne, lblAddressTwo, lblCity, lblPostCode, picture;
private JTextField txtFirstName, txtSurname, txtAddressOne, txtPhone,
txtMiddlename, txtAddressTwo, txtEmail, txtCity, txtPostCode;
private JButton btSave, btExit, btDelete;
private JList contacts;
private JPanel panel;
public static void main(String[] args) {
new AddressBook();
}
public AddressBook(){
JFrame frame = new JFrame("My Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.cyan);
lblFirstname = new JLabel("First name");
lblFirstname.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblFirstname.setFont(styleOne);
panel.add(lblFirstname);
txtFirstName = new JTextField();
txtFirstName.setBounds(210, 50, 150, 20);
panel.add(txtFirstName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(385,50,150,20);
Font styleTwo = new Font ("Arial",Font.BOLD,13);
lblSurname.setFont(styleTwo);
panel.add(lblSurname);
txtSurname = new JTextField();
txtSurname.setBounds(450,50,150,20);
panel.add(txtSurname);
lblMiddlename = new JLabel ("Middle Name");
lblMiddlename.setBounds(620,50,150,20);
Font styleThree = new Font ("Arial", Font.BOLD,13);
lblMiddlename.setFont(styleThree);
panel.add(lblMiddlename);
txtMiddlename = new JTextField();
txtMiddlename.setBounds(710,50,150,20);
panel.add(txtMiddlename);
lblPhone = new JLabel("Phone");
lblPhone.setBounds(160,100,100,20);
Font styleFour = new Font ("Arial", Font.BOLD,13);
lblPhone.setFont(styleFour);
panel.add(lblPhone);
txtPhone = new JTextField();
txtPhone.setBounds(210,100,150,20);
panel.add(txtPhone);
lblEmail = new JLabel("Email");
lblEmail.setBounds(410,100,100,20);
Font styleFive = new Font ("Arial", Font.BOLD,13);
lblEmail.setFont(styleFive);
panel.add(lblEmail);
txtEmail = new JTextField();
txtEmail.setBounds(450,100,150,20);
panel.add(txtEmail);
lblAddressOne = new JLabel("Address 1");
lblAddressOne.setBounds(145,150,100,20);
Font styleSix = new Font ("Arial", Font.BOLD,13);
lblAddressOne.setFont(styleSix);
panel.add(lblAddressOne);
txtAddressOne = new JTextField();
txtAddressOne.setBounds(210,150,150,20);
panel.add(txtAddressOne);
lblAddressTwo = new JLabel("Address 2");
lblAddressTwo.setBounds(145,200,100,20);
Font styleSeven = new Font ("Arial", Font.BOLD,13);
lblAddressTwo.setFont(styleSeven);
panel.add(lblAddressTwo);
txtAddressTwo = new JTextField();
txtAddressTwo.setBounds(210,200,150,20);
panel.add(txtAddressTwo);
lblCity = new JLabel("City");
lblCity.setBounds(180,250,100,20);
Font styleEight = new Font ("Arial", Font.BOLD,13);
lblCity.setFont(styleEight);
panel.add(lblCity);
txtCity = new JTextField();
txtCity.setBounds(210,250,150,20);
panel.add(txtCity);
lblPostCode = new JLabel("Post Code");
lblPostCode.setBounds(380,250,100,20);
Font styleNine = new Font ("Arial", Font.BOLD,13);
lblPostCode.setFont(styleNine);
panel.add(lblPostCode);
txtPostCode = new JTextField();
txtPostCode.setBounds(450,250,150,20);
panel.add(txtPostCode);
//image
ImageIcon image = new ImageIcon("C:\\Users\\Hassan\\Desktop\\icon.png");
picture = new JLabel(image);
picture.setBounds(600,90, 330, 270);
panel.add(picture);
//buttons
btSave = new JButton ("Save");
btSave.setBounds(380,325,100,20);
panel.add(btSave);
btDelete = new JButton ("Delete");
btDelete.setBounds(260,325,100,20);
panel.add(btDelete);
btExit = new JButton ("Exit");
btExit.setBounds(500,325,100,20);
panel.add(btExit);
btExit.addActionListener(new Action());
//list
contacts=new JList();
contacts.setBounds(0,10,125,350);
panel.add(contacts);
frame.add(panel);
frame.setVisible(true);
}
//button actions
static class Action implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFrame option = new JFrame();
int n = JOptionPane.showConfirmDialog(option,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
Buttons need Event Handlers to work. You have not added any Event Handlers to the Save and Delete buttons. You need to call the addActionListener on those buttons too.
I recommend anonymous inner classes:
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
You need to addActionListener to the buttons btSave and btDelete.
You could create a anonymous class like this and perform your work there.
btSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
btDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//Do you work for the button here
}
}
Edit:
I have an example to which you can refer to and accordingly make changes by understanding it. I got it from a professor at our institute.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TooltipTextOfList{
private JScrollPane scrollpane = null;
JList list;
JTextField txtItem;
DefaultListModel model;
public static void main(String[] args){
TooltipTextOfList tt = new TooltipTextOfList();
}
public TooltipTextOfList(){
JFrame frame = new JFrame("Tooltip Text for List Item");
String[] str_list = {"One", "Two", "Three", "Four"};
model = new DefaultListModel();
for(int i = 0; i < str_list.length; i++)
model.addElement(str_list[i]);
list = new JList(model){
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (-1 < index) {
String item = (String)getModel().getElementAt(index);
return item;
} else {
return null;
}
}
};
txtItem = new JTextField(10);
JButton button = new JButton("Add");
button.addActionListener(new MyAction());
JPanel panel = new JPanel();
panel.add(txtItem);
panel.add(button);
panel.add(list);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction extends MouseAdapter implements ActionListener{
public void actionPerformed(ActionEvent ae){
String data = txtItem.getText();
if (data.equals(""))
JOptionPane.showMessageDialog(null,"Please enter text in the Text Box.");
else{
model.addElement(data);
JOptionPane.showMessageDialog(null,"Item added successfully.");
txtItem.setText("");
}
}
}
}

Categories

Resources