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

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

Related

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

How to make a JPanel into a BufferedImage Java

I have a half-working paint/turtle graphics program but I am having a few issues.
I am going to need to save the image that is drawn at some point - I know I need to use a BufferedImage but how do I go about this? I have attached a little bit of my code below.
In short I have a JFrame with a text field and a white JPanel below it. When commands are typed in by the user lines are drawing through another class and appear on the JPanel. I know I won't be able to save them off the JPanel to an image but have no understanding of how to implement a buffered image and what i would/wouldn't need to change.
Please be kind, I am new to programming and haven't finished some parts of my code yet.
Thanks in advance
public class Turtle2 extends JFrame implements ActionListener, KeyListener{
JMenuBar menuBar;
JMenu help, file;
JPanel panel, panel2;
JMenuItem newO, load, save, exitO, about;
JTextField text;
int savecounter = 0, newcounter = 1, part2I = 0;
int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
int trigger = 1, turnleftconstant = 0, turnrightconstant =0, direction =0;
int col = 0;
public Turtle2() {
setLayout(new FlowLayout());
setSize(1000, 1000);
setTitle("Graphic");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//menu bar
//sets up general look of window
panel = new JPanel();
panel.setBackground(Color.darkGray);
//implements box layout
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
//sets up drawing area
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(500, 500));;
panel2.setBackground(Color.WHITE);
panel2.setBorder(BorderFactory.createLineBorder(Color.darkGray, 3));
//starting point on drawing area co-ordinates
x1 = 15; x2 = 15; y1 = 230; y2 =230;
//starting point implemented
LinePen first = new LinePen(x1, y1, x2, y2, col);
panel2.add(first);
//sets up user input text box
text = new JTextField(30);
//add action listener to text box - ready for input and details responses
text.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//retrieves user input
String actions = text.getText();
first.setVisible(true);
//commands from text
//add the command line textfeild to the interface
panel.add(text);
//uses border layout to set the layout of the interface
getContentPane().add(BorderLayout.NORTH, panel);
getContentPane().add(BorderLayout.CENTER, panel2);
//set the size of the interface
setSize(600,600);
//ensure the interface is visible
setVisible(true);
}
I would keep an array of all your lines, then iterate through them, and then use img.createGraphics() to draw your lines and other graphics.

JFrame not becoming transparent

Recently I have been trying to get a transparent JFrame without success.
I want to make all components visible but not the frame and I see that people set the background to transparent and set Opaque to false.
I am doing this but without success.
public class KeyDialog extends JFrame {
public static MapPanel mapPanel = new MapPanel();
public KeyDialog() {
GridBagConstraints customGridBagLayout = new GridBagConstraints();
setLayout(new GridBagLayout());
setUndecorated(true);
// Title - Row 1
JTextField row1 = new JTextField();
row1.setSize(new Dimension(this.getWidth(), HEIGHT));
row1.setFont(new Font("Arial", Font.PLAIN, 30));
PromptSupport.setPrompt("Title Goes Here", row1);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.gridy = 0;
add(row1, customGridBagLayout);
// Key - Row 2
JPanel row2 = new JPanel();
row2.setOpaque(false);
// With Key
JPanel withKey = titleBoxKey(true);
withKey.setBackground(new Color(0, 0, 0, 0));
row2.add(withKey);
// Against Key
JPanel againstKey = titleBoxKey(false);
againstKey.setBackground(new Color(0, 0, 0, 0));
row2.add(againstKey);
customGridBagLayout.gridy = 1;
add(row2, customGridBagLayout);
pack();
}
public static JPanel titleBoxKey(boolean with) {
JPanel keyPanel = new JPanel();
keyPanel.setLayout(new GridBagLayout());
GridBagConstraints customGridBagLayout = new GridBagConstraints();
customGridBagLayout.insets = new Insets(7, 7, 7, 7); // Padding
Color republicanColor = null;
Color democraticColor = null;
if (with) {
republicanColor = mapPanel.getRepublicanWithColor();
democraticColor = mapPanel.getRepublicanAgainstColor();
} else if (!with) {
republicanColor = mapPanel.getDemocraticAgainstColor();
democraticColor = mapPanel.getDemocraticAgainstColor();
}
// Row 1 - Rectangles and Text Field
// Democratic Rectangle
JLabel republicanRect = mapPanel.drawRect(republicanColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 0;
keyPanel.add(republicanRect, customGridBagLayout);
// Republican Rectangle
JLabel democraticRect = mapPanel.drawRect(democraticColor);
customGridBagLayout.fill = GridBagConstraints.HORIZONTAL;
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 0;
keyPanel.add(democraticRect, customGridBagLayout);
// With/Against Label
JLabel infoLabel;
if (with) {
infoLabel = new JLabel("With");
} else {
infoLabel = new JLabel("Against");
}
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 2;
customGridBagLayout.gridy = 0;
keyPanel.add(infoLabel, customGridBagLayout);
// Row 2 - Bottom Text
// Republican Label
JLabel republicanLabel = new JLabel("Republican");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 0;
customGridBagLayout.gridy = 1;
keyPanel.add(republicanLabel, customGridBagLayout);
// Democrat Label
JLabel democraticLabel = new JLabel("Democratic");
customGridBagLayout.weightx = 0.5;
customGridBagLayout.gridx = 1;
customGridBagLayout.gridy = 1;
keyPanel.add(democraticLabel, customGridBagLayout);
return keyPanel;
}
}
You've made a nice attempt, but try this instead.
// Apply a transparent colour
setBackground(new Color(0, 255, 0, 0));
Simply add that code and your done :)
I set the background to frame.setBackground(new Color(0, 0, 0, 0)); thanks to the help of #JontyMorris
I then set all the contents on the frame to opaque panel.setOpaque(false);
and removed the backgrounds I set so the stripped down version looks like this...
// Frame
JFrame frame = new JFrame();
frame.setBackground(new Color(0, 0, 0, 0)); // Setting frame to be transparent
// Components
JPanel panel = new JPanel();
//add stuff to panel...
panel.setOpaque(false);
Actually there's a bit more to it than setting the background color. You have to change the undecorated property to true. Here's a quick tutorial you can follow. Well explained.
https://www.youtube.com/watch?v=zecGJfNHPWo

JList is showing duplicates

I am working on a small example using Java Swing where I want to draw a sine graph on one panel and the co-ordinates of the graph in another panel. So I created a class that extends the JFrame then I created the JPanel for graph and co-ordinates. For displaying co-ordinates I am using JList. Now the problem is the co-ordinates are showing duplicate values. Here is my code:
public class MyFrame extends JFrame {
JList list;
DecimalFormat df = new DecimalFormat("#.###");
DefaultListModel model = new DefaultListModel();
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 600);
contentPane = new JPanel();
contentPane.setBorder(new LineBorder(new Color(0, 0, 0)));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 2, 0, 0));
JPanel panel = new MyGraph();
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
contentPane.add(panel);
list = new JList(model);
list.setVisibleRowCount(4);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0)));
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
JLabel lblNewLabel_1 = new JLabel("X - Y");
panel_1.add(lblNewLabel_1);
JScrollPane slistScroller = new JScrollPane(list);
panel_1.add(slistScroller);
contentPane.add(panel_1);
}
class MyGraph extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int xBase = 10;
int top = 100;
int yScale = 10;
int xAxis = 360;
int yBase = top + yScale;
g.drawLine(xBase, top, xBase, top + 2 * yScale);
g.drawLine(xBase, yBase, xBase + xAxis, yBase);
g.setColor(Color.red);
int x2=0, y2=0;
int x1 = xBase + 0;
int y1 = yBase - (int) (10*Math.sin(0) * yScale);
int i;
for (i = 0; i < 10; i++) {
x2 = xBase + i;
y2 = yBase - (int) (10*Math.sin(i) * yScale);
g.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
df = new DecimalFormat("#.###");
model.addElement(i +" -- " + df.format(10*Math.sin(i)));
}
model.addElement("------END----------");
}
}
}
Here is the output of my program:
As per my program, I have a for loop from angles 0 to 10 and I am adding the values to DefaultListModel model which is added to JList list.
Can someone please help me where I am doing mistake in this code?
Also even when I have this line list.setVisibleRowCount(4); , I was expecting only 4 records displayed to the user with a scroll-bar, but as per the output image it is not working like that.
paintComponent may be any number of times, for any number of reasons, try resizing the frame and see what happens.
Your paint method should focus on doing just that, painting.
You need to change the process so that the paintComponent becomes depend on the model, not the other way round.
Take a look at Painting in AWT and Swing for more details about painting in Swing.
You may also want to consider using a ListCellRender to render the data in the model in the JList, this way, you could more easily share the model and it's data.
See Writing a Custom Cell Renderer for more details

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

Categories