Im looking a little bit of help here.
I have been given the task of creating a car park management system with a GUI interface as opposed to a console interface. The system has 15 spaces - 5 of those spaces being large can only fit 'large' vehicles - the other 10 are regular sized spaces. Whether they are large or not is determined by the parking attendant in the car park.
Upon entry to the car park, the attendant is required to fill in information about the car (reg number of vehicle, and to click a Yes or No radio button for whether or not the car is of 'high value' or not, or also if the car is a 'large vehicle')
I am currently trying to build the interface which when the program is run at first displays the car park (spaces will change from red to green when a space becomes available, and vice versa) which i have drawn using Graphics2D. (At this point i am not sure how to make this appear in a JFrame or whatever i need to use) Under the drawn car park with changing colours, i will include 3 JButtons - one to 'Add a Car', 'Remove a Car' and to 'Search for a Car.' I am unsure how to make the 'carPark' component and the afore mentioned JButtons to the window which will appear when it is run.
Consequently when i click these buttons a new window will appear displaying a form relevant to each button (add, remove and search)
What must i do to get the carpark and buttons to appear in the same window.
Here is the code i have created thus far - although it is very untidy and in pretty much one class i know whats going on and plan to split it up once i have everthing working. (I know this isnt efficient for writing code):
package carparksystem;
import javax.swing.*;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import java.awt.Color;
public class DrawCarPark extends javax.swing.JFrame
{
public DrawCarPark()
{
JButton addACar = new JButton("Add Car");
JButton removeACar = new JButton("Remove Car");
JButton searchCars = new JButton("Search Cars");
JFrame frame = new JFrame();
frame.add(new CarPark());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Car Park System");
frame.setSize(435, 600);
frame.setVisible(true);
frame.setResizable(false);
//frame.add(addACar);
//frame.add(removeACar);
//frame.add(searchCars);
GroupLayout mainLayout = new GroupLayout(getContentPane()); //chosen to display components in group layout
getContentPane().setLayout(mainLayout);
mainLayout.setAutoCreateGaps(true);
mainLayout.setAutoCreateContainerGaps(true);
mainLayout.setHorizontalGroup(mainLayout.createSequentialGroup()
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(frame)
.addGroup(mainLayout.createSequentialGroup()
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(addACar))
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(removeACar))
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchCars))))
);
mainLayout.setVerticalGroup(mainLayout.createSequentialGroup()
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(frame)
.addGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(addACar)
.addComponent(removeACar)
.addComponent(searchCars)))
);
//addCarForm();
//removeCarForm();
//searchCarForm();
}
private void addCarForm()
{
/*JPanel panel = new JPanel();
//frame.add(panel);
panel.setSize(450, 650);
panel.setVisible(true);
panel.getSize();*/
JLabel regNumLabel = new JLabel("Registration Number:");
JLabel highValLabel = new JLabel("High Value?");
JLabel largeLabel = new JLabel("Large Vehicle?");
JRadioButton btnYesHighVal = new JRadioButton("Yes", false);
JRadioButton btnNoHighVal = new JRadioButton("No", true);
JRadioButton btnYesLarge = new JRadioButton("Yes", false);
JRadioButton btnNoLarge = new JRadioButton("No", true);
ButtonGroup highVal = new ButtonGroup(); //allows just one radio button from the group to be selected
highVal.add(btnYesHighVal);
highVal.add(btnNoHighVal);
ButtonGroup largeCar = new ButtonGroup(); //allows just one radio button from the group to be selected
largeCar.add(btnYesLarge);
largeCar.add(btnNoLarge);
JTextField regNumField = new JTextField();
JButton addCar = new JButton(" Add ");
JButton addCancel = new JButton("Cancel");
GroupLayout addLayout = new GroupLayout(getContentPane()); //chosen to display components in group layout
getContentPane().setLayout(addLayout);
addLayout.setAutoCreateGaps(true);
addLayout.setAutoCreateContainerGaps(true);
addLayout.setHorizontalGroup(addLayout.createSequentialGroup()
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumLabel)
.addComponent(highValLabel)
.addComponent(largeLabel))
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumField)
.addGroup(addLayout.createSequentialGroup()
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(btnYesHighVal)
.addComponent(btnYesLarge))
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(btnNoHighVal)
.addComponent(btnNoLarge))))
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(addCar)
.addComponent(addCancel))
);
addLayout.setVerticalGroup(addLayout.createSequentialGroup()
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(regNumLabel)
.addComponent(regNumField)
.addComponent(addCar))
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(addLayout.createSequentialGroup()
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(highValLabel)
.addComponent(btnYesHighVal)
.addComponent(btnNoHighVal))
.addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(largeLabel)
.addComponent(btnYesLarge)
.addComponent(btnNoLarge)))
.addComponent(addCancel))
);
setSize(375, 150);
setTitle("Add Car");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
private void removeCarForm()
{
JLabel regNumLabel = new JLabel("Registration Number:");
JTextField regNumField = new JTextField();
JButton removeCar = new JButton("Remove");
JButton removeCancel = new JButton("Cancel");
GroupLayout removeLayout = new GroupLayout(getContentPane());
getContentPane().setLayout(removeLayout);
removeLayout.setAutoCreateGaps(true);
removeLayout.setAutoCreateContainerGaps(true);
removeLayout.setHorizontalGroup(removeLayout.createSequentialGroup()
.addGroup(removeLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumLabel))
.addGroup(removeLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumField))
.addGroup(removeLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(removeCar)
.addComponent(removeCancel))
);
removeLayout.setVerticalGroup(removeLayout.createSequentialGroup()
.addGroup(removeLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(regNumLabel)
.addComponent(regNumField)
.addComponent(removeCar))
.addGroup(removeLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(removeCancel))
);
setSize(375, 150);
setTitle("Search Car");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
private void searchCarForm()
{
JLabel regNumLabel = new JLabel("Registration Number:");
JTextField regNumField = new JTextField();
JButton searchCar = new JButton("Search");
JButton searchCancel = new JButton("Cancel");
GroupLayout searchLayout = new GroupLayout(getContentPane());
getContentPane().setLayout(searchLayout);
searchLayout.setAutoCreateGaps(true);
searchLayout.setAutoCreateContainerGaps(true);
searchLayout.setHorizontalGroup(searchLayout.createSequentialGroup()
.addGroup(searchLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumLabel))
.addGroup(searchLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(regNumField))
.addGroup(searchLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchCar)
.addComponent(searchCancel))
);
searchLayout.setVerticalGroup(searchLayout.createSequentialGroup()
.addGroup(searchLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(regNumLabel)
.addComponent(regNumField)
.addComponent(searchCar))
.addGroup(searchLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchCancel))
);
setSize(375, 150);
setTitle("Remove Car");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[]args)
{
DrawCarPark carPark = new DrawCarPark();
carPark.setVisible(true);
}
}
Also here is my main menu class with the carPark i have drawn:
package carparksystem;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JButton;
public class CarPark extends javax.swing.JPanel
{
private void draw(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
//Draw carpark boundary
g2.drawLine(20, 20, 400, 20);
g2.drawLine(20, 450, 20, 20);
g2.drawLine(20, 450, 400, 450);
g2.drawLine(400, 20, 400, 140);
g2.drawLine(400, 330, 400, 450);
g2.drawString("ENTER", 370, 180); //labels
g2.drawString("EXIT", 375, 300);
g2.setColor(Color.WHITE); //attendants box
g2.fill3DRect(330, 200, 70, 70, true);
g2.setColor(Color.BLACK);
g2.drawString("Attendant", 338, 230);
g2.drawString("Station", 345, 245);
g2.drawRect(330, 200, 70, 70);
g2.setColor(Color.GREEN);
g2.fillRect(40, 40, 50, 100); //8 first row spaces
g2.fillRect(110, 40, 50, 100); //7
g2.fillRect(180, 40, 50, 100); //6
g2.fillRect(250, 60, 40, 80); //2
g2.fillRect(310, 60, 40, 80); //1
g2.setColor(Color.BLACK); //drawRect palces a black border around shape
g2.drawRect(40, 40, 50, 100);
g2.drawRect(110, 40, 50, 100);
g2.drawRect(180, 40, 50, 100);
g2.drawRect(250, 60, 40, 80);
g2.drawRect(310, 60, 40, 80);
g2.setColor(Color.GREEN); //second row spaces
g2.fillRect(90, 195, 40, 80); //13
g2.fillRect(150, 195, 40, 80); //12
g2.fillRect(210, 195, 40, 80); //11
g2.fillRect(270, 195, 40, 80); //3
g2.setColor(Color.BLACK);
g2.drawRect(90, 195, 40, 80);
g2.drawRect(150, 195, 40, 80);
g2.drawRect(210, 195, 40, 80);
g2.drawRect(270, 195, 40, 80);
g2.setColor(Color.GREEN); //3rd row spaces
g2.fillRect(30, 330, 40, 80); //15
g2.fillRect(90, 330, 40, 80); //14
g2.fillRect(150, 330, 50, 100); //10
g2.fillRect(220, 330, 50, 100); //9
g2.fillRect(290, 330, 40, 80); //5
g2.fillRect(350, 330, 40, 80); //4
g2.setColor(Color.BLACK);
g2.drawRect(30, 330, 40, 80);
g2.drawRect(90, 330, 40, 80);
g2.drawRect(150, 330, 50, 100);
g2.drawRect(220, 330, 50, 100);
g2.drawRect(290, 330, 40, 80);
g2.drawRect(350, 330, 40, 80);
g2.drawString("1", 328, 105); //place labels on each shape
g2.drawString("2", 268, 105);
g2.drawString("3", 288, 240);
g2.drawString("4", 368, 375);
g2.drawString("5", 308, 375);
g2.drawString("6", 203, 95);
g2.drawString("7", 133, 95);
g2.drawString("8", 63, 95);
g2.drawString("9", 242, 385);
g2.drawString("10", 168, 385);
g2.drawString("11", 225, 240);
g2.drawString("12", 165, 240);
g2.drawString("13", 105, 240);
g2.drawString("14", 103, 375);
g2.drawString("15", 43, 375);
}
#Override
public void paintComponent(Graphics g)
{
draw(g);
}
}
Thanks in advance if anyone is willing to help.
The answer to the actual question you've asked is "use a layout manager in a JFrame and/or JPanel to position components, but think you already know that. You've used a GroupLayout manager in one of your two JFrames.
I think your problem may be that you have two of them. You declare a JFrame variable in DrawCarPark, and that class also extends JFrame. You probably don't need or want both, and it may be confusing you -- if you expect things to show up in the declared JFrame, the JFrame methods you call without reference to that instance will pass the compiler since DrawCarPark extends JFrame, but they won't be doing what you want. If you want one window with all your GUI elements in it, get rid of either the variable or the extension to JFrame.
I might suggest using a different layout manager for the remaining JFrame -- its default is BorderLayout, and it seems to me that might be better for what you want. Put your buttons into a JPanel (using whatever other layout manager you want, GroupLayout or whatever), and put that panel in the NORTH section of the BorderLayout. Then put your CarPark panel into the CENTER of that BorderLayout, and the resulting JFrame will have both.
Good luck with it.
Related
I am trying to create a pizza ordering system where the user is presented with two choices for pizza sauces (tomato and barbeque). I have already created the GUI and have already coded the design for the radio buttons, but I am not sure how to display the radio buttons on screen along with other elements. I have tried placing it within the paint code and the main aswell, but it changes the colour of the GUI.
I have attached two images. First one is the GUI which is meant to have the radio buttons placed underneath the text (pizza, base&sauce, topping).
Second one is the GUI I get when I add in radio button code.
//Code
package pizzaorder2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/**
*
* #author sm
*/
public class PizzaOrder2 extends JFrame {
static JFrame frame;
static String[] pizza = {"Supremo Supreme", "Supreme", "Chicken",
"Aussie",
"Vegie", "Hawaiian"};
static String[] base = {"Thin and Crispy", "Pan", "Cheese filled
crust"};
static String[] topping = {"None", "Pepperoni", "Salami", "Ham",
"Bacon", "Chicken", "Onion"};
static String tomatoString = "Tomato";
static String barbequeString = "Barbeque";
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 55));
g.drawString("Pizza Order", 175, 70);
Image imagepizza = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/piz.jpg").getImage();
g.drawImage(imagepizza, 20, 90, 140, 120, this);
Image imagesauce = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/sauce.jpg").getImage();
g.drawImage(imagesauce, 220, 90, 150, 120, this);
Image imagetopping = new ImageIcon("/Users/supriyamayuri/NetBeansProjects/DrawGraphics/src/top.jpg").getImage();
g.drawImage(imagetopping, 430, 90, 140, 120, this);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Pizza", 40, 240);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Base & Sauce", 210, 240);
g.setColor(Color.WHITE);
g.setFont(new Font("Helvetica", Font.BOLD, 25));
g.drawString("Topping", 450, 240);
}
public PizzaOrder2() {
//Create the radio buttons.
JRadioButton tomatoButton = new JRadioButton(tomatoString);
tomatoButton.setMnemonic(KeyEvent.VK_B);
tomatoButton.setActionCommand(tomatoString);
JRadioButton barbequeButton = new JRadioButton(barbequeString);
barbequeButton.setMnemonic(KeyEvent.VK_C);
barbequeButton.setActionCommand(barbequeString);
//Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(tomatoButton);
group.add(barbequeButton);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel();
radioPanel.add(tomatoButton);
radioPanel.add(barbequeButton);
add(radioPanel);
}
public static void main(String[] args) {
JFrame frame = new PizzaOrder2();
frame.setSize(600, 600);
frame.getContentPane().setBackground(new Color(40, 80, 120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I am doing a quiz program, therefore I need JRadioButton. However, the problem is that I do not know how to validate them such that only one Radio button can be selected.
public class QuizQ1Panel extends MasterPanel{
protected static final JFrame JFrame = null;
/**
* Create the panel.
* #param myPanel
*/
public QuizQ1Panel(JFrame mf) {
super(mf);
setBounds(100, 100, 900, 750);
JLabel lblQuiz1JY = new JLabel("This quiz consists of 5 questions.");
lblQuiz1JY.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQuiz1JY.setBounds(470, 162, 429, 20);
add(lblQuiz1JY);
JLabel lblQ1JY = new JLabel("Question 1");
lblQ1JY.setFont(new Font("Tahoma", Font.BOLD, 17));
lblQ1JY.setBounds(66, 216, 120, 20);
add(lblQ1JY);
JLabel lblQns1JY = new JLabel("What shape is used to represent a 'process' symbol?");
lblQns1JY.setFont(new Font("Tahoma", Font.BOLD, 17));
lblQns1JY.setBounds(66, 241, 534, 20);
add(lblQns1JY);
/* How do I validate JRadioButtons such that only one button can be selected?*/
JRadioButton rdbtnRectJY = new JRadioButton("A. Rectangle");
rdbtnRectJY.setBounds(60, 273, 155, 29);
add(rdbtnRectJY);
JRadioButton rdbtnDiaJY = new JRadioButton("B. Diamond");
rdbtnDiaJY.setBounds(60, 310, 155, 29);
add(rdbtnDiaJY);
JRadioButton rdbtnCirJY = new JRadioButton("C. Circle");
rdbtnCirJY.setBounds(60, 344, 155, 29);
add(rdbtnCirJY);
JRadioButton rdbtnParaJY = new JRadioButton("D. Parallelogram");
rdbtnParaJY.setBounds(60, 381, 155, 29);
add(rdbtnParaJY);
/* Currently when I clicked on JRadioButton, all can be selectd. However, I only want one button to be selected. So, how should I validate it? */
As stated in the comments, use Buttongroups for that task. They will allow only 1 RadionButton to be selected at a time: https://docs.oracle.com/javase/7/docs/api/javax/swing/ButtonGroup.html
credits to #LukasRotter
This question already has answers here:
Components in second JFrame not showing up
(2 answers)
Closed 7 years ago.
I'm trying to make a JFrame that will have graphics and 5 JButtons (which correspond with graphics on screen).
Yesterday my code ran, but now it is glitching and the graphics and buttons only appear when I am resizing the JFrame (pulling it with the cursor!). This is for a game I am making for a class project. If know what the problem may be/is, please tell me. I've been staring at this for so long and I think someone with fresh eyes or more skill than myself could see why the code is wrong. >.<
It has 2 classes, one for graphics and one with a main.
The class for the graphics:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Polygon;
public class drawingComponentMap extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
drawingComponentMap DCM = new drawingComponentMap(); // this is used in
// the class
// below
Color door = new Color(255, 218, 185); // the graphics are making a
// house, hence the colours
Color glass = new Color(173, 216, 230);
Color mapGrass = new Color(144, 238, 144);
g.setColor(mapGrass);
g2.fillRect(0, 0, 500, 500);
// circles to correspond with buttons (as in each button reps a circle)
Color minigame = new Color(221, 160, 221);
g.setColor(minigame);
g2.fillOval(10, 20, 50, 50);
g2.fillOval(220, 70, 50, 50);
g2.fillOval(20, 200, 50, 50);
g2.fillOval(100, 300, 50, 50);
g2.fillOval(200, 200, 50, 50);
Color black = new Color(0, 0, 0);
g.setColor(black);
g2.drawOval(10, 20, 50, 50);
g2.drawOval(220, 70, 50, 50);
g2.drawOval(20, 200, 50, 50);
g2.drawOval(100, 300, 50, 50);
g2.drawOval(200, 200, 50, 50);
// the house graphic
Color walls = new Color(210, 105, 3);
g.setColor(walls);
g2.fillRect(300, 300, 150, 200);
Color roof = new Color(165, 42, 42);
g.setColor(roof);
g2.drawRect(300, 300, 150, 200);
int[] xPoints = { 300, 375, 450 };
int[] yPoints = { 300, 225, 300 };
Polygon imageTriangle = new Polygon(xPoints, yPoints, 3);
g2.fillPolygon(imageTriangle);
g.setColor(black);
g2.drawPolygon(imageTriangle);
g.setColor(glass);
g2.fillRect(380, 350, 50, 50);
g.setColor(door);
g2.fillRect(325, 450, 30, 50);
g.setColor(black);
g2.drawRect(325, 450, 30, 50);
g2.fillOval(330, 470, 5, 5);
g2.drawRect(380, 350, 50, 50);
g2.drawString("Where do you want to go?", 10, 400);
}
}
this is the class which uses the graphics, and where the jframe, jlabel, and jbuttons are made.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Map {
JFrame window = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton();
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
}
}
Sorry about the formatting of the code/text portion of this question. I'm in class right now.
It's just a single statement issue - window.setVisible(true).
Move your window.setVisible(true) statement to the end. Your main method contents should now look like this (just for your reference):
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
window.setVisible(true);
I am currently doing a diploma course in Java and for our project we have to create a Restaurant Calculator(See screenshot), I have the majority of the GUI done but I am having great difficulty with the SQL. I have never used SQL before so I'm not 100% certain what to do. I understand how it works but I can't even run the SQL file that the college supplied us in MySQL. Any help with this would be greatly appreciated as I am really struggling with this. I have had this GUI done the past 2 weeks and have been searching online for help but cannot get my head around it
Code is below...
import java.awt.Container;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RestaurantCalculator {
private static JTextField TotalText;
private static JTextField TaxText;
private static JTextField Table;
private static JTextField Sub;
private static JTextField WName;
private static JComboBox BevMenu;
private static JComboBox AppMenu;
private static JComboBox MainMenu;
private static JComboBox DesMenu;
public static void testFun(String myName){
TotalText.setText(myName);
}
public static void addComponentsToPane(Container pane){
pane.setLayout(null);
Border border = BorderFactory.createLoweredBevelBorder();
Border button = BorderFactory.createRaisedBevelBorder();
JLabel Welcome = new JLabel("Restaurant");
Welcome.setBounds(250, 5, 150, 100);
Welcome.setFont(new Font("Arial Black", Font.BOLD, 20));
JLabel Waiter = new JLabel("Waiter Information");
Waiter.setBounds(100, 100, 200, 100);
Waiter.setFont(new Font("Arial Black", Font.BOLD, 14));
JLabel Tableno = new JLabel("Table number:");
Tableno.setBounds(120, 130, 200, 100);
Tableno.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel WaiterName = new JLabel("Waiter Name:");
WaiterName.setBounds(120, 160, 200, 100);
WaiterName.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel MenuItems = new JLabel("Menu Items");
MenuItems.setBounds(100, 220, 150, 100);
MenuItems.setFont(new Font("Arial Black", Font.BOLD, 14));
JLabel Beverage = new JLabel("Beverage:");
Beverage.setBounds(120, 250, 200, 100);
Beverage.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel Appetizer = new JLabel("Appetizer:");
Appetizer.setBounds(120, 280, 200, 100);
Appetizer.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel MainCourse = new JLabel("Main Course:");
MainCourse.setBounds(120, 310, 200, 100);
MainCourse.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel Dessert = new JLabel("Dessert:");
Dessert.setBounds(120, 340, 200, 100);
Dessert.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel SubTotal = new JLabel("Sub Total:");
SubTotal.setBounds(120, 440, 200, 100);
SubTotal.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel Tax = new JLabel("Tax:");
Tax.setBounds(120, 470, 200, 100);
Tax.setFont(new Font("Arial Black", Font.BOLD, 12));
JLabel Total = new JLabel("Total:");
Total.setBounds(120, 500, 200, 100);
Total.setFont(new Font("Arial Black", Font.BOLD, 12));
Table = new JTextField(10);
Table.setBounds(290, 171, 150, 20);
Table.setBorder(border);
WName = new JTextField(11);
WName.setBounds(290, 201, 150, 20);
WName.setBorder(border);
Sub = new JTextField(10);
Sub.setBounds(260,482,150, 20);
Sub.setBorder(border);
Sub.setEditable(false);
TotalText = new JTextField(10);
TotalText.setBounds(260,545,150, 20);
TotalText.setBorder(border);
TotalText.setEditable(false);
TaxText = new JTextField(10);
TaxText.setBounds(260,515,150, 20);
TaxText.setBorder(border);
TaxText.setEditable(false);
BevMenu = new JComboBox();
BevMenu.setBounds(290, 295, 180, 20);
AppMenu = new JComboBox();
AppMenu.setBounds(290, 325, 180, 20);
MainMenu = new JComboBox();
MainMenu.setBounds(290, 355, 180, 20);
DesMenu = new JComboBox();
DesMenu.setBounds(290, 385, 180, 20);
JButton calculateJButton;
calculateJButton = new JButton( "Calculate Bill" );
calculateJButton.setBounds(250,425, 170, 30);
calculateJButton.setBorder(button);
pane.add(Welcome);
pane.add(Waiter);
pane.add(Tableno);
pane.add(WaiterName);
pane.add(MenuItems);
pane.add(Beverage);
pane.add(Appetizer);
pane.add(MainCourse);
pane.add(Dessert);
pane.add(SubTotal);
pane.add(Tax);
pane.add(Total);
pane.add(Table);
pane.add(WName);
pane.add(Sub);
pane.add(TaxText);
pane.add(TotalText);
pane.add(calculateJButton);
pane.add(BevMenu);
pane.add(AppMenu);
pane.add(MainMenu);
pane.add(DesMenu);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Restaurant Bill Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Size and display the window.
Insets insets = frame.getInsets();
frame.setSize(600 + insets.left + insets.right,
700 + insets.top + insets.bottom);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
String theBest = "test";
testFun(theBest);
}
});
}
I am trying to start the program with jcheckbox hat selected and rectangle visible then the Rectangle disappears when the checkbox is unselected and repainted as checkbox is selected again. When I run the program and check the box another check box appears or left of the frame.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
public class Head extends JPanel {
JCheckBox hat;
public Head() {
hat = new JCheckBox("Hat");
hat.setSelected(true);
hat.addItemListener(new CheckSelection());
add(hat);
}
class CheckSelection implements ItemListener {
public void itemStateChanged(ItemEvent ie) {
repaint();
}
}
public void paintComponent(Graphics g) {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
}
}
public static void main(String[] args) {
Head head = new Head();
JFrame f = new JFrame();
f.add(head);
f.setSize(400, 400);
//f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You've broken the paint chain by not calling the paintComponent's super method
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
if (hat.isSelected()) {
g.drawRect(100, 90, 120, 10);
} else {
setForeground(Color.RED);
g.drawOval(110, 100, 100, 100);
g.drawOval(130, 120, 20, 15);
g.drawOval(170, 120, 20, 15);
g.drawLine(160, 130, 160, 160);
g.drawOval(140, 170, 40, 15);
}
}
The Graphics context is a shared resource between components, one of the jobs of paintComponent is to prepare the Graphics for painting, typically by filling it with the background color of the component. So failing to call super.paintComponent means that what ever was previously painted to the Graphics context will still be there
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing