JPanel sizing inside Another JPanel - java

I really need help with this. I have been having problems resizing the gameBoardPanel JPanel that is added the the main Panel. Everything I have tried including resizing it has not helped, I basically want to add the gameBoardPanel at 400x400 to the main panel (which is 400x500), leaving me 400x100 of space for other buttons e.x return to menu, etc. Any help would be much appreciated!
Thanks!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.*;
public class SliderPractice extends JFrame implements ActionListener {
private int numberOfRows, mode;
private JPanel gameBoardPanel, menuPanel, main; //create a panel to add to JFRAME
private int emptyIndex; //Variable will track the empty spot
private int moves = 0;
JButton[] buttons, compareButtons;
private JLabel radioButtons, radioButtons1;
private ButtonGroup radioButtonGroup1, radioButtonGroup2;
private JButton start, displayInstructions = new JButton(); //buttons on start panel
private JTextArea title;
private JRadioButton easy, medium, hard, extreme, three, four, five, six; //Radio buttons allow user to only select 1 of 3
public SliderPractice()
{
super("Slider! - By: Michel V.");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400); //Overall size of grid but window
//is resizable by default. Layout
//Manager takes care of the necessary scaling.
setResizable(false); //set resizable false for menu
menu(); //calling menu
}
public void actionPerformed(ActionEvent e) { //when an action is performed
if (e.getSource().equals(start)){ //Start button
startUp(); //starts up game
}
for(int i = 0 ; i < buttons.length; i++) //checks for all the game buttons if any were pressed
{
if(e.getSource() == buttons[i]) //if a specific game button is pressed
{
if(isNextTo(i, emptyIndex)==true) //calling isNextTo to make sure its beside one another
{
swapPieces(i); //if its beside, swap pieces and increase number of moves
moves++;
}
}
}
if(win()){ //if Win == true
int select = JOptionPane.showConfirmDialog(this, "You won with " + moves + " moves! Play same settings again(Y/N)?\n Or press cancel to exit!");
//Yes clicked - Play again
if (select == JOptionPane.YES_OPTION){
scramble();
moves = 0;
}//no picked, resetGUI!
else if (select == JOptionPane.NO_OPTION){
resetGUI();
}//if Cancel or closed is picked, exit program
else if (select == JOptionPane.CANCEL_OPTION){
System.exit(0);
}
else if (select == JOptionPane.CLOSED_OPTION){
System.exit(0);
}
}
}
public void gamePanel(int numberRows){
numberOfRows = numberRows;
buttons = new JButton[numberOfRows*numberOfRows]; //Make room for as many buttons as needed for picked number of Rows
compareButtons = new JButton[numberOfRows*numberOfRows];
Font f = new Font("Arial", Font.BOLD, 22);
Color[] colours = {Color.red, Color.green};
gameBoardPanel = new JPanel();
gameBoardPanel.setLayout(new GridLayout(numberOfRows,numberOfRows,5,5)); // 4x4 grid with 5 pixel
// vert/horz dividers
gameBoardPanel.setBackground(Color.white); //Allows empty space to be black
for (int i = 0; i < buttons.length; i++) //From i is 0 to 15
{
int colourIndex = 0; //Start with Orange
compareButtons[i] = new JButton("" + i);
buttons[i] = new JButton("" + i); //Constructor sets text on new buttons
buttons[i].setSize(100,100); //Button size, but don't really need this line
//line since we are using Layout Manager
if (numberOfRows %2 ==0){
if (i % 2 == 0) //Alternate orange and white for evens and odds
colourIndex = 1;
if ((i/4)%2 == 0)
colourIndex = 1-colourIndex;
}
else{
if(i % 2 == 0)
colourIndex = 1;
}
buttons[i].setBackground(colours[colourIndex]);
buttons[i].setForeground(Color.white); //Text colour
buttons[i].setFont(f);
buttons[i].addActionListener(this); //Set up ActionListener on each button
gameBoardPanel.add(buttons[i]); //Add buttons to the grid layout of
//gameBoardPanel
}
emptyIndex=(numberOfRows*numberOfRows-1);
buttons[emptyIndex].setVisible(false);
}
public void menu(){
Font f = new Font("Arial", Font.BOLD, 26);
Font t = new Font("Trebuchet MS", Font.BOLD, 13);
Color[] colours = {Color.red, Color.green};
/*--- JPanel for Start Menu ---*/
menuPanel = new JPanel();
menuPanel.setLayout(null);
menuPanel.setBackground(colours[0]);
menuPanel.setVisible(true);
//Title
title = new JTextArea("Michel's Slider \n Game!");
title.setLineWrap(true);
title.setWrapStyleWord(true);
title.setBounds(100, 10, 250, 60);
title.setFont(f);
title.setBorder(BorderFactory.createEmptyBorder());
title.setBackground(colours[0]);
title.setEditable(false);
title.setEnabled(false);
title.setDisabledTextColor(Color.BLACK);
//Label for radio buttons
radioButtons = new JLabel("Choose the difficulty for this game:");
radioButtons.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
radioButtons.setBounds(50, 155, 400, 20);
//Radio buttons to select picture to play with
easy = new JRadioButton("Easy");
easy.setBackground(colours[0]);
easy.setBounds(15, 178, 100, 20);
easy.setActionCommand("Mode 1");
easy.setFont(t);
easy.setSelected(true); //Default selection
medium = new JRadioButton("Medium");
medium.setBackground(colours[0]);
medium.setBounds(120, 178, 100, 20);
medium.setFont(t);
hard = new JRadioButton("Hard");
hard.setBackground(colours[0]);
hard.setBounds(215, 178, 100, 20);
hard.setFont(t);
extreme = new JRadioButton("Extreme");
extreme.setBackground(colours[0]);
extreme.setBounds(310, 178, 100, 20);
extreme.setFont(t);
//Add radio buttons to a group
radioButtonGroup1 = new ButtonGroup();
radioButtonGroup1.add(easy);
radioButtonGroup1.add(medium);
radioButtonGroup1.add(hard);
radioButtonGroup1.add(extreme);
radioButtons1 = new JLabel("Choose the size for this game:");
radioButtons1.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
radioButtons1.setBounds(68, 100, 400, 20);
//Radio buttons to select picture to play with
three = new JRadioButton("3x3");
three.setBackground(colours[0]);
three.setBounds(15, 124, 110, 20);
three.setActionCommand("Mode 1");
three.setFont(t);
three.setSelected(true); //Default selection
four = new JRadioButton("4x4");
four.setBackground(colours[0]);
four.setBounds(120, 124, 100, 20);
four.setFont(t);
five = new JRadioButton("5x5");
five.setBackground(colours[0]);
five.setBounds(215, 124, 100, 20);
five.setFont(t);
six = new JRadioButton("6x6");
six.setBackground(colours[0]);
six.setBounds(310, 124, 100, 20);
six.setFont(t);
//Add radio buttons to a group
radioButtonGroup2 = new ButtonGroup();
radioButtonGroup2.add(three);
radioButtonGroup2.add(four);
radioButtonGroup2.add(five);
radioButtonGroup2.add(six);
//Start game button
start = new JButton("Start Game");
start.addActionListener(this);
start.setBounds(110, 290, 170, 35);
start.setBackground(colours[1]);
start.setFont(new Font("Trebuchet MS", Font.BOLD, 22));
//Instructions button
displayInstructions = new JButton("Instructions");
displayInstructions.addActionListener(this);
displayInstructions.setBounds(130, 335, 130, 20);
displayInstructions.setBackground(colours[1]);
displayInstructions.setFont(new Font("Trebuchet MS", Font.BOLD, 17));
//Add components to start panel
menuPanel.add(start);
menuPanel.add(displayInstructions);
menuPanel.add(title);
menuPanel.add(easy);
menuPanel.add(medium);
menuPanel.add(hard);
menuPanel.add(extreme);
menuPanel.add(radioButtons);
menuPanel.add(three);
menuPanel.add(four);
menuPanel.add(five);
menuPanel.add(six);
menuPanel.add(radioButtons1);
/*--- End Start Menu JPanel ---*/
add(menuPanel);
setVisible(true);
}
public static void main(String[] args) {
new SliderPractice(); //Run constructor for class
}
private void swapPieces(int btnIndex) //Send along button that was pushed
{
buttons[emptyIndex].setText(buttons[btnIndex].getText()); //Move over text
//to blank button
buttons[btnIndex].setVisible(false); //Turn off visibility of button that was pushed
//and background will show through as black
buttons[emptyIndex].setVisible(true);//Turn on visibility of the old blank button
emptyIndex = btnIndex; //Update the emptyIndex to the button that was
//pushed.
}
private boolean isNextTo(int choice, int blankButton)
{
if(choice/numberOfRows==blankButton/numberOfRows){
if(Math.abs(choice-blankButton)==1) return true;
}
else if(Math.abs(choice/numberOfRows-blankButton/numberOfRows)==1) {
if(Math.abs(choice-blankButton)==numberOfRows) {
return true;
}
}
return false;
}
private boolean win()
{
int count = 0;
for (int i = 0; i < buttons.length; i++) //From i is 0 to 15
{
if(buttons[i].getText().equals(compareButtons[i].getText()))
{
count++;
}
else{
break;
}
}
if (count == (numberOfRows*numberOfRows-1))
return true;
else
return false;
}
private void scramble()
{
int s = 0;
int g;
int max = (int) Math.pow(numberOfRows, mode);
while (s<max)
{
g = (int) ((Math.random()*(numberOfRows*numberOfRows))-1);
if(isNextTo(g, emptyIndex)==true)
{
swapPieces(g);
s++;
}
}
}
private void startUp(){
int size = 0;
//Set image on button according to radio button selection
if (three.isSelected()){
size = 3;
}
else if (four.isSelected()){
size = 4;
}
else if (five.isSelected()){
size = 5;
}
else if (six.isSelected()){
size = 6;
}
if (easy.isSelected()){
mode = 2;
}
else if (medium.isSelected()){
mode = 3;
}
else if (hard.isSelected()){
mode = 4;
}
else if (extreme.isSelected()){
mode = 5;
}
gamePanel(size);
setSize(400, 500);
gameBoardPanel.setEnabled(false);
//Switch panels from start panel to main panel
main = new JPanel();
menuPanel.setVisible(false);
remove(menuPanel);
main.add(gameBoardPanel);
main.setSize(400, 400);
main.setBackground(Color.white);
add(main);
setResizable(true);
//Shuffle Pieces
scramble();
}
private void resetGUI(){
numberOfRows = 0;
moves = 0;
emptyIndex = 0;
setResizable(false);
setSize(400,400);
remove(gameBoardPanel);
add(menuPanel);
menu();
mode = 0;
}
}

It's really hard to understand what you want to achieve. You want to make room to which buttons at the bottom?? How is the screen supposed to look like?
Anyway, i think you should use different panels and layoutmanagers to solve your problem, and what I think can help you best is the BorderLayout.
If you want your gameBoardPanel to fully fit the window when the game starts, you could change your code to something like this at the end of your startUp() method:
//Switch panels from start panel to main panel
main = new JPanel(new BorderLayout());
menuPanel.setVisible(false);
remove(menuPanel);
main.add(gameBoardPanel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
buttonsPanel.setPreferredSize(new Dimension(400, 100));
main.add(buttonsPanel, BorderLayout.SOUTH);

From looking at your code it is obvious you haven't read the layout manager tutorials. From your description you almost certainly want to use BorderLayout, put your game panel in CENTER and your button panel in SOUTH.
The component in CENTER position gets all left over space and the component in SOUTH gets its preferred height honored, but takes all available width.
https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

Related

Java Swing button creates a dupe on the panel below it

We have this assignment where we make a GUI window which sets a panel's color based on RGB-Alpha values. I got it mostly working, but when I click the change color button, it duplicates (I'm not sure if its only visual bug) a clicked state of itself under it. It's not visible if alpha is 255 because it's fully opaque, but if it's transparent, the visual glitch thing is visible.
Screenshots of Window/Frame: https://imgur.com/a/Vf1Hb2B
This is my current code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class ColorCalc implements ActionListener {
//Containers
private JFrame f;
private JPanel colorPanel;
//Components
private JLabel l1,l2,l3,l4;
private JTextField redTf,greenTf,blueTf,alphaTf;
private JButton bCompute,bClear;
public ColorCalc()
{
//Containers
f = new JFrame("My Color Calculator");
f.setPreferredSize(new Dimension(400, 250));//Set Frame Size
colorPanel = new JPanel();
colorPanel.setPreferredSize(new Dimension(300, 200));//Set Panel Size
//Components
l1 = new JLabel("Red:");
l2 = new JLabel("Green:");
l3 = new JLabel("Blue:");
l4 = new JLabel("Alpha:");
redTf = new JTextField("0", 3);
greenTf = new JTextField("0", 3);
blueTf = new JTextField("0", 3);
alphaTf = new JTextField("0", 3);
bCompute = new JButton("Compute");
bClear = new JButton("Clear");
//Action Listeners
bCompute.addActionListener(this);
bClear.addActionListener(this);
}
public void startApp()
{
//Labels Panel
JPanel lPanel = new JPanel();
lPanel.setLayout(new GridLayout(5,1));
lPanel.add(l1);
lPanel.add(l2);
lPanel.add(l3);
lPanel.add(l4);
lPanel.add(bCompute);
//Text Fields Panel
JPanel tfPanel = new JPanel();
tfPanel.setLayout(new GridLayout(5,1));
tfPanel.add(redTf);
tfPanel.add(greenTf);
tfPanel.add(blueTf);
tfPanel.add(alphaTf);
tfPanel.add(bClear);
//Labels + TextFields Panel
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new GridLayout(1,2));
inputPanel.add(lPanel);
inputPanel.add(tfPanel);
//Add all panels to Frame
f.setLayout(new GridLayout(2,1));
f.add(inputPanel);
f.add(colorPanel);
f.setLocationRelativeTo(null);
f.pack();
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == bCompute)
{
//Set Default Values
int red = 255;
int green = 255;
int blue = 255;
int alpha = 255;
try
{
//Get Values and Parse to Integer
red = Integer.parseInt(redTf.getText());
green = Integer.parseInt(greenTf.getText());
blue = Integer.parseInt(blueTf.getText());
alpha = Integer.parseInt(alphaTf.getText());
} catch (NumberFormatException nfe)//If Parsing failed due to invalid types
{
red = 255; green = 255; blue = 255; alpha = 255; //Set values to white
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
if(red < 256 && green < 256 && blue < 256 && alpha < 256)//Max Value: 255
{
if(red > -1 && green > -1 && blue > -1 && alpha > -1)//Min Value: 0
colorPanel.setBackground(new Color(red, green, blue, alpha));
else
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
else
JOptionPane.showMessageDialog(null, "Invalid Inputs (RGB,Alpha values 0-255)");
}
else if(e.getSource() == bClear)
{
//Set all values to 0 and set panel to white
redTf.setText("0");
greenTf.setText("0");
blueTf.setText("0");
alphaTf.setText("0");
colorPanel.setBackground(Color.WHITE);
}
}
public static void main(String[] args)
{
ColorCalc colCalc = new ColorCalc();
colCalc.startApp();
}
}
Call the method f.repaint(); at the end of the actionPerformed() method
See more info here

JTextField not editable with JFrame as parent, JWindow making method unpaintable

I have the following code
private JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
private JWindow hsWindow = new JWindow(frame);
hsWindow.setPreferredSize(new Dimension(400, 200));
JButton btnSave = new JButton("Save");
JButton btnCancel = new JButton("Cancel");
JLabel lblName = new JLabel("Enter your name: ");
JTextField txtName = new JTextField();
hsWindow.add(btnSave);
hsWindow.add(btnCancel);
hsWindow.add(lblName);
hsWindow.add(txtName);
hsWindow.setVisible(true);
hsWindow.setFocusable(true);
hsWindow.setLocationRelativeTo(frame);
btnSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
hsName = txtName.getText();
saveHighScores();
hsWindow.setVisible(false);
hsWindow.setFocusable(false);
txtName.setText("");
setHighScores();
gameOver(g);
}
});
Can someone tell me why the JTextField is not editable?
The field itself is there, but I cannot type in it.
Also, when I call my method gameOver(g) without the JWindow appearing, everything is fine. However, if I have the JWindow appear and call it after pushing the button, my gameOver method is not properly painted.
Why is that?
Here is the important parts of the gameOver method
private void gameOver(Graphics g){
int z = 25;
score = dots - 3; //The amount of apples collected = your score
String msg = "Game Over";
String scoreS = "Final Score : " + score; //Displaying score
Font small = new Font("Helvetica", Font.BOLD, 14);
Font smallnb = new Font("Helvetica", Font.PLAIN, 12);
FontMetrics metric = getFontMetrics(small); //FontMetrics is easier to use to position text
g.setColor(Color.white);
g.setFont(small);
//Centers and Draws the Messages
g.drawString(msg, (WIDTH - metric.stringWidth(msg)) / 2, HEIGHT / 2);
g.drawString(scoreS, (WIDTH - metric.stringWidth(scoreS)) / 2, ((HEIGHT / 2) - 30));
//Drawing High Scores
metric = getFontMetrics(smallnb);
g.setFont(smallnb);
g.setColor(Color.red);
for(String line : str.split("\n")){
g.drawString(line, (WIDTH - metric.stringWidth(str)) - 110, z +=
g.getFontMetrics().getHeight());
}

ArrayList<JButton> adding Action listeners with ArrayList

Been stuck on this for awhile now and thought after a bit of searching and not finding what I'm looking for would ask to see if anyone has a solution to my problem. Currently for a small collage project I'm working on I need to have a panel which contains 100 buttons but each button must have an action listener. This action listener when selected must report its number in the grid and change the text of the button.
for (int i = 0; i < 100; ++i) //Sets buttons created
{
ArrayList<JButton> testButton = new ArrayList<JButton>(); //Button Text
PlayerGrid1.add( new JButton(" ? ") );
}
The Code is how I add the buttons to the ArrayList but the issue I'm having is when I try to add an action listener it throws errors about abstract buttons and other issues.
JPanel PlayerGrid1 = new JPanel();
PlayerGrid1.setBackground(Color.WHITE);
PlayerGrid1.setBounds(0, 0, 375, 400);
frmBattleships.getContentPane().add(PlayerGrid1);
PlayerGrid1.setLayout(new GridLayout(10, 10, 0, 0));
This is the grid in which I store the Buttons.
If anyone one knows how I can add a listener to the ArrayList or has a link to a post of someone using the same method as me it would be appreciated. Also just to let anyone know if this is not set out correctly or wrong please don't flame I don't normally ask many Stack overflow Questions. Thanks.
Define a map instead of list before for loop like:
Map<String,JButton> buttonMap = new HashMap<String,JButton>();
After that you should set unique action command for each button in for loop 'i' can be used for that purpose.
for (int i = 0; i < 100; ++i) //Sets buttons created
{
JButton button = new JButton();
button.setActionCommand(String.valueOf(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonMap.get(e.getActionCommand()).setText("Whatever you want!");
}
});
buttonMap.put(String.valueOf(i), button);
PlayerGrid1.add(button);
}
try this `
JFrame frmBattleships = new JFrame();
JPanel PlayerGrid1 = new JPanel();
PlayerGrid1.setBackground(Color.WHITE);
PlayerGrid1.setBounds(0, 0, 375, 400);
frmBattleships.getContentPane().add(PlayerGrid1);
PlayerGrid1.setLayout(new GridLayout(10, 10, 0, 0));
for (int i = 0; i < 100; ++i) // Sets buttons created
{
ArrayList<JButton> testButton = new ArrayList<JButton>(); // Button
JButton newButton = new JButton("" + i); // Text
newButton.setName("" + i);
newButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource()).getName());
}
});
PlayerGrid1.add(newButton);
}
frmBattleships.setVisible(true);
`

JComboBox Issue

I have an assignment in my CS12 class, which to create a program where can be combined JRadioButon/JCheckBox/JComboBox all together.
As of now I am very confused with JComboBox, I don't understand what exactly am i missing in an ActionListener part.
First I can't choose any option from the third column( Colour & Interior ), it is simply doesn't shows up on the label created in the same column.
Second, I can't see the values of the JCheckBoxes created in the second column, before I chose the province from the fourth column.
Will accept any advise, thank you.
// please excuse for my english, I am not a native speaker.
import javax.swing.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
public class VolvoStore extends JFrame implements ItemListener {
private JButton btnCheckout;
private JButton btnClear;
private JButton btnExit;
private JButton btnAbout;
private JLabel txt1 = new JLabel();// total
private JLabel txt2 = new JLabel();
private JLabel txt3 = new JLabel();
private JLabel txt4 = new JLabel();
private JLabel txt5 = new JLabel();
private JLabel txt6 = new JLabel();
private JLabel txt7 = new JLabel();
private JLabel txt8 = new JLabel();
Double m;
Double k;
JCheckBox chk = new JCheckBox("Climate Package [Add $1,350.00]");
JCheckBox chk1 = new JCheckBox("Technology Package [Add $1,500.00]");
JCheckBox chk2 = new JCheckBox("Inscription Package [Add $2,600.00]");
JCheckBox chk3 = new JCheckBox(
"19\" BOR Diamond Cut Alloy Wheels [Add $1,250.00]");
JCheckBox chk4 = new JCheckBox(
"Blind Spot Information System [Add $800.00]");
JCheckBox chk5 = new JCheckBox(
"Active Dual Xenon Headlights with Washers [Add $1,000.00]");
JCheckBox chk6 = new JCheckBox("Front and Rear Park Assist [Add $600.00]");
JCheckBox chk7 = new JCheckBox(
"Apple CarPlay System + Bose Sound System [Add $2400.00]");
private JRadioButton rb1, rb2, rb3, rb4;
private JLabel label = new JLabel();
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JLabel label3 = new JLabel();
private JLabel label4 = new JLabel();
private JLabel label5 = new JLabel();
private JLabel label6 = new JLabel();
private JLabel label7 = new JLabel();
private JLabel label11 = new JLabel();
private JLabel label12 = new JLabel();
private JLabel label13 = new JLabel();
private JLabel label14 = new JLabel();
private JLabel label15 = new JLabel();
private JLabel label16 = new JLabel();
private JLabel label17 = new JLabel();
private JLabel label18 = new JLabel();
private JLabel label19 = new JLabel();
private JLabel label20 = new JLabel();
private JLabel label21 = new JLabel();
private JLabel label111 = new JLabel();
private JLabel label112 = new JLabel();
private JLabel label113 = new JLabel();
private JLabel label114 = new JLabel();
private JLabel tx = new JLabel();
private JLabel tx2 = new JLabel();
private JLabel tx3 = new JLabel();
private JLabel tx4 = new JLabel();
private JLabel tx4a = new JLabel();
private JLabel tx5 = new JLabel();
private JLabel tx6 = new JLabel();
private JLabel tx7 = new JLabel();
private JLabel tx71 = new JLabel();
private JLabel tx72 = new JLabel();
private JLabel tx73 = new JLabel();
double total;
double total1;
JComboBox<String> cboAColor;
JComboBox<String> cboBColor;
JComboBox<String> cboCColor;
JComboBox<String> cboProvinces;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int d1 = 0;
int f = 0;
int g = 0;
int h = 0;
JPanel panel = new JPanel();
private JTextField text1 = new JTextField("", 16);// total bill
public static void main(String[] args) {
new VolvoStore();
}
public VolvoStore() {
// OK Button
btnCheckout = new JButton("Checkout");
btnCheckout.setToolTipText("Checkout");
btnCheckout.setBounds(1315, 150, 120, 40);
btnCheckout.setMnemonic(KeyEvent.VK_C);
panel.setLayout(null);
btnCheckout.setBorderPainted(false);
panel.add(btnCheckout);
// Clear
btnClear = new JButton("Clear");
btnClear.setToolTipText("Clear");
btnClear.setBounds(1315, 200, 120, 40);
btnClear.setMnemonic(KeyEvent.VK_C);
btnClear.setBorderPainted(false);
panel.add(btnClear);
// EXIT
btnExit = new JButton("Exit");
btnExit.setToolTipText("Exit");
btnExit.setBounds(1315, 250, 120, 40);
btnExit.setMnemonic(KeyEvent.VK_C);
panel.setLayout(null);
btnExit.setBorderPainted(false);
panel.add(btnExit);
// ABOUT
btnAbout = new JButton("About");
btnAbout.setToolTipText("About");
btnAbout.setBounds(1315, 300, 120, 40);
btnAbout.setMnemonic(KeyEvent.VK_C);
panel.setLayout(null);
btnAbout.setBorderPainted(false);
panel.add(btnAbout);
//user input
panel.add(text1);
text1.setBounds(1275, 775, 200, 35);
text1.setHorizontalAlignment(JLabel.CENTER);
//total MSRP
txt1.setText("0.0");
txt1.setBounds(1300, 575, 140, 40);
panel.add(txt1);
txt1.setHorizontalAlignment(JLabel.CENTER);
// 1st column
txt2.setText("0.0");
txt2.setBounds(155, 875, 140, 40);
panel.add(txt2);
txt2.setHorizontalAlignment(JLabel.CENTER);
//Second Column
txt3.setText("0.0");
txt3.setBounds(575, 875, 140, 40);
panel.add(txt3);
txt3.setHorizontalAlignment(JLabel.CENTER);
// total Selling Price
txt4.setText("0.0");
txt4.setBounds(1300, 875, 140, 40);
panel.add(txt4);
txt4.setHorizontalAlignment(JLabel.CENTER);
//Freight & Dealer Prep
txt5.setText("10.0");
txt5.setBounds(1300, 675, 140, 40);
panel.add(txt5);
txt5.setHorizontalAlignment(JLabel.CENTER);
//third column
txt6.setText("0.0");
txt6.setBounds(965, 875, 140, 40);
panel.add(txt6);
txt6.setHorizontalAlignment(JLabel.CENTER);
//check buttons in a second column + radio button and images from the first column
panel.add(chk);
panel.add(chk1);
panel.add(chk2);
panel.add(chk3);
panel.add(chk4);
panel.add(chk5);
panel.add(chk6);
panel.add(chk7);
chk.setBounds(450, 50, 540, 40);
chk1.setBounds(450, 150, 540, 40);
chk2.setBounds(450, 250, 540, 40);
chk3.setBounds(450, 350, 540, 40);
chk4.setBounds(450, 450, 540, 40);
chk5.setBounds(450, 550, 540, 40);
chk6.setBounds(450, 650, 540, 40);
chk7.setBounds(450, 750, 540, 40);
panel.setLayout(null);
btnCheckout.addActionListener(new ButtonListener());
btnClear.addActionListener(new ButtonListener());
btnAbout.addActionListener(new ButtonListener());
btnExit.addActionListener(new ButtonListener());
chk.addItemListener(this);
chk1.addItemListener(this);
chk2.addItemListener(this);
chk3.addItemListener(this);
chk4.addItemListener(this);
chk5.addItemListener(this);
chk6.addItemListener(this);
chk7.addItemListener(this);
// images
ImageIcon imgThisImg = new ImageIcon("S80.png");
label1.setIcon(imgThisImg);
label1.setBounds(25, 450, 550, 590);
panel.add(label1);
label1.setOpaque(false);
ImageIcon imgThisImg1 = new ImageIcon("XC90.png");
label2.setIcon(imgThisImg1);
label2.setBounds(25, -50, 680, 390);
panel.add(label2);
label2.setOpaque(false);
ImageIcon imgThisImg2 = new ImageIcon("XC70.png");
label3.setIcon(imgThisImg2);
label3.setBounds(25, 150, 680, 390);
panel.add(label3);
label3.setOpaque(false);
ImageIcon imgThisImg3 = new ImageIcon("XC60.png");
label4.setIcon(imgThisImg3);
label4.setBounds(25, 350, 680, 390);
panel.add(label4);
label4.setOpaque(false);
ImageIcon imgThisImg4 = new ImageIcon("Volvo.jpeg");
label5.setIcon(imgThisImg4);
label5.setBounds(-10, -170, 680, 390);
panel.add(label5);
label5.setOpaque(false);
ImageIcon imgThisImg5 = new ImageIcon("012.png");
label6.setIcon(imgThisImg5);
label6.setBounds(1275, 290, 680, 390);
panel.add(label6);
label6.setOpaque(false);
ImageIcon imgThisImg6 = new ImageIcon("sun.png");
label7.setIcon(imgThisImg6);
label7.setBounds(1275, 220, 680, 390);
panel.add(label7);
label7.setOpaque(false);
// Create radio buttons
rb1 = new JRadioButton("Volvo XC90");
rb2 = new JRadioButton("Volvo XC70");
rb3 = new JRadioButton("Volvo XC60");
rb4 = new JRadioButton("Vovlo S80");
// Create button group for soup options
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
group.add(rb4);
// Create soup panel
rb1.setBounds(0, 200, 120, 40);
rb2.setBounds(0, 400, 120, 40);
rb3.setBounds(0, 600, 120, 40);
rb4.setBounds(0, 800, 120, 40);
//panel.add(label);
//label.setBounds(200, -150, 550, 590);
rb1.addItemListener(this);
rb2.addItemListener(this);
rb3.addItemListener(this);
rb4.addItemListener(this);
// text at the top and side
Font a = new Font("Greek", Font.PLAIN, 20);
tx.setText("Step 1: Model");
tx.setBounds(125, 0, 300, 40);
panel.add(tx);
tx2.setText("Step 2: Packages & Options ");
tx2.setBounds(520, 0, 300, 40);
panel.add(tx2);
tx3.setText("Step 3: Paint & Interior");
tx3.setBounds(925, 0, 300, 40);
panel.add(tx3);
tx4.setText("Step 4: Final Payment");
tx4.setBounds(1275, 0, 300, 40);
panel.add(tx4);
tx4a.setText("Total MSRP");
tx4a.setBounds(1275, 525, 300, 40);
panel.add(tx4a);
tx5.setText("Freight & Dealer Preparation");
tx5.setBounds(1275, 625, 300, 40);
panel.add(tx5);
tx6.setText("Trade-in and Down Payment ");
tx6.setBounds(1275, 725, 300, 40);
panel.add(tx6);
tx7.setText("Total Selling Price");
tx7.setBounds(1275, 825, 300, 40);
panel.add(tx7);
tx71.setText("Select Upholstery");
tx71.setBounds(985, 350, 300, 40);
panel.add(tx71);
tx72.setText("Select Trim");
tx72.setBounds(1000, 550, 300, 40);
panel.add(tx72);
tx73.setText("Select Color");
tx73.setBounds(1000, 150, 300, 40);
panel.add(tx73);
tx.setFont(a);
tx2.setFont(a);
tx3.setFont(a);
tx4.setFont(a);
//
// Create main panel
panel.setLayout(null);
panel.add(rb1);
panel.add(rb2);
panel.add(rb3);
panel.add(rb4);
//Jcombobox at third and fourth columns
String[] aa = { "Black Sapphire" ,"Electric Silver", "Passion Red [add $200.00]",
"Crystal White Pearl [add $200.00]" };
cboAColor = new JComboBox<String>(aa);
panel.add(cboAColor);
cboAColor.setBounds(940, 100, 200, 200);
String[] bb = { "Black/Black ARTICO Leather, without additional charge",
"Alpaca Grey/Alpaca Grey ARTICO Leather, without additional charge",
"Almond Beige/Cashmere Beige ARTICO Leather [add $350.00]" };
cboBColor = new JComboBox<String>(bb);
panel.add(cboBColor);
cboBColor.setBounds(940, 300, 200, 200);
String[] cc = { "Burl Walnut Wood, without additional charge", "Dark Ash Wood, without additional charge", "Aluminum[add $200]" };
cboCColor = new JComboBox<String>(cc);
panel.add(cboCColor);
cboCColor.setBounds(940, 500, 200, 200);
String[] dd = { "Select Province", "Ontario", "Quebeck", "Nova Scotia",
"New Brunswick", "Manitoba", "British Colombia",
"Prince Edward Island", "Saskatchewan", "Alberta",
"Newfoundland and Labrador" };
cboProvinces = new JComboBox<String>(dd);
panel.add(cboProvinces);
cboProvinces.setBounds(1275, 000, 200, 200);
cboAColor.addItemListener(this);
cboBColor.addItemListener(this);
cboCColor.addItemListener(this);
cboProvinces.addItemListener(this);
// borders ...
panel.add(label11);
label11.setBackground(Color.white);// set background color
label11.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label11.setBounds(125, 875, 200, 35);// bounds and location
label11.setOpaque(false);
// create black border for a Clear Button
panel.add(label12);
label12.setOpaque(false);
label12.setBackground(Color.white);// set background color
label12.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label12.setBounds(550, 875, 200, 35);// bounds and location
// create black border for a Clear Button
panel.add(label13);
label13.setOpaque(false);
label13.setBackground(Color.white);// set background color
label13.setBorder(BorderFactory.createLineBorder(Color.black));// set
// color
label13.setBounds(940, 875, 200, 35);// bounds and location
panel.add(label14);
label14.setOpaque(false);
label14.setBackground(Color.white);// set background color
label14.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label14.setBounds(1275, 875, 200, 35);// bounds and location
panel.add(label15);
label15.setOpaque(false);
label15.setBackground(Color.white);// set background color
label15.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label15.setBounds(1275, 775, 200, 35);// bounds and location
panel.add(label16);
label16.setOpaque(false);
label16.setBackground(Color.white);// set background color
label16.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label16.setBounds(1275, 675, 200, 35);// bounds and location
panel.add(label17);
label17.setOpaque(false);
label17.setBackground(Color.white);// set background color
label17.setBorder(BorderFactory.createLineBorder(Color.black));// set //
// color
label17.setBounds(1275, 575, 200, 35);// bounds and location
panel.add(label18);
label18.setOpaque(false);
label18.setBackground(Color.white);// set background color
label18.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));// set
// //
// color
label18.setBounds(0, -100, 445, 1100);// bounds and location
panel.add(label19);
label19.setOpaque(false);
label19.setBackground(Color.white);// set background color
label19.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));// set
// //
// color
label19.setBounds(445, -100, 415, 1100);// bounds and location
panel.add(label20);
label20.setOpaque(false);
label20.setBackground(Color.white);// set background color
label20.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));// set
// //
// color
label20.setBounds(860, -100, 360, 1100);// bounds and location
panel.add(label21);
label21.setOpaque(false);
label21.setBackground(Color.white);// set background color
label21.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));// set
// //
// color
label21.setBounds(1220, -100, 360, 1100);// bounds and location
panel.add(label111);
label111.setBackground(Color.white);// set background color
label111.setBorder(BorderFactory.createLineBorder(Color.black));// set
// //
// color
label111.setBounds(1275, 150, 200, 35);// bounds and location
label111.setOpaque(false);
panel.add(label112);
label112.setBackground(Color.white);// set background color
label112.setBorder(BorderFactory.createLineBorder(Color.black));// set
// //
// color
label112.setBounds(1275, 200, 200, 35);// bounds and location
label112.setOpaque(false);
panel.add(label113);
label113.setBackground(Color.white);// set background color
label113.setBorder(BorderFactory.createLineBorder(Color.black));// set
// //
// color
label113.setBounds(1275, 250, 200, 35);// bounds and location
label113.setOpaque(false);
panel.add(label114);
label114.setBackground(Color.white);// set background color
label114.setBorder(BorderFactory.createLineBorder(Color.black));// set
// //
// color
label114.setBounds(1275, 300, 200, 35);// bounds and location
label114.setOpaque(false);
//
// frame
setContentPane(panel);
setSize(1520, 950);
setTitle("Volvo Store");
getContentPane().setBackground(new Color(255, 255, 255));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
validate();
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCheckout) {
} else if (e.getSource() == btnClear) {
txt1.setText("0.0");
txt2.setText("0.0");
txt3.setText("0.0");
txt4.setText("0.0");
txt5.setText("0.0");
txt6.setText("0.0");
txt7.setText("0.0");
chk7.setSelected(false);
chk6.setSelected(false);
chk5.setSelected(false);
chk4.setSelected(false);
chk3.setSelected(false);
chk2.setSelected(false);
chk1.setSelected(false);
chk.setSelected(false);
} else if (e.getSource() == btnAbout) {
JOptionPane.showMessageDialog(null,
"Made by Evgeny Shumilov - 2014", "About",
JOptionPane.INFORMATION_MESSAGE);
} else if (e.getSource() == btnExit) {
}
}
}
public void itemStateChanged(ItemEvent e) {
double a = 0;
double b = 0;
double c = 0;
double d = 0;
double d1 = 0;
double f = 0;
double g = 0;
double h = 0;
double a1 = 0;
double a2 = 0;
double a3 = 0;
double a4 = 0;
double b1 = 0;
double b2 = 0;
double b3 = 0;
double c1 = 0;
double c2 = 0;
double c3 = 0;
//radiobutton
if (e.getSource() == rb1) {
txt1.setText("50800.0");
txt2.setText("50800.0");
panel.add(txt1);
panel.add(txt2);
m = Double.parseDouble(txt1.getText());
txt1.setHorizontalAlignment(JLabel.CENTER);
}
else if (rb2.isSelected()) {
txt1.setText("42100.0");
txt2.setText("42100.0");
panel.add(txt1);
panel.add(txt2);
m = Double.parseDouble(txt1.getText());
txt1.setHorizontalAlignment(JLabel.CENTER);
} else if (rb3.isSelected()) {
txt1.setText("40950.0");
txt2.setText("40950.0");
panel.add(txt1);
panel.add(txt2);
m = Double.parseDouble(txt1.getText());
txt1.setHorizontalAlignment(JLabel.CENTER);
} else if (rb4.isSelected()) {
txt1.setText("49000.0");
txt2.setText("49000.0");
panel.add(txt1);
panel.add(txt2);
m = Double.parseDouble(txt1.getText());
txt1.setHorizontalAlignment(JLabel.CENTER);
}
if (chk.isSelected()) {
a = 1350;
}
if (chk1.isSelected()) {
b = 1500;
}
if (chk2.isSelected()) {
c = 2600;
}
if (chk3.isSelected()) {
d = 1250;
}
if (chk4.isSelected()) {
d1 = 800;
}
if (chk5.isSelected()) {
f = 1000;
}
if (chk6.isSelected()) {
g = 600;
}
if (chk7.isSelected()) {
h = 2400;
}
//p
if (e.getSource() == cboProvinces) {
String one = (String) cboProvinces.getSelectedItem();
if (one.equals("Select Province")) {
txt5.setText("0.0");
panel.add(txt5);
} else if (one.equals("Ontario")) {
txt5.setText("1934.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Quebeck")) {
txt5.setText("2200.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Nova Scotia")) {
txt5.setText("1800.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("New Brunswick")) {
txt5.setText("1999.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Manitoba")) {
txt5.setText("2100.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("British Colombia")) {
txt5.setText("1300.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Prince Edward Island")) {
txt5.setText("2335.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Saskatchewan")) {
txt5.setText("2120.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Alberta")) {
txt5.setText("1670.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
} else if (one.equals("Newfoundland and Labrador")) {
txt5.setText("3200.0");
panel.add(txt5);
k = Double.parseDouble(txt5.getText());
}
}
//color
if (e.getSource() == cboAColor) {
String one = (String) cboAColor.getSelectedItem();
if (one.equals("Passion Red")) {
a1 = 200;
txt6.setText("200.0");
panel.add(txt6);
} else if (one.equals("Black Sapphire")) {
a2 = 0;
txt6.setText("0.0");
panel.add(txt6);
} else if (one.equals("Crystal White Pearl")) {
a3 = 200.0;
txt6.setText("200.0");
panel.add(txt6);
} else if (one.equals("Electric Silver")) {
a4 = 0;
txt6.setText("0.0");
panel.add(txt6);
}
}
//leather
if (e.getSource() == cboBColor) {
String two = (String) cboBColor.getSelectedItem();
if (two.equals("Black/Black ARTICO Leather")) {
b1 = 0;
txt6.setText("0.0");
panel.add(txt6);
} else if (two.equals("Alpaca Grey/Alpaca Grey ARTICO Leather")) {
b2 = 0;
txt6.setText("0.0");
panel.add(txt6);
} else if (two.equals("Almond Beige/Cashmere Beige ARTICO Leather")) {
b3 = 350;
txt6.setText("350.0");
panel.add(txt6);
}
}
//panel
if (e.getSource() == cboCColor) {
String one1 = (String) cboCColor.getSelectedItem();
if (one1.equals("Aluminum")) {
c1 = 300;
txt6.setText("300.0");
panel.add(txt6);
} else if (one1.equals("Burl Walnut Wood")) {
c2 = 0;
txt6.setText("0.0");
panel.add(txt6);
} else if (one1.equals("Dark Ash Wood")) {
c3 = 0;
txt6.setText("0.0");
panel.add(txt6);
}
}
//Double b1ll = Double.parseDouble(text1.getText());
Double total = m + a + b + c + d + d1 + f + g + h + a1 + a2 + a3 +a4 + b1 + b2 + b3+ c1 + c2 +c3;
Double total1 = a + b + c + d + d1 + f + g + h;
Double totala = a1 + a2 + a3 +a4 + b1 + b2 + b3+ c1 + c2 +c3;
Double FinalC= total + k;// - b1ll ;
String total2 = Double.toString(total);
String total21 = Double.toString(total1);
String totalm = Double.toString(totala);
String Final = Double.toString(FinalC);
txt1.setText(total2);
txt3.setText(total21);
txt6.setText(totalm);
txt4.setText(Final);
validate();
}
}
This....
Is why you should use appropriate layout managers...
As to your problems...
You keep getting a NullPointerException because (as far as I've been able to test it), m and k are null...
You're using a single instance of an ItemListener listener for all your controls (that accept them), this is a really bad idea as it makes it difficult to determine 1- the current state and 2- what caused the event...
Personally, I prefer to use separate listeners where I can, so I can isolate exactly what is going on...
If you change m and k to be double instead of Double, this will solve the immediate issue
The next issue you will have is with the comparison of the values from the combo box...
In you event handler, you are using if (one.equals("Passion Red")) { to check the color option, but the actual entry is Passion Red [add $200.00], meaning that it will never match...
I presume you have a number of these types of issues, so you're going to have to dig through your code to find them all...

Reinitializing my JPanel after pressing a button

i have a Jframe which has some panels as instance variables and one of the panels is a grid board (i am implementing Lines of action game). After my game ends I have a button "Play again" which i want to reinitialize my board panel. I tried a lot of things like removing my panel from the content pane and re-initializing it, but nothing worked so far. Here are some of the things i tried (i didn't try them all at once )
public class Frame extends JFrame implements MouseListener{
JLabel l = new JLabel();
Panel1 Boards;
Panel2 newGame;
Panel3 winner;
Point lastCheckerSelected;
Board game = new Board();
public Frame() {
setResizable(false);
setTitle("Lines Of Action");
setBounds(290, 350, 1000, 700);
setLayout(null);
winner=new Panel3();
winner.playAgain.addMouseListener(this);
getContentPane().add(winner);
Boards= new Panel1();
getContentPane().add(Boards);
setDefaultCloseOperation(EXIT_ON_CLOSE);
l.setIcon(new ImageIcon(
"E:\\background0213.jpg"));
l.setBounds(0 ,0 , 1000 , 700);
getContentPane().add(l);
validate();
newGame=new Panel2();
newGame.b.addMouseListener(this);
getContentPane().add(newGame);
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
Boards.x[i][j].addMouseListener(this);
Boards.y[i][j].addMouseListener(this);
}
}
}
public void mouseClicked(MouseEvent e) {
if(e.getSource().equals(newGame.b)) {
Boards.setVisible(true);
newGame.setVisible(false);
game=new Board();
}
if(this.game.getWinner()==1) {
winner.setVisible(true);
winner.whiteWins.setVisible(true);
}
if(this.game.getWinner()==2) {
winner.setVisible(true);
winner.greywins.setVisible(true);
}
if(e.getSource().equals(winner.playAgain)) {
//this.getContentPane().remove(Boards);
// this.game= new Board();
// Boards = new Panel1();
// this.getContentPane().add(Boards);
//Boards.setVisible(true);
// validate();
// Boards.repaint();
}
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
}
I still cant make my new panel appear ( removing the Boards panel from the content pane makes it disappear which is good but the new one does not appear)
here is my panel =1 that contains the board
public class Panel1 extends JPanel {
JButton[][] x = new JButton[8][8];
JButton[][] y=new JButton[8][8];
Graphics g;
public Panel1() {
setBounds(0, 30 ,400 ,400);
setLayout(new GridLayout(8, 8));
setOpaque(false);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
x[i][j] = new JButton();
x[i][j].setSize(50, 50);
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) {
x[i][j].setBackground(Color.DARK_GRAY.darker());
// x[i][j].setBackground(new Color(111,89,81,150));
}
else {
// Color.OPAQUE = 2;
x[i][j].setBackground(Color.red.darker().darker());
// x[i][j].setBackground(new Color(223,37,32,150));
}
x[i][j].setEnabled(false);
add(x[i][j]);
}
}
for(int i = 0; i < 8 ;i++){
for(int j=0;j < 8;j++){
y[i][j]=new JButton();
x[i][j].add(y[i][j]);
// y[i][j].setSize(100,100);
// y[i][j].setEnabled(false);
// y[i][j].setOpaque(false);
// y[i][j].setContentAreaFilled(false);
// y[i][j].setBorderPainted(false);
y[i][j].setVisible(false);
}
}
for(int i=1;i<7;i++){
// y[0][i].setOpaque(true);
y[0][i].setBackground(Color.white);
y[0][i].setEnabled(true);
y[0][i].setVisible(true);
// y[7][i].setOpaque(true);
y[7][i].setBackground(Color.white);
y[7][i].setEnabled(true);
y[7][i].setVisible(true);
}
for(int i=1;i<7;i++){
// y[i][0].setOpaque(true);
y[i][0].setEnabled(true);
y[i][0].setBackground(new Color(102,125,153));
y[i][0].setVisible(true);
// y[i][7].setOpaque(true);
y[i][7].setEnabled(true);
y[i][7].setBackground(new Color(102,125,153));
y[i][7].setVisible(true);
}
// addMouseListener(this);
setVisible(false);
}
}
You could also try this:
if(e.getSource().equals(winner.playAgain))
{
Boards.removeAll();
revalidate();
repaint();
}
I don't think you need to create a new Panel1 instance.
i have a Jframe which has some panels as instance variables and one of
the panels is a grid board (i am implementing Lines of action game).
After my game ends I have a button "Play again" which i want to
reinitialize my board panel. I tried a lot of things like removing my
panel from the content pane and re-initializing it, but nothing worked
so far.
I think that CardLayout is best of choices
Try these four together. Need to see more of your code to make sure this work.
if(e.getSource().equals(winner.playAgain)) {
this.getContentPane().remove(Boards);
Boards = new Panel1();
this.getContentPane().add(Boards);
this.invalidate();
this.validate();
this.repaint();
}
After the components are made visible in the screen, if you remove and add components, then you have to call Component.repaint() or Component.validate() to call the repainting again. Do this inside your actionPerformed() of your playAgainButton()

Categories