JComboBox Issue - java

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...

Related

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());
}

How to visualize sorting algorithms? [duplicate]

This question already has an answer here:
Java swing repainting while computing: animating sorting algorithm
(1 answer)
Closed 4 years ago.
I want to sort these coloured bars using different algorithms.
.
I have created a JFrame and added eight buttons and one JPanel. In the panel I have created a bar chart of an array. I want to sort this bar chart visually by using different sorting algorithms like bubble sort, selection sort, merge sort etc by clicking on buttons and showing each algorithm and step. But I'm finding trouble in visualizing these algorithms.
Here is my code:
public class VisuofSortTech {
//Declarations....
private final JLabel lbl = new JLabel();
private JTextField jtf = new JTextField(10);
private JPanel pnl = new JPanel();
private final JButton bbl= new JButton("Bubble Sort");
private final JButton ins= new JButton("Insertion Sort");
private final JButton mrg= new JButton("Merge Sort");
private final JButton slc= new JButton("Selection Sort");
private final JButton qck= new JButton("Quick Sort");
private final JButton rdx= new JButton("Radix Sort");
private final JButton heap= new JButton("Heap Sort");
private final JButton stp= new JButton("Stupid Sort");
private final JButton go = new JButton("Create");
String[] parts;
int[] arr1;
BarChart chart = new BarChart();
Random rand = new Random();
//Main method....
public static void main(String[] args) {
VisuofSortTech visuOfSortTech = new VisuofSortTech();
System.out.println("Visual :" + visuOfSortTech);
}
// Bars
public class BarChart extends Canvas
{
private final Map<Color, Integer> bars =
new LinkedHashMap<>();
public void addBar(Color color, int value)
{
bars.put(color, value);
repaint();
}
//
#Override
public void paint(Graphics g)
{
// determine longest bar
int max = Integer.MIN_VALUE;
for (int value : bars.values())
{
max = Math.max(max, value);
}
// paint bars
int width = (getWidth() / bars.size()) - 2;
int x = 1;
for (Color color : bars.keySet())
{
int value = bars.get(color);
int height = (int) ((getHeight()-5) * ((double)value / max));
g.setColor(color);
g.fill3DRect(x, getHeight() - height, width, height , true);
g.setColor(Color.white);
g.drawRect(x, getHeight() - height, width, height);
x += (width + 2);
}
}
}
// Constructor........
public VisuofSortTech(){
JFrame frame = new JFrame("DSA Project");
frame.getContentPane().setLayout(null);
// Label
lbl.setText("Visualization of Sorting Algorithms");
lbl.setFont(new Font("SansSerif", 3, 36));
lbl.setForeground(Color.red);
lbl.setBackground(new Color(150,235,210,100));
lbl.setFocusable(true);
lbl.setBounds(10,10, 620, 60);
lbl.setMinimumSize(new Dimension(200,200));
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.white, 3, true));
frame.add(lbl);
// Buttons
bbl.setBounds(50, 100, 115, 35);
bbl.setForeground(Color.magenta);
bbl.setBackground(Color.white);
bbl.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
bbl.setBorderPainted(true);
frame.add(bbl);
ins.setBounds(50, 150, 115, 35);
ins.setForeground(Color.magenta);
ins.setBackground(Color.white);
ins.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
ins.setBorderPainted(true);
frame.add(ins);
mrg.setBounds(50, 200, 115, 35);
mrg.setForeground(Color.magenta);
mrg.setBackground(Color.white);
mrg.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
mrg.setBorderPainted(true);
frame.add(mrg);
qck.setBounds(50, 250, 115, 35);
qck.setForeground(Color.magenta);
qck.setBackground(Color.white);
qck.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
qck.setBorderPainted(true);
frame.add(qck);
slc.setBounds(50, 300, 115, 35);
slc.setForeground(Color.magenta);
slc.setBackground(Color.white);
slc.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
slc.setBorderPainted(true);
frame.add(slc);
rdx.setBounds(50, 350, 115, 35);
rdx.setForeground(Color.magenta);
rdx.setBackground(Color.white);
rdx.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
rdx.setBorderPainted(true);
frame.add(rdx);
heap.setBounds(50, 400, 115, 35);
heap.setForeground(Color.magenta);
heap.setBackground(Color.white);
heap.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
heap.setBorderPainted(true);
frame.add(heap);
stp.setBounds(50, 450, 115, 35);
stp.setForeground(Color.magenta);
stp.setBackground(Color.white);
stp.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
stp.setBorderPainted(true);
frame.add(stp);
go.setBounds(755, 600, 100, 30);
go.setForeground(Color.magenta);
go.setBackground(Color.white);
go.setBorder(BorderFactory.createDashedBorder(Color.GREEN, 5, 2, 0, true));
go.setBorderPainted(true);
frame.add(go);
// Textfield
jtf.setBounds(550, 600, 200, 30);
jtf.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2, true));
frame.add(jtf);
// Panel
pnl.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.white, 4, true), "Sorting Pane"));
pnl.setBounds(342, 100, 682, 384);
pnl.setLayout(new BorderLayout());
pnl.setBackground(new Color(255,255,255,150));
frame.add(pnl);
// Color arrays
int l= 20;
int[] clr1= new int[l];
int[] clr2= new int[l];
int[] clr3= new int[l];
// red color
for(int i=0; i < l ;i++){
int r= rand.nextInt(255);
clr1[i]= r;
}
// green color
for(int i=0; i < l ;i++){
int g= rand.nextInt(255);
clr2[i]= g;
}
// blue color
for(int i=0; i < l ;i++){
int b= rand.nextInt(255);
clr3[i]= b;
}
// Array
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt){
pnl.setVisible(false);
String str = jtf.getText();
parts = str.split(",");
arr1 =new int[parts.length];
for(int i=0 ; i<parts.length; i++){
arr1[i]=Integer.parseInt(parts[i]);
}
for(int i=0; i <arr1.length; i++){
chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
}
pnl.add(chart);
pnl.setVisible(true);
}
});
// Bubble sort
bbl.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
pnl.remove(chart);
pnl.setVisible(false);
//Thread t = new Thread();
int loop=arr1.length-1;
for(int i=0; i<loop; i++){
for(int j=0; j<loop-i;j++)
{
boolean exp = arr1[j]>arr1[j+1];
if(exp)
{
int temp=arr1[j];
arr1[j]=arr1[j+1];
arr1[j+1]=temp;
System.out.print(exp + ",");
try{
Thread.sleep(250);
}
catch(Exception e){
System.out.println("Thread is not working " + e);
}
System.out.print(temp + ",");
}
}
}
for(int i=0; i <arr1.length; i++){
chart.addBar(new Color(clr1[i] , clr2[i] ,clr3[i]) ,arr1[i]);
}
pnl.add(chart);
pnl.setVisible(true);
}
});
// Frame
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(167,167,247));
frame.setPreferredSize(new Dimension(screensize.width,screensize.height));
frame.pack();
frame.setResizable(true);
frame.setVisible(true);
}
}
You cannot use Thread.sleep() in Swing’s Event Dispatching Thread. That doesn’t slow down the program to allow you to see what happens; rather it prevents the UI from responding to anything, including repaint requests, so nothing happens, and time is wasted for no benefit.
Use a Swing Timer or (better) a SwingWorker to perform the sorting, in steps, and publish() the interm partial sort results for display.

Object doesn't move when I press a JButton

I am a first year student to the university. About a month ago I received an assignment on Java which asked me to create a maze game with a ball and after that to program the ball to navigate through the maze. After I finished the whole GUI I started programming the ball but I came across a problem.
After my code was ready the ball needed to move properly but it only move left no matter which button I was pressing on. After I changed the rightX +=38 from rightY +=38 guessing that was the main issue that caused, I saw that the ball after this change wasn't moving at all.
I will provide my full code below (there are some minor error like buttons that doesn't exist because I didn't removed them yet). The code for the ball to move starts on public boolean moveLeft1() and goes all the way until the end.
public class GMazeBall extends JFrame implements ActionListener{
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11,
button12, buttonact, buttongame, button16, buttoncompass, button, buttonsand, button13, buttonLeft,buttonRight,
buttonUp, buttonDown;
private JPanel panel1, panel2, panel3;
private JTextField textoption, textsquare, textdirection, firsttext, secondtext, thirdtext;
private JLabel lsquare, ldirection, loption, l1, label2, ldigital, lspeed;
private ImageIcon gamereset, east, west, north, south, gameact, gamerun, white, sand;
private JSlider slidebar;
private JButton SandRoad;
private JButton SandStone;
private JButton GoldenBall;
ArrayList<JButton> myArray = new ArrayList<JButton>();
ImageIcon South = new ImageIcon("myimg/south.jpg");
ImageIcon West = new ImageIcon("myimg/west.jpg");
ImageIcon East = new ImageIcon("myimg/east.jpg");
ImageIcon North = new ImageIcon("myimg/noth.jpg");
public static void main(String[] args) {
GMazeBall frame = new GMazeBall();
frame.setSize(775, 665);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
panel1 = new JPanel();
panel1.setBounds(0, 0, 610, 500);
panel1.setBackground(Color.white);
panel1.setLayout(null);
window.add(panel1);
//public void createGoldenBall(int x, int y) {
Border border = BorderFactory.createEmptyBorder();
GoldenBall = new JButton(new ImageIcon("myimg/gold-ball.png"));
GoldenBall.setBounds(570, 0, 38, 38);
GoldenBall.setBorder(border);
GoldenBall.setOpaque(false);
GoldenBall.setContentAreaFilled(false);
GoldenBall.setBorderPainted(false);
panel1.add(GoldenBall);
createSandStone(0, 456);
Border newborder = BorderFactory.createEmptyBorder();
sand = new ImageIcon("myimg/sand.jpg");
for (int i = 0; i < 16; i++) {
buttonsand = new JButton(sand);
buttonsand.setBounds(i * 38, 0, 38, 38);
buttonsand.setBorder(newborder);
panel1.add(buttonsand);
myArray.add(buttonsand);
}
for (int i = 0; i < 16; i++) {
buttonsand = new JButton(sand);
buttonsand.setBounds(i * 38, 114, 38, 38);
buttonsand.setBorder(newborder);
panel1.add(buttonsand);
myArray.add(buttonsand);
}
for (int i = 0; i < 16; i++) {
buttonsand = new JButton(sand);
buttonsand.setBounds(i * 38, 228, 38, 38);
buttonsand.setBorder(newborder);
panel1.add(buttonsand);
myArray.add(buttonsand);
}
for (int i = 0; i < 16; i++) {
buttonsand = new JButton(sand);
buttonsand.setBounds(i * 38, 342, 38, 38);
buttonsand.setBorder(newborder);
panel1.add(buttonsand);
myArray.add(buttonsand);
}
for (int i = 0; i < 16; i++) {
buttonsand = new JButton(sand);
buttonsand.setBounds(i * 38, 456, 38, 38);
buttonsand.setBorder(newborder);
panel1.add(buttonsand);
myArray.add(buttonsand);
}
createSandRoad(38, 38);
createSandRoad(38, 76);
createSandRoad(190, 38);
createSandRoad(190, 76);
createSandRoad(342, 38);
createSandRoad(342, 76);
createSandRoad(76, 152);
createSandRoad(76, 190);
createSandRoad(228, 152);
createSandRoad(228, 190);
createSandRoad(418, 152);
createSandRoad(418, 190);
createSandRoad(38, 266);
createSandRoad(38, 304);
createSandRoad(190, 266);
createSandRoad(190, 304);
createSandRoad(456, 266);
createSandRoad(456, 304);
createSandRoad(76, 380);
createSandRoad(76, 418);
createSandRoad(228, 380);
createSandRoad(228, 418);
white = new ImageIcon("myimg/white32x32.jpg");
for (int y = 0; y < 13; y++) {
for (int x = 0; x < 16; x++) {
button = new JButton(white);
button.setBounds(x * 38, y * 38, 38, 38);
button.setContentAreaFilled(false);
button.setBorder(newborder);
panel1.add(button);
}
}
panel2 = new JPanel();
panel2.setBounds(605, 0, 170, 500);
panel2.setBackground(Color.LIGHT_GRAY);
panel2.setBorder(newborder);
window.add(panel2);
panel3 = new JPanel();
panel3.setBounds(0, 500, 775, 500);
panel3.setBackground(Color.LIGHT_GRAY);
panel3.setBorder(newborder);
window.add(panel3);
loption = new JLabel("option:");
panel2.add(loption);
textoption = new JTextField(5);
loption.setPreferredSize(new Dimension(70, 25));
textoption.setSize(20, 50);
panel2.add(textoption);
lsquare = new JLabel("square:");
panel2.add(lsquare);
textsquare = new JTextField(5);
lsquare.setPreferredSize(new Dimension(70, 25));
textsquare.setSize(20, 50);
panel2.add(textsquare);
ldirection = new JLabel("direction:");
panel2.add(ldirection);
textdirection = new JTextField(5);
ldirection.setPreferredSize(new Dimension(70, 25));
textdirection.setSize(20, 50);
panel2.add(textdirection);
ldigital = new JLabel(" DIGITAL TIMER");
ldigital.setPreferredSize(new Dimension(151, 25));
panel2.add(ldigital);
firsttext = new JTextField("00");
firsttext.setBackground(Color.black);
firsttext.setPreferredSize(new Dimension(35, 20));
panel2.add(firsttext);
l1 = new JLabel(":");
panel2.add(l1);
secondtext = new JTextField("00");
secondtext.setBackground(Color.black);
secondtext.setPreferredSize(new Dimension(35, 20));
panel2.add(secondtext);
label2 = new JLabel(":");
panel2.add(label2);
thirdtext = new JTextField("00");
thirdtext.setBackground(Color.black);
thirdtext.setPreferredSize(new Dimension(35, 20));
panel2.add(thirdtext);
button1 = new JButton("");
button1.setPreferredSize(new Dimension(41, 24));
panel2.add(button1);
buttonUp = new JButton("^");
buttonUp.setPreferredSize(new Dimension(41, 24));
buttonUp.addActionListener(this);
panel2.add(buttonUp);
button3 = new JButton("");
button3.setPreferredSize(new Dimension(41, 24));
panel2.add(button3);
buttonLeft = new JButton("<");
buttonLeft.setPreferredSize(new Dimension(41, 24));
buttonLeft.addActionListener(this);
panel2.add(buttonLeft);
button5 = new JButton("");
button5.setPreferredSize(new Dimension(41, 24));
panel2.add(button5);
buttonRight = new JButton(">");
buttonRight.setPreferredSize(new Dimension(41, 24));
buttonRight.addActionListener(this);
panel2.add(buttonRight);
button7 = new JButton("");
button7.setPreferredSize(new Dimension(41, 24));
panel2.add(button7);
buttonDown = new JButton("v");
buttonDown.setPreferredSize(new Dimension(41, 24));
buttonDown.addActionListener(this);
panel2.add(buttonDown);
button9 = new JButton("");
button9.setPreferredSize(new Dimension(41, 24));
panel2.add(button9);
button10 = new JButton("Opt.1");
panel2.add(button10);
button11 = new JButton("Opt.2");
panel2.add(button11);
button12 = new JButton("Opt.3");
panel2.add(button12);
button13 = new JButton(" Exit ");
panel2.add(button13);
east = new ImageIcon("myimg/north.jpg");
buttoncompass = new JButton(east);
panel2.add(buttoncompass);
buttoncompass.setPreferredSize(new Dimension(85, 80));
gameact = new ImageIcon("myimg/step.png");
buttonact = new JButton(gameact);
buttonact.setPreferredSize(new Dimension(70, 20));
panel3.add(buttonact);
gamerun = new ImageIcon("myimg/run.png");
buttongame = new JButton(gamerun);
buttongame.setPreferredSize(new Dimension(70, 20));
panel3.add(buttongame);
gamereset = new ImageIcon("myimg/reset.png");
button16 = new JButton(gamereset);
button16.setPreferredSize(new Dimension(70, 20));
panel3.add(button16);
lspeed = new JLabel(" speed: ");
panel3.add(lspeed);
slidebar = new JSlider(JSlider.HORIZONTAL, 200, 1000, 1000);
slidebar.setPreferredSize(new Dimension(182, 26));
panel3.add(slidebar);
}
public void createSandRoad(int x, int y) {
Border border = BorderFactory.createEmptyBorder();
SandRoad = new JButton(new ImageIcon("myimg/sand.jpg"));
SandRoad.setBounds(x, y, 38, 38);
SandRoad.setContentAreaFilled(false);
SandRoad.setBorder(border);
panel1.add(SandRoad);
}
public void createSandStone(int x, int y) {
Border border = BorderFactory.createEmptyBorder();
SandStone = new JButton(new ImageIcon("myimg/sandstone.jpg"));
SandStone.setBounds(x, y, 38, 38);
SandStone.setContentAreaFilled(false);
SandStone.setBorder(border);
panel1.add(SandStone);
}
public boolean moveLeft1() {
int leftX = GoldenBall.getX();
int leftY = GoldenBall.getY();
leftX -= 38;
for (int i = 0; i < myArray.size(); i++) {
if (myArray.get(i).getX() == leftX && myArray.get(i).getY() == leftY)
return true;
}
return false;
}
public boolean moveRight1() {
int rightX = GoldenBall.getX();
int rightY = GoldenBall.getY();
rightX += 38;
for (int i = 0; i < myArray.size(); i++) {
if (myArray.get(i).getX() == rightX && myArray.get(i).getY() == rightY)
return true;
}
return false;
}
public boolean moveUp1() {
int upX = GoldenBall.getX();
int upY = GoldenBall.getY();
upY -= 38;
for (int i = 0; i < myArray.size(); i++) {
if (myArray.get(i).getX() == upX && myArray.get(i).getY() == upY)
return true;
}
return false;
}
public boolean moveDown1() {
int downX = GoldenBall.getX();
int downY = GoldenBall.getY();
downY += 38;
for (int i = 0; i < myArray.size(); i++) {
if (myArray.get(i).getX() == downX && myArray.get(i).getY() == downY)
return true;
}
return false;
}
public void moveLeft2() {
int LeftX = GoldenBall.getX();
int LeftY = GoldenBall.getY();
LeftX -= 38;
GoldenBall.setBounds(LeftX, LeftY, 38, 38);
}
public void moveRight2() {
int RightX = GoldenBall.getX();
int RightY = GoldenBall.getY();
RightX += 38;
GoldenBall.setBounds(RightX, RightY, 38, 38);
}
public void moveUp2() {
int UpX = GoldenBall.getX();
int UpY = GoldenBall.getY();
UpY -= 38;
GoldenBall.setBounds(UpX, UpY, 38, 38);
}
public void moveDown2() {
int DownX = GoldenBall.getX();
int DownY = GoldenBall.getY();
DownY += 38;
GoldenBall.setBounds(DownX, DownY, 38, 38);
}
public void actionPerformed(ActionEvent movement) {
if (movement.getSource() == buttonLeft);
//buttoncompass.setIcon(west);
{
if (moveLeft1())
moveLeft2();
}
if (movement.getSource() == buttonRight);
//buttoncompass.setIcon(east);
{
if (moveRight1())
moveRight2();
}
if (movement.getSource() == buttonUp);
//buttoncompass.setIcon(north);
{
if (moveUp1())
moveUp2();
}
if (movement.getSource() == buttonDown);
//buttoncompass.setIcon(south);
{
if (moveDown1())
moveDown2();
}
}
}
First, follow the advices in the comments in the main question. Your code is a chaos (and i am not reviewing, i am just saying that no matter how much help you ask, few people will do it).
If you want to avoid the "only moving left" problem, here is how i would do it:
I would remove "implements ActionListener" from the class, and add the listeners with lambdas.
buttonUp.addActionListener(e->{
System.out.println("I am moving up");
if (moveUp1())
moveUp2();
});
buttonLeft.addActionListener(e->{
System.out.println("I am moving left");
if (moveLeft1())
moveLeft2();
});
buttonRight.addActionListener(e->{
System.out.println("I am moving right.");
if (moveRight1())
moveRight2();
});
buttonDown.addActionListener(e->{
System.out.println("I am moving down");
if (moveDown1())
moveDown2();
});

JPanel sizing inside Another JPanel

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

Duplicate JLabels in a JFrame

I am making UNO game in JAVA. I am having problems with duplicate labels. I have a JFrame. In it, there are 7 JPanels. Every JPanel has a JLabel inside it. The JLabels are stored in an arrayList in another class. Every JLabel has an image inside it. The arrayList has duplicate JLabels inside it. I am getting the JLabels into the JPanels randomly. But when a duplicate JLabel is called, it is skipped. Help please.
The Deck:
public class Deck {
private ArrayList<JLabel> cards;
Zero zero = new Zero();
One one = new One();
Two two = new Two();
Three three = new Three();
Four four = new Four();
Five five = new Five();
Six six = new Six();
Seven seven = new Seven();
Eight eight = new Eight();
Nine nine = new Nine();
Reverse reverse = new Reverse();
Skip skip = new Skip();
DrawTwo drawTwo = new DrawTwo();
Wild wild = new Wild();
WildDrawFour wildDrawFour = new WildDrawFour();
public Deck() {
cards = new ArrayList<JLabel>();
cards.add(zero.getLabelR());
cards.add(zero.getLabelY());
cards.add(zero.getLabelG());
cards.add(zero.getLabelB());
cards.add(one.getLabelR());
cards.add(one.getLabelR());
cards.add(one.getLabelB());
cards.add(one.getLabelG());
cards.add(one.getLabelY());
cards.add(one.getLabelB());
cards.add(one.getLabelG());
cards.add(one.getLabelY());
cards.add(two.getLabelB());
cards.add(two.getLabelG());
cards.add(two.getLabelY());
cards.add(two.getLabelR());
cards.add(two.getLabelB());
cards.add(two.getLabelG());
cards.add(two.getLabelY());
cards.add(two.getLabelR());
cards.add(three.getLabelB());
cards.add(three.getLabelG());
cards.add(three.getLabelY());
cards.add(three.getLabelR());
cards.add(three.getLabelB());
cards.add(three.getLabelG());
cards.add(three.getLabelY());
cards.add(three.getLabelR());
cards.add(four.getLabelB());
cards.add(four.getLabelG());
cards.add(four.getLabelY());
cards.add(four.getLabelR());
cards.add(four.getLabelB());
cards.add(four.getLabelG());
cards.add(four.getLabelY());
cards.add(four.getLabelR());
cards.add(five.getLabelB());
cards.add(five.getLabelG());
cards.add(five.getLabelY());
cards.add(five.getLabelR());
cards.add(five.getLabelB());
cards.add(five.getLabelG());
cards.add(five.getLabelY());
cards.add(five.getLabelR());
cards.add(six.getLabelB());
cards.add(six.getLabelG());
cards.add(six.getLabelY());
cards.add(six.getLabelR());
cards.add(six.getLabelB());
cards.add(six.getLabelG());
cards.add(six.getLabelY());
cards.add(six.getLabelR());
cards.add(seven.getLabelB());
cards.add(seven.getLabelG());
cards.add(seven.getLabelY());
cards.add(seven.getLabelR());
cards.add(seven.getLabelB());
cards.add(seven.getLabelG());
cards.add(seven.getLabelY());
cards.add(seven.getLabelR());
cards.add(eight.getLabelB());
cards.add(eight.getLabelG());
cards.add(eight.getLabelY());
cards.add(eight.getLabelR());
cards.add(eight.getLabelB());
cards.add(eight.getLabelG());
cards.add(eight.getLabelY());
cards.add(eight.getLabelR());
cards.add(nine.getLabelB());
cards.add(nine.getLabelG());
cards.add(nine.getLabelY());
cards.add(nine.getLabelR());
cards.add(nine.getLabelB());
cards.add(nine.getLabelG());
cards.add(nine.getLabelY());
cards.add(nine.getLabelR());
cards.add(reverse.getLabelB());
cards.add(reverse.getLabelG());
cards.add(reverse.getLabelY());
cards.add(reverse.getLabelR());
cards.add(reverse.getLabelB());
cards.add(reverse.getLabelG());
cards.add(reverse.getLabelY());
cards.add(reverse.getLabelR());
cards.add(skip.getLabelB());
cards.add(skip.getLabelG());
cards.add(skip.getLabelY());
cards.add(skip.getLabelR());
cards.add(skip.getLabelB());
cards.add(skip.getLabelG());
cards.add(skip.getLabelY());
cards.add(skip.getLabelR());
cards.add(drawTwo.getLabelB());
cards.add(drawTwo.getLabelG());
cards.add(drawTwo.getLabelY());
cards.add(drawTwo.getLabelR());
cards.add(drawTwo.getLabelB());
cards.add(drawTwo.getLabelG());
cards.add(drawTwo.getLabelY());
cards.add(drawTwo.getLabelR());
cards.add(wild.getLabel());
cards.add(wild.getLabel());
cards.add(wild.getLabel());
cards.add(wild.getLabel());
cards.add(wildDrawFour.getLabel());
cards.add(wildDrawFour.getLabel());
cards.add(wildDrawFour.getLabel());
cards.add(wildDrawFour.getLabel());
shuffle();
}
public ArrayList<JLabel> getCards() {
return cards;
}
public void shuffle() {
Collections.shuffle(cards);
}
}
The GUI:
public class GUI extends JFrame {
JPanel card1;
JPanel card2;
JPanel card3;
JPanel card4;
JPanel card5;
JPanel card6;``
JPanel card7;
Back back = new Back();
Zero zero = new Zero();
One one = new One();
Two two = new Two();
Three three = new Three();
Four four = new Four();
Five five = new Five();
Six six = new Six();
Seven seven = new Seven();
Eight eight = new Eight();
Nine nine = new Nine();
Reverse reverse = new Reverse();
Skip skip = new Skip();
DrawTwo drawTwo = new DrawTwo();
Wild wild = new Wild();
WildDrawFour wildDrawFour = new WildDrawFour();
Deck ar = new Deck();
Random r = new Random();
public GUI() {
super("UNO");
setLayout(null);
setSize(1150, 690);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(35, 176, 40));
int a = r.nextInt(100) + r.nextInt(9) + 1;
card1 = new JPanel();
card1.setLayout(null);
card1.setBounds(65, 500, 85, 120);
card1.setBackground(new Color(35, 176, 40));
card1.add(ar.getCards().get(a)).setBounds(0, 0, 85, 120);
System.out.println(ar.getCards().get(a));
System.out.println(a);
int b = 0;
while (true) {
b = r.nextInt(100) + r.nextInt(9) + 1;
if (b != a) {
card2 = new JPanel();
card2.setLayout(null);
card2.setBounds(215, 500, 85, 120);
card2.setBackground(new Color(35, 176, 40));
card2.add(ar.getCards().get(b)).setBounds(0, 0, 85, 120);
System.out.println(ar.getCards().get(b));
System.out.println(b);
break;
} else
continue;
}
int c = 0;
while (true) {
c = r.nextInt(100) + r.nextInt(9) + 1;
if (c != a && c != b) {
card3 = new JPanel();
card3.setLayout(null);
card3.setBounds(365, 500, 85, 120);
card3.setBackground(new Color(35, 176, 40));
card3.add(ar.getCards().get(c)).setBounds(0, 0, 85, 120);
System.out.println(ar.getCards().get(c));
System.out.println(c);
break;
} else
continue;
}
int d = 0;
while (true) {
d = r.nextInt(100) + r.nextInt(9) + 1;
if (d != a && d != b && d != c) {
card4 = new JPanel();
card4.setLayout(null);
card4.setBounds(515, 500, 85, 120);
card4.setBackground(new Color(35, 176, 40));
card4.add(ar.getCards().get(d)).setBounds(0, 0, 85, 120);
;
System.out.println(ar.getCards().get(d));
System.out.println(d);
break;
} else
continue;
}
int e = 0;
while (true) {
e = r.nextInt(100) + r.nextInt(9) + 1;
if (e != a && e != b && e != c && e != b) {
card5 = new JPanel();
card5.setLayout(null);
card5.setBounds(665, 500, 85, 120);
card5.setBackground(new Color(35, 176, 40));
card5.add(ar.getCards().get(e)).setBounds(0, 0, 85, 120);
System.out.println(ar.getCards().get(e));
System.out.println(e);
break;
} else
continue;
}
int f = 0;
while (true) {
f = r.nextInt(100) + r.nextInt(9) + 1;
if (f != a && f != b && f != c && f != d && f != e) {
card6 = new JPanel();
card6.setLayout(null);
card6.setBounds(815, 500, 85, 120);
card6.setBackground(new Color(35, 176, 40));
card6.add(ar.getCards().get(f)).setBounds(0, 0, 85, 120);
System.out.println(ar.getCards().get(f));
System.out.println(f);
break;
} else
continue;
}
card7 = new JPanel();
card7.setLayout(null);
card7.setBounds(965, 500, 85, 120);
card7.setBackground(new Color(35, 176, 40));
card7.add(back.getLabel()).setBounds(0, 0, 85, 120);
add(card1);
add(card2);
add(card3);
add(card4);
add(card5);
add(card6);
add(card7);
setLocationRelativeTo(null);
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.setStroke(new BasicStroke(6));
g2.drawRoundRect(965, 523, 100, 135, 15, 15);
g2.setStroke(new BasicStroke(5));
g2.drawLine(0, 480, 1150, 480);
}
}
When duplication doesn't occur:
When duplication occurs:
Swing components can't be shared by multiple parents.
However an Icon can be shared.
So your get() method needs to be changed to get a random Icon, not a random label. Then once you retrieve the Icon, you create a new JLabel and add the Icon to the label. Then you add the label to the form.

Categories