I have a new error with the code below. Originally I had some classes that were named different. I changed them, but new errors arose. The code below will not run correctly because I had to remove some of it for the post. It had too many characters. Hopefully I didn't get rid of the part that is needed to be fixed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import javax.swing.ButtonGroup;
import java.awt.FlowLayout;
public class VolCalc extends JFrame implements ActionListener{
private JTabbedPane jtabbedPane;
private JPanel general;
private JPanel pools;
private JPanel tempCalc;
private JPanel options;
private JPanel hotTub;
private JComponent date;
JTextField lengthText, widthText, depthText, volumeText;
public void CalcVolume(){
JPanel customers = new JPanel();
setTitle("Pools");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createGeneral();
createPools();
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("General", general);
jtabbedPane.addTab("Pools", pools);
jtabbedPane.addTab("Temp Calculator", tempCalc);
jtabbedPane.addTab("Options", options);
jtabbedPane.addTab("Hot Tubs", hotTub);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE GENERAL */
public void createGeneral(){
general = new JPanel();
general.setLayout(null);
JLabel dateLabel = new JLabel("Todays Date");
dateLabel.setBounds(10, 15, 150, 20);
general.add(dateLabel);
JFormattedTextField date = new JFormattedTextField(
java.util.Calendar.getInstance().getTime());
date.setEditable(false);
date.setBounds(150,15,150,20);
general.add(date);
JButton Exit = new JButton("Exit");
Exit.setBounds(10,80,150,30);
Exit.addActionListener(this);
Exit.setBackground(Color.red);
general.add(Exit);
}
/* CREATE POOLS */
public void createPools(){
pools = new JPanel();
pools.setLayout(null);
JLabel lengthLabel = new JLabel( "Enter the length of swimming pool(ft):");
lengthLabel.setBounds(10, 15, 260, 20);
pools.add(lengthLabel);
lengthText = new JTextField();
lengthText.setBounds( 260, 15, 150, 20 );
pools.add( lengthText );
JLabel widthLabel = new JLabel("Enter the width of the swimming pool(ft):");
widthLabel.setBounds(10, 60, 260, 20);
pools.add(widthLabel);
widthText = new JTextField();
widthText.setBounds(260, 60, 150, 20);
pools.add(widthText);
JLabel depthLabel = new JLabel("Enter the average depth the swimming pool(ft):");
depthLabel.setBounds(10, 100, 260, 20);
pools.add( depthLabel);
depthText = new JTextField();
depthText.setBounds(260, 100, 150, 20);
pools.add(depthText);
JLabel volumeLabel = new JLabel("The pool volume is:(ft ^3");
volumeLabel.setBounds(10, 200, 260, 20);
pools.add(volumeLabel);
volumeText = new JTextField();
volumeText.setBounds(260, 200, 150, 20);
volumeText.setEditable(false);
pools.add(volumeText);
JButton calcVolume = new JButton("Calculate Volume");
calcVolume.setBounds(150,250,150,30);
calcVolume.addActionListener(this);
pools.add(calcVolume);
JButton Exit = new JButton("Exit");
Exit.setBounds(350,250,80,30);
Exit.addActionListener(this);
Exit.setBackground(Color.white);
pools.add(Exit);
}
public void createOptions()
{
options = new JPanel();
options.setLayout( null );
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds( 150, 50, 150, 20 );
options.add( labelOptions );
JTextField newTitle = new JTextField();
newTitle.setBounds( 150, 70, 150, 20 );
options.add( newTitle );
JButton newName = new JButton("Set New Name");
newName.setBounds(100,115,150,30);
newName.addActionListener(this);
newName.setBackground(Color.yellow);
options.add(newName);
JButton Exit = new JButton("Exit");
Exit.setBounds(250,115,80,30);
Exit.addActionListener(this);
Exit.setBackground(Color.red);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton)event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed(); return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
if ("Calculate Volume".equalsIgnoreCase(buttonLabel)){
Calculate_Volume(); return;
}
if ("Customers".equalsIgnoreCase(buttonLabel)){
Customers(); return;
}
if ("Calculate Volume".equalsIgnoreCase(buttonLabel)){
Calculate_Volume();
return;
}
if ("Options".equalsIgnoreCase(buttonLabel)){
Options();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.exit(0);
}
private void Calculate_Volume(){
String lengthString, widthString, depthString;
int length=0;
int width=0;
int depth=0;
lengthString = lengthText.getText();
widthString = widthText.getText();
depthString = depthText.getText();
if (lengthString.length() < 1 || widthString.length() < 1 || depthString.length() < 1){
volumeText.setText("Error! Must enter in all three numbers!!");
return;
}
length = Integer.parseInt(lengthString );
width = Integer.parseInt(widthString );
depth = Integer.parseInt(depthString);
if (length != 0 || width != 0 || depth != 0){
volumeText.setText((length * width * depth) + "" );
}
else{
volumeText.setText("Error! Must Enter in all three numbers!!");
return;
}
}
private void Customers(){
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolCalc();
frame.setSize(525, 350);
frame.setVisible(true);
}
}
Errs:
java.lang.NoClassDefFoundError: VolCac Caused by: java.lang.ClassNotFoundException: VolCac at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) Exception in thread "main"
My guess is that you tried to use a previous launch configuration, which was using the old name. Launching the class from the context menu (or using the appropriate keyboard shortcut, which I can't remember now - something like Ctrl-Alt-X, J) will use the new name, and may solve the problem.
Alternatively, you could use the dropdown next to the "Run" button and edit the launch configuration to tell it the correct class name to launch.
Don't know how you instantiate this but the stacktrace indicate the "VolCac" class is not found. In the code you pasted here, your class is named "VolCalc"...
Related
Newbie question:
So this code here
public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if(comboGroup.getSelectedItem().equals("Betta Fish")){
comboItem.removeAllItems();
arrayItem.add("Plakat");
arrayItem.add("Halfmoon");
arrayItem.add("Crown Tail");
arrayItem.add("Double Tail");
iter = arrayItem.iterator();
while(iter.hasNext()){
comboItem.addItem(iter.next());
}
}
else if(comboGroup.getSelectedItem().equals("Snails")){
comboItem.removeAllItems();
arrayItem.add("Apple Horn");
arrayItem.add("RamsHorn");
arrayItem.add("Pond Snail");
arrayItem.add("Assassin Snail");
iter = arrayItem.iterator();
while(iter.hasNext()){
comboItem.addItem(iter.next());
}
works when I try it on comboBoxes from Design tab in NetBeans. But when I try to apply it to my coded ComboBox, I get a message from evt saying Unused method parameters should be removed. Can I get an explanation why and what is the alternative for hardcoded comboBox?
Purpose of code: a dynamic comboBox so whatever I pick from comboBox1 will have each own set of lists for comboBox2
NOTE: I also tried to change comboItemItemStateChanged to just itemStatChanged.
Source code of my project: https://github.com/kontext66/GuwiPos/blob/main/GuwiPos
Sorry for the confusion everyone, I do have a main class.
public class Main{
public static void main(String[] args){
new GuwiPos();
new HelpWin();
}
}
Main.java, GuwiPos.java
It's quite simple, really.
The message is just NetBeans informing you that the code of method comboItemItemStateChanged does not reference the method parameter evt. It is not an error nor even a warning. You can ignore it. NetBeans displays these "hints" in its editor when you write code whereas NetBeans GUI builder generates code.
Note that method comboItemItemStateChanged will be called each time an item in the JComboBox is selected and also each time an item is de-selected. I'm guessing that you only want the code to run when an item is selected, hence the first line of method comboItemItemStateChanged should be
if (evt.getStateChange() == ItemEvent.SELECTED) {
and then you are referencing the method parameter and the "hint" will go away.
Refer to How to Write an Item Listener
Edit
I think maybe you would benefit from learning about GUI design. I have never seen one like yours. I would like to know how you arrived at that design. In any case, the below code addresses only the functionality whereby the list in comboItem adjusts depending on the selected item in comboGroup.
In my experience, removing and adding items to the JComboBox via methods removeAllItems and addItem, is very slow. It is much more efficient to simply replace the JComboBox model which is what I have done in the below code. For small lists such as yours, the difference will not be noticed but it increases as the lists get larger.
Also, the [JComboBox] selected item is in the evt parameter to method comboItemItemStateChanged.
Your original code did not add an item listener to comboGroup nor did it have a main method. I have added these in the below code. Note that the item listener is added via a method reference.
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author kahbg
*/
public class GuwiPos extends JFrame implements ActionListener {
public static final Map<String, ComboBoxModel<String>> LISTS;
JButton buttonBasket;
JButton buttonHelp;
JTextField txtGroup;
JTextField txtItem;
JTextField txtQty;
JTextField txtTotal;
JTextField txtPrice;
JComboBox<String> comboGroup;
JComboBox<String> comboItem;
static {
LISTS = new HashMap<>();
Vector<String> v = new Vector<>();
v.add("Plakat");
v.add("Halfmoon");
v.add("Crown Tail");
v.add("Double Tail");
ComboBoxModel<String> model = new DefaultComboBoxModel<>(v);
LISTS.put("Betta Fish", model);
v = new Vector<>();
v.add("Apple Horn");
v.add("RamsHorn");
v.add("Pond Snail");
v.add("Assassin Snail");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Snails", model);
v = new Vector<>();
v.add("Small Fine Net");
v.add("Large Fine Net");
v.add("Flaring Mirror");
v.add("Aquarium Hose");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Supplies", model);
v = new Vector<>();
v.add("Tubifex");
v.add("Daphnia");
v.add("Optimum Pellets");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Food", model);
}
GuwiPos() {
// ComboBox
String[] products = {"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
comboGroup = new JComboBox<String>(products);
comboGroup.addItemListener(this::comboItemItemStateChanged);
comboGroup.setBounds(130, 35, 150, 40);
comboItem = new JComboBox<String>();
comboItem.setBounds(130, 85, 150, 40);
// TextFields
txtPrice = new JTextField();
txtPrice.setBounds(130, 135, 150, 40);
txtQty = new JTextField();
txtQty.setBounds(130, 185, 150, 40);
txtTotal = new JTextField();
txtTotal.setBounds(130, 235, 150, 40);
// txtTotalAmt = new JTextField(); to code later on
// txtPaid = new JTextField(); to code later on
// txtChange = new JTextField(); to code later on
// Labels
// Product
JLabel labelProduct = new JLabel();
labelProduct.setText("Item Group");
labelProduct.setBounds(10, 5, 100, 100);
// Item
JLabel labelItem = new JLabel();
labelItem.setText("Item");
labelItem.setBounds(10, 55, 100, 100);
// Price
JLabel labelPrice = new JLabel();
labelPrice.setText("Price");
labelPrice.setBounds(10, 105, 100, 100);
// Qty
JLabel labelQty = new JLabel();
labelQty.setText("Quantity");
labelQty.setBounds(10, 155, 100, 100);
// Total
JLabel labelTotal = new JLabel();
labelTotal.setText("Total");
labelTotal.setBounds(10, 205, 100, 100);
// Buttons
buttonBasket = new JButton();
buttonBasket.setBounds(0, 0, 300, 50);
buttonBasket.setText("Add to Basket");
buttonBasket.setFocusable(false);
buttonBasket.setBorder(BorderFactory.createEtchedBorder());
buttonBasket.addActionListener(this);
JButton buttonPay = new JButton();
buttonPay.setText("PAY");
buttonPay.setBounds(0, 50, 150, 100);
buttonPay.setFocusable(false);
buttonPay.setBorder(BorderFactory.createEtchedBorder());
buttonPay.addActionListener(e -> System.out.println("Payment Success"));
JButton buttonCancel = new JButton();
buttonCancel.setText("CANCEL");
buttonCancel.setBounds(0, 150, 150, 100);
buttonCancel.setFocusable(false);
buttonCancel.setBorder(BorderFactory.createEtchedBorder());
buttonCancel.addActionListener(e -> System.out.println("Transaction Cancelled"));
JButton buttonDiscount = new JButton();
buttonDiscount.setText("Apply Discount?");
buttonDiscount.setBounds(150, 50, 150, 50);
buttonDiscount.setFocusable(false);
buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
buttonDiscount.addActionListener(e -> System.out.println("20% Discount Applied"));
JButton buttonHelp = new JButton();
buttonHelp.setText("HELP");
buttonHelp.setBounds(150, 100, 150, 100);
buttonHelp.setFocusable(false);
buttonHelp.setBorder(BorderFactory.createEtchedBorder());
JButton buttonDelete = new JButton();
buttonDelete.setText("DELETE");
buttonDelete.setBounds(150, 200, 150, 50);
buttonDelete.setFocusable(false);
buttonDelete.setBorder(BorderFactory.createEtchedBorder());
buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));
// Panels
// Left contains item and price
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
bluePanel.setBounds(0, 0, 300, 300); // x,y,width,height
bluePanel.setLayout(null);
// Right contains product basket
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setBounds(300, 0, 600, 300); // x,y,width,length
redPanel.setLayout(null);
// Bottom Left contains buttons pay,change,discount
JPanel greenPanel = new JPanel();
greenPanel.setBackground(Color.green);
greenPanel.setBounds(0, 300, 300, 450);// x,y,width,length
greenPanel.setLayout(null);
// Bottom Right contains total amount
JPanel yellowPanel = new JPanel();
yellowPanel.setBackground(Color.yellow);
yellowPanel.setBounds(0, 300, 900, 450);// x,y,width,length
yellowPanel.setLayout(null);
this.setTitle("Open Betta POS");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(900, 590);
this.setResizable(false);
this.setVisible(true);
// ADDED AWT
bluePanel.add(txtQty);
bluePanel.add(txtTotal);
bluePanel.add(txtPrice);
bluePanel.add(comboItem);
bluePanel.add(comboGroup);
bluePanel.add(labelProduct);
bluePanel.add(labelItem);
bluePanel.add(labelPrice);
bluePanel.add(labelQty);
bluePanel.add(labelTotal);
greenPanel.add(buttonBasket);
greenPanel.add(buttonPay);
greenPanel.add(buttonCancel);
greenPanel.add(buttonDiscount);
greenPanel.add(buttonHelp);
greenPanel.add(buttonDelete);
this.add(bluePanel);
this.add(redPanel);
this.add(greenPanel);
this.add(yellowPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonBasket) {
System.out.println("Added Item to Basket: " + comboGroup.getSelectedItem() + "\n"
+ comboItem.getSelectedItem());
}
}
// This is not working
public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object selection = evt.getItem();
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if (selection.equals("Betta Fish")) {
comboItem.setModel(LISTS.get("Betta Fish"));
}
else if (selection.equals("Snails")) {
comboItem.setModel(LISTS.get("Snails"));
}
else if (selection.equals("Supplies")) {
comboItem.setModel(LISTS.get("Supplies"));
}
else if (selection.equals("Food")) {
comboItem.setModel(LISTS.get("Food"));
}
else if (selection.equals("Select Item...")) {
comboItem.removeAllItems();
arrayItem.add("Select Item...");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GuwiPos());
}
}
Your code (improved version - minus one ActionListener)
public class SwingApp {
private static JComboBox<String> comboItem;
private static JComboBox<String> productCombo;
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
createAndShowGUI();
}
});
}
private static void createAndShowGUI () {
JFrame frame = createMainFrame();
JPanel bluePanel = createBluePanel();
JPanel greenPanel = createGreenPanel();
JPanel redPanel = createRedPanel();
JPanel yellowPanel = createYellowPanel();
frame.add(bluePanel);
frame.add(greenPanel);
frame.add(redPanel);
frame.add(yellowPanel);
frame.setVisible(true);
}
private static JFrame createMainFrame () {
JFrame frame = new JFrame("Open Betta POS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(900, 590);
frame.setResizable(false);
return frame;
}
private static JPanel createBluePanel () {
ComboSelectionListener productComboListener = new ComboSelectionListener();
JPanel panel = new JPanel(null); // Sets layout manager to null which is a bad idea!
String[] products =
{"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
productCombo = new JComboBox<>(products);
productCombo.setBounds(130, 35, 150, 40);
productCombo.setActionCommand("selectProduct");
productCombo.addActionListener(productComboListener);
comboItem = new JComboBox<>();
comboItem.setBounds(130, 85, 150, 40);
// TextFields
JTextField txtPrice = new JTextField();
txtPrice.setBounds(130, 135, 150, 40);
JTextField txtQty = new JTextField();
txtQty.setBounds(130, 185, 150, 40);
JTextField txtTotal = new JTextField();
txtTotal.setBounds(130, 235, 150, 40);
JLabel labelProduct = new JLabel();
labelProduct.setText("Item Group");
labelProduct.setBounds(10, 5, 100, 100);
// Item
JLabel labelItem = new JLabel();
labelItem.setText("Item");
labelItem.setBounds(10, 55, 100, 100);
// Price
JLabel labelPrice = new JLabel();
labelPrice.setText("Price");
labelPrice.setBounds(10, 105, 100, 100);
// Qty
JLabel labelQty = new JLabel();
labelQty.setText("Quantity");
labelQty.setBounds(10, 155, 100, 100);
// Total
JLabel labelTotal = new JLabel();
labelTotal.setText("Total");
labelTotal.setBounds(10, 205, 100, 100);
panel.setBackground(Color.blue);
panel.setBounds(0, 0, 300, 300); // x,y,width,height
panel.add(txtQty);
panel.add(txtTotal);
panel.add(txtPrice);
panel.add(comboItem);
panel.add(productCombo);
panel.add(labelProduct);
panel.add(labelItem);
panel.add(labelPrice);
panel.add(labelQty);
panel.add(labelTotal);
return panel;
}
private static JPanel createGreenPanel () {
JPanel panel = new JPanel(null);
panel.setBackground(Color.green);
panel.setBounds(0, 300, 300, 450);// x,y,width,length
JButton buttonBasket = new JButton();
buttonBasket.setBounds(0, 0, 300, 50);
buttonBasket.setText("Add to Basket");
buttonBasket.setFocusable(false);
buttonBasket.setBorder(BorderFactory.createEtchedBorder());
buttonBasket
.addActionListener(e -> System.out.println("Added Item to Basket: "
+ productCombo.getSelectedItem() + "\n" + comboItem.getSelectedItem()));
JButton buttonPay = new JButton();
buttonPay.setText("PAY");
buttonPay.setBounds(0, 50, 150, 100);
buttonPay.setFocusable(false);
buttonPay.setBorder(BorderFactory.createEtchedBorder());
buttonPay.addActionListener(e -> System.out.println("Payment Success"));
JButton buttonCancel = new JButton();
buttonCancel.setText("CANCEL");
buttonCancel.setBounds(0, 150, 150, 100);
buttonCancel.setFocusable(false);
buttonCancel.setBorder(BorderFactory.createEtchedBorder());
buttonCancel
.addActionListener(e -> System.out.println("Transaction Cancelled"));
JButton buttonDiscount = new JButton();
buttonDiscount.setText("Apply Discount?");
buttonDiscount.setBounds(150, 50, 150, 50);
buttonDiscount.setFocusable(false);
buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
buttonDiscount
.addActionListener(e -> System.out.println("20% Discount Applied"));
JButton buttonHelp = new JButton();
buttonHelp.setText("HELP");
buttonHelp.setBounds(150, 100, 150, 100);
buttonHelp.setFocusable(false);
buttonHelp.setBorder(BorderFactory.createEtchedBorder());
JButton buttonDelete = new JButton();
buttonDelete.setText("DELETE");
buttonDelete.setBounds(150, 200, 150, 50);
buttonDelete.setFocusable(false);
buttonDelete.setBorder(BorderFactory.createEtchedBorder());
buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));
panel.add(buttonBasket);
panel.add(buttonPay);
panel.add(buttonCancel);
panel.add(buttonDiscount);
panel.add(buttonHelp);
panel.add(buttonDelete);
return panel;
}
private static JPanel createRedPanel () {
JPanel panel = new JPanel(null);
panel.setBackground(Color.red);
panel.setBounds(300, 0, 600, 300); // x,y,width,length
return panel;
}
private static JPanel createYellowPanel () {
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
panel.setBounds(0, 300, 900, 450); // x,y,width,length
return panel;
}
private static class ComboSelectionListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
JComboBox<String> comboGroup = (JComboBox<String>) e.getSource();
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if (comboGroup.getSelectedItem().equals("Betta Fish")) {
comboItem.removeAllItems();
arrayItem.add("Plakat");
arrayItem.add("Halfmoon");
arrayItem.add("Crown Tail");
arrayItem.add("Double Tail");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Snails")) {
comboItem.removeAllItems();
arrayItem.add("Apple Horn");
arrayItem.add("RamsHorn");
arrayItem.add("Pond Snail");
arrayItem.add("Assassin Snail");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Supplies")) {
comboItem.removeAllItems();
arrayItem.add("Small Fine Net");
arrayItem.add("Large Fine Net");
arrayItem.add("Flaring Mirror");
arrayItem.add("Aquarium Hose");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Food")) {
comboItem.removeAllItems();
arrayItem.add("Tubifex");
arrayItem.add("Daphnia");
arrayItem.add("Optimum Pellets");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Select Item...")) {
comboItem.removeAllItems();
arrayItem.add("Select Item...");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
}
}
}
}
Improvements made (aside from fixing the main issue)
Created a Swing (main) class that is not a Swing component
Main class doesn't implement ActionListener
Used SwingUtilities to launch Swing Application
Created methods to encapsulate the details involving the creation of components
Minimized the scope of variables
This is my first post!
I'm trying to implement the combo box made in the TutCombo program into the ExamGradesGUI + ExamGrades one. As you can see in the TutCombo program, there is the 'String subjectUnitTxt'. Ideally, I would like this to replace the 'subjectUnitTxt' in the ExamGradesGUI program, but having the functionality of the combo box and being able to be saved to the file along with firstName, lastName and examMark. If someone could tell me how to do this, that would be great. Sorry if I have added too much code. Thanks
I got this to work by making some minor changes in your code (see attached code). Search for "unitCombo".
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ExamGradesGUI {
public static void main(String[] args) {
new ExamGradesGUI();
}
String[] firstName = new String[20];
String[] lastName = new String[20];
String[] subjectUnit = new String[20];
double[] examMark = new double[20];
private JLabel firstNameLbl, lastNameLbl, unitLbl, markLbl;
private JTextField firstNameTxt, lastNameTxt, subjectUnitTxt, examMarkTxt;
private JComboBox<String> unitCombo;
private JButton btnClear, btnSave, btnOpen, btnExit;
private JPanel panel;
private JFrame frame;
public ExamGradesGUI(){
buildFrame();
buildFields();
buildButtons();
frame.setVisible(true);
frame.add(panel);
}
public void buildFrame(){
frame = new JFrame("GradeEnter");
frame.setSize(650,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.white);
}
public void buildFields(){
// Labels, User Input + Location
firstNameTxt = new JTextField(10);
firstNameTxt.setBounds(180, 80, 150, 20);
panel.add(firstNameTxt);
String str = firstNameTxt.getText();
if(str.matches("[-a-zA-Z]*"))
{
}
else
{
JOptionPane.showMessageDialog(null, "Please enter amount donating");
}
lastNameTxt = new JTextField(10);
lastNameTxt.setBounds(180, 110, 150, 20);
panel.add(lastNameTxt);
subjectUnitTxt = new JTextField(10);
String[] courses = {"Computing","Forensic","Business"};
unitCombo = new JComboBox<String>(courses);
//subjectUnitTxt.setBounds(180, 140, 150, 20);
//panel.add(subjectUnitTxt);
unitCombo.setBounds(180, 140, 150, 20);
panel.add(unitCombo);
// IF HAVE TIME: Turn Combo Box into GUI - Refer to testgui.java
examMarkTxt = new JTextField(10);
examMarkTxt.setBounds(180, 170, 150, 20);
panel.add(examMarkTxt);
firstNameLbl = new JLabel("First Name:");
firstNameLbl.setBounds(70, 80, 100, 20);
panel.add (firstNameLbl);
lastNameLbl = new JLabel("Last Name:");
lastNameLbl.setBounds(70, 110, 100, 20);
panel.add (lastNameLbl);
unitLbl = new JLabel("Unit:");
unitLbl.setBounds(70, 140, 100, 20);
panel.add (unitLbl);
markLbl = new JLabel("Mark:");
markLbl.setBounds(70, 170, 100, 20);
panel.add (markLbl);
}
public void buildButtons() {
btnClear = new JButton ("Reset Fields");
btnClear.setBounds(55, 220, 110, 20);
btnClear.addActionListener(new ClearButtonListener());
panel.add (btnClear);
btnSave = new JButton ("Save");
btnSave.setBounds(155, 220, 70, 20);
btnSave.addActionListener(new SaveButton());
panel.add (btnSave);
btnOpen = new JButton ("Open 'GradeEnter.txt' ");
btnOpen.setBounds(90, 250, 200, 20);
btnOpen.addActionListener(new OpenButton());
panel.add (btnOpen);
btnExit = new JButton ("Exit");
btnExit.setBounds(255, 220, 70, 20);
btnExit.addActionListener(new ExitButton());
panel.add (btnExit);
}
public void setText() {
firstNameTxt.setText("");
lastNameTxt.setText("");
subjectUnitTxt.setText("");
examMarkTxt.setText("");
}
public void getText() {
int i = 0;
i++;
firstName[i] = firstNameTxt.getText();
lastName[i] = lastNameTxt.getText();
subjectUnit[i] = unitCombo.getItemAt(unitCombo.getSelectedIndex());
examMark[i] = Double.parseDouble(examMarkTxt.getText());
}
private class ClearButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
setText();
}
}
private class SaveButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
getText();
setText();
ExamGrades save = new ExamGrades();
save.fileOpen();
save.addRecords(firstName, lastName, subjectUnit, examMark);
JOptionPane.showMessageDialog(null, "Entry Saved!");
save.fileClose();
}
}
private class OpenButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
JOptionPane.showMessageDialog(null, "'GradeEnter.txt' opening in Java!");
Thread.sleep(2); // Adds a 2 second delay so user can read dialog message
Runtime.getRuntime().exec("eclipse GradeEnter.txt" );
} catch (Exception NoFileFound) {
System.out.println("Couldn't open or find the file.");
}
}
}
class ExitButton implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame,
"Are you sure you want to exit?",
"Exit?",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
}
}
}
}
This is another problem that has come up after having solved my earlier question here:
How to use a variable created in class1, in another class?
The answer to the question above allows me to use a variable created in class 3 to be printed by calling a method in class 4, from class 4.
However, when I try to print that variable as part of an action listener, it prints out 'null' instead of whatever the user inputs in the JTexfield create_u1 (in class 3).
Updated for sajjadG: please try it yourself
class 1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class class1 extends JFrame {
public static void main(String[] args) {
mainPage MP = new mainPage();
MP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MP.setLocationRelativeTo(null);
MP.setSize(300,200);
MP.setVisible(true);
}
}
class 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainPage extends JFrame {
create_account crAcc = new create_account();
change_username chU = new change_username();
change_password chPW = new change_password();
sign_in signIn = new sign_in();
private JButton create_account, change_username, change_password, signIn_button;
public mainPage(){
super("Password Programme");
setPreferredSize (new Dimension (400, 100));
setLayout (null);
create_account = new JButton("Create an Account");
add(create_account);
change_username = new JButton("Change Username");
add(change_username);
change_password = new JButton("Change Password");
add(change_password);
signIn_button = new JButton("Sign in and Access Files");
add(signIn_button);
create_account.setBounds (10, 20, 150, 20);
change_username.setBounds (10, 50, 150, 20);
change_password.setBounds (10, 80, 150, 20);
signIn_button.setBounds (10, 110, 200, 20);
HandlerClass handler = new HandlerClass();
create_account.addActionListener(handler);
change_username.addActionListener(handler);
change_password.addActionListener(handler);
signIn_button.addActionListener(handler);
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==create_account) {
crAcc.setLocationRelativeTo(null);
crAcc.setSize(300,200);
crAcc.setVisible(true);
}
if(event.getSource()==change_username) {
chU.setLocationRelativeTo(null);
chU.setSize(300,200);
chU.setVisible(true);
}
if(event.getSource()==change_password) {
chPW.setLocationRelativeTo(null);
chPW.setSize(300,200);
chPW.setVisible(true);
}
if(event.getSource()==signIn_button) {
signIn.setLocationRelativeTo(null);
signIn.setSize(300,200);
signIn.setVisible(true);
}
}
}
}
class 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class create_account extends JFrame{
private String u1, pw1;
private JLabel cU1, cpw1, statusBar;
public JTextField create_u1;
public JPasswordField create_pw1;
private JButton change;
public String userName3, passWord3;
public void checkUserName(String u, String pw) {
System.out.println(u); ///// this prints it out correctly
System.out.println(pw);
if (create_u1.getText()==u){
System.out.println("correct");
}else { /// it tests incorrect even though i inputted same thing
System.out.println("incorrect");
System.out.println(create_u1.getText());
System.out.println(userName3); /// prints out null }
}
public create_account() {
super("Create Account");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Create a username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 110, 250, 30);
cU1 = new JLabel("Username");
cpw1 = new JLabel("Password");
create_u1 = new JTextField(10);
create_pw1 = new JPasswordField(10);
cU1.setBounds(10, 10, 150, 30);
create_u1.setBounds(100, 10, 100, 30);
cpw1.setBounds(10, 50, 150, 30);
create_pw1.setBounds(100, 50, 100, 30);
add(create_u1);
add(cU1);
create_u1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Username saved. Now create a password");
statusBar.setText("Create a password");
add(cpw1);
add(create_pw1);
cpw1.repaint();
create_pw1.repaint();
create_pw1.requestFocus();
}
}
);
create_pw1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "Password saved");
statusBar.setText("Account created. Return to main programme");
statusBar.requestFocus();
}
}
);
}
}
class 4
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class change_username extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField username_input, username_change;
private JPasswordField password_input;
create_account objOfClass3 = new create_account();
public void checkUserName() {
objOfClass3.checkUserName(username_input.getText(), password_input.getText());
}
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
username_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your password");
add(pwT);
add(password_input);
pwT.repaint();
password_input.repaint();
password_input.requestFocus();
}
}
);
password_input.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Enter your new username");
add(uCh);
add(username_change);
uCh.repaint();
username_change.repaint();
username_change.requestFocus();
checkUserName();
}
}
);
username_change.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event){
statusBar.setText("Username Changed. Return to main programme");
username_change.requestFocus();
}
}
);
}
}
That is because you are not setting userName attribute first. you should set usernName first then try getUserName()
Try adding below line in your actionPerformed method before printing userName
setUserName(username_input.getText());
here is the corrected and tested code:
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class ChangeUsername extends JFrame {
private JLabel uT1, pwT, uCh, statusBar;
private JTextField usernameInput, usernameChange;
private JPasswordField passwordInput;
public String userName, passWord;
public String getUserName() {
return this.userName;
}
public void setUserName(String givenUserName) {
this.userName = givenUserName;
System.out.println(getUserName()); /////// this correctly prints the variable
}
public ChangeUsername() {
super("Change Username");
setPreferredSize(new Dimension(400, 85));
setLayout(null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
usernameInput = new JTextField(10);
pwT = new JLabel("Password");
passwordInput = new JPasswordField(10);
uCh = new JLabel("New Username");
usernameChange = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
usernameInput.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
passwordInput.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
usernameChange.setBounds(100, 90, 100, 30);
add(uT1);
add(usernameInput);
usernameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
statusBar.setText("Enter your password");
add(pwT);
add(passwordInput);
pwT.repaint();
passwordInput.repaint();
passwordInput.requestFocus();
setUserName(usernameInput.getText());// setting the username
// statusBar.setText(statusBar.getText() + " " + getUserName());
System.out.println(getUserName()); ////// this line does not
}
});
}
public static void main(String argv[]) {
new ChangeUsername().setVisible(true);
}
}
Also I should mention that you should start using Java naming convention and use meaningful names for your classes, attributes and methods.
classes start with Upercase letter
methods and attribute start with lower case
all of identifiers are camelCase so don't use _ between them. write getUserName instead of get_user_name
Read this link for more rules on Java naming convention.
And you need to learn more about OOP. So I suggest reading book Thinking in Java. TIJ third edition is free and good.
Here, you are not setting the value for the text field.
Do something like
username_input.setText(userName);
Put the above line in setUserName(){}
OR
public change_username() {
super("Change Username");
setPreferredSize (new Dimension (400, 85));
setLayout (null);
statusBar = new JLabel("Enter your username");
add(statusBar, BorderLayout.SOUTH);
statusBar.setBounds(20, 130, 250, 30);
uT1 = new JLabel("Username");
username_input = new JTextField(10);
pwT = new JLabel("Password");
password_input = new JPasswordField(10);
uCh = new JLabel("New Username");
username_change = new JTextField(10);
uT1.setBounds(10, 10, 150, 30);
username_input.setBounds(100, 10, 100, 30);
pwT.setBounds(10, 50, 150, 30);
password_input.setBounds(100, 50, 100, 30);
uCh.setBounds(10, 90, 150, 30);
username_change.setBounds(100, 90, 100, 30);
add(uT1);
add(username_input);
// SET THE TEXT HERE Before the Listener **************************
username_input.setText(getUserName());
// *****************************************************************
Then your code ahead.....
im doing a java vending machine os and I've just imported my original project into eclipse and added a guy page and since then its been throwing errors everywhere no mater what i do, can i get some help? the main error now is 'Syntax error on token(s), misplaced construct(s)' i do apologise in advance if the code is bad or inefficient of scraps laying around.
package JavaOS;
class OS {
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
public class OS extends Frame {
ImageIcon ironman3 = new ImageIcon ("H:\\School\\TECH\\Javaimages\\ironman3");
ImageIcon dredd = new ImageIcon ("H:\\School\\TECH\\Javaimages\\dredd");
ImageIcon indiana = new ImageIcon ("H:\\School\\TECH\\Javaimages\\indiana");
ImageIcon startrek = new ImageIcon ("H:\\School\\TECH\\Javaimages\\startrek");
public static String newline = System.getProperty("line.separator");
private static final long serialVersionUID = 1L;
private static Object activate;
String movie = null;
static boolean rightCreditCard = false;
public static void main(String[] args) throws IOException {
slot.d(activate);
beginProgram();
Welcome_GUI();
System.out.println("Part A - Intalising JFrame Windows");
checkCard();
if (rightCreditCard == false) {
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Your Credit Card is invalid!");
checkCard();
} else {
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Your Credit Card is valid!");
}
}
//Scanner scanner = new Scanner(System.in);
//System.out.println(scanner.nextLine());
//PrintWriter out = new PrintWriter(new FileWriter("H:\\School\\TECH\\JavaFileOutputs\\outputfile.txt"));
//out.print("Hello ");
//out.println("world");
//out.close();
//BufferedReader in = new BufferedReader(new FileReader("H:\\School\\TECH\\JavaFileOutputs\\outputfile.txt"));
//String text = in.readLine();
//in.close();
//System.out.println(text);
public static void beginProgram() {
Object[] options = { "OK", "Cancel" };
int JOP_Start = JOptionPane.showOptionDialog(null,
"Do you want to begin program?",
"Start?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (JOP_Start == JOptionPane.NO_OPTION)
{
System.out.println("Program Terminated");
System.exit(0);
}
}
public static void checkCard() {
String number = JOptionPane.showInputDialog("Enter your creditcard");;
int sum1=0,sum2=0;
//find the first Sum
for(int i=number.length()-1;i>=0;i=i-2)
{
sum1 = sum1 + Character . getNumericValue( number . charAt(i));
}
//find the second sum
for(int i=number.length()-2;i>=0;i=i-2)
{
int doublenumber = 2 * Character . getNumericValue( number.charAt(i));
String doublestring = Integer.toString(doublenumber);
//System.out.println(doublenumber+ " "+doublestring);
for(int j=0;j<doublestring.length();j++)
{
//System.out.println( Character . getNumericValue( doublestring.charAt(j)));
sum2 = sum2 + Character . getNumericValue( doublestring.charAt(j)) ;
}
}
//System.out.println(sum1+" "+sum2);
//Check the result
if((sum1+sum2)%10 == 0) {
System.out.println("Valid Credit Card!");
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Your Credit Card is valid!");
boolean rightCreditCard = true;
}
else
{
System.out.println("Invalid Credit Card!");
boolean rightCreditCard = false;
//Suggesting right check digit
System.out.println(sum1+sum2);
int totalsum = sum1+sum2;
int lastdigitoftotalsum = totalsum%10;
int numbertoaddtocheckdigit = 10 - lastdigitoftotalsum;
int userenteredcheckdigit = Character . getNumericValue( number . charAt(number.length()-1));
int progsuggestedcheckdigit = userenteredcheckdigit + numbertoaddtocheckdigit;
System.out.println(lastdigitoftotalsum + " " + numbertoaddtocheckdigit + " " + userenteredcheckdigit + " "+ progsuggestedcheckdigit);
System.out.println("The check digit should be " + progsuggestedcheckdigit);
////////////////////////////
//CREDIT CARD CHECK /\ END//
////////////////////////////
}
}
public static void rentMovie() {
Object[] options = { "OK", "Cancel" };
int accept = JOptionPane.showOptionDialog(null,
"Are you shoure you wish to rent this movie?",
"???",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[0]);
if (accept == JOptionPane.NO_OPTION)
{
System.out.println("You have not rented moive");
}
if (accept == JOptionPane.YES_OPTION)
{
System.out.println("You have rented moive");
slot.d(activate);
System.out.println("Slot dispenser activated");
}
}
public static void overDue() {
}
public static void delay(int i) {
try { //a wait or delay
Thread.sleep(i);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public static void Welcome_GUI() {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new JPanel());
frame.pack();
frame.setVisible (true);
class MyPanel extends JPanel {
private JLabel jcomp1;
private JLabel jcomp2;
private JButton jcomp3;
private JLabel jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JLabel jcomp8;
private JLabel jcomp9;
private JLabel jcomp10;
private JLabel jcomp11;
private JLabel jcomp12;
private JLabel jcomp13;
private JLabel jcomp14;
private JLabel jcomp15;
private JLabel jcomp16;
public MyPanel() {
//construct components
jcomp1 = new JLabel (" Welcome To Video Pro 2000-XD");
jcomp2 = new JLabel (" Iron Man 3");
jcomp3 = new JButton ("Rent");
jcomp4 = new JLabel ("Dredd 3D");
jcomp5 = new JButton ("Rent");
jcomp6 = new JButton ("Rent");
jcomp7 = new JButton ("Rent");
jcomp8 = new JLabel ("Indiana Jones");
jcomp9 = new JLabel ("Star Trek");
jcomp10 = new JLabel ("Into Darkness");
jcomp11 = new JLabel ("Kindom Of the ");
jcomp12 = new JLabel ("Crystal Skull");
jcomp13 = new JLabel ("PIC _STAR_TREK");
jcomp14 = new JLabel ("PIC_INDINA_JONES");
jcomp15 = new JLabel ("PIC_IRONMAN3");
jcomp16 = new JLabel ("PIC_DREDD_3D");
//adjust size and set layout
setPreferredSize (new Dimension (1241, 746));
setLayout (null);
//add components
add (jcomp1);
add (jcomp2);
add (jcomp3);
add (jcomp4);
add (jcomp5);
add (jcomp6);
add (jcomp7);
add (jcomp8);
add (jcomp9);
add (jcomp10);
add (jcomp11);
add (jcomp12);
add (jcomp13);
add (jcomp14);
add (jcomp15);
add (jcomp16);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (285, 35, 210, 35);
jcomp2.setBounds (280, 170, 80, 30);
jcomp3.setBounds (280, 205, 100, 25);
jcomp4.setBounds (400, 170, 70, 30);
jcomp5.setBounds (400, 205, 100, 25);
jcomp6.setBounds (280, 580, 100, 25);
jcomp7.setBounds (400, 565, 100, 25);
jcomp8.setBounds (280, 500, 100, 25);
jcomp9.setBounds (400, 510, 100, 25);
jcomp10.setBounds (400, 535, 100, 25);
jcomp11.setBounds (280, 525, 100, 25);
jcomp12.setBounds (280, 550, 100, 25);
jcomp13.setBounds (530, 400, 220, 326);
jcomp14.setBounds (40, 400, 220, 326);
jcomp15.setBounds (40, 40, 220, 326);
jcomp16.setBounds (530, 40, 220, 326);
}
}
}
}
You have
class OS {
and also
public class OS extends Frame {
The first one should be removed.
Other than that, the object 'slot' was not declared and initialized.
After removing
class OS {
and two lines of
slot.d(activate);
your file should compile and run.
I’ve started to create a GUI that consists of a few tabs. Right now I am focusing on two of them. The Pool tab and the Hot Tub tab. When I first started I got everything to work fine on the pool tab. So I figured since all of the label and text box placement would be the same for the Hot Tub tab I would just copy the coding over. Well, I did that and tried naming all the labels and text boxes the same just with the number 2 after them. It’s not working. Now the Hot Tub tab works, but the Pool tab doesn’t, plus the text boxes are gone. I’m also having alignment issues with the text boxes too, but I think that has to do with the naming of the labels and text boxes, I’m not sure.
MAIN CLASS:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.SimpleDateFormat;
public class test extends JFrame implements ActionListener{
private JTabbedPane jtabbedPane;
private JPanel General;
private JPanel Pools;
private JPanel HotTub;
JTextField lengthText, widthText, depthText, volumeText;
public test(){
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
createGeneral();
createPools();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("General", General);
jtabbedPane.addTab("Pool", Pools);
jtabbedPane.addTab("Hot Tub", HotTub);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
public void createGeneral(){
General = new JPanel();
General.setLayout( null );
JLabel dateLabel = new JLabel("Today's Date");
dateLabel.setBounds(10, 15, 150, 20);
General.add( dateLabel );
JFormattedTextField date = new JFormattedTextField(
java.util.Calendar.getInstance().getTime());
date.setEditable(false);
date.setBounds(90,15,150,20);
General.add(date);
JButton Close = new JButton("Close");
Close.setBounds(20,50,80,20);
Close.addActionListener(this);
Close.setBackground(Color.white);
General.add(Close);
}
/* CREATE POOL */
public void createPools(){
Pools = new JPanel();
Pools.setLayout( null );
JLabel lengthLabel = new JLabel("Length of pool (ft):");
lengthLabel.setBounds(10, 15, 260, 20);
Pools.add( lengthLabel );
lengthText = new JTextField();
lengthText.setBounds(260, 15, 150, 20);
Pools.add( lengthText );
JLabel widthLabel = new JLabel("Width of pool (ft):");
widthLabel.setBounds(10, 60, 260, 20);
Pools.add( widthLabel );
widthText = new JTextField();
widthText.setBounds(260, 60, 150, 20);
Pools.add( widthText );
JLabel depthLabel = new JLabel("Average Depth of pool (ft):");
depthLabel.setBounds( 10, 100, 260, 20 );
Pools.add( depthLabel );
depthText = new JTextField();
depthText.setBounds(260, 100, 150, 20);
Pools.add( depthText );
JLabel volumeLabel = new JLabel("The pool's volume is:(ft ^3");
volumeLabel.setBounds(10, 200, 260, 20);
Pools.add( volumeLabel );
volumeText = new JTextField();
volumeText.setBounds(260, 200, 150, 20);
volumeText.setEditable(false);
Pools.add(volumeText);
JButton calcVolume = new JButton("Calculate Volume");
calcVolume.setBounds(150,250,150,20);
calcVolume.addActionListener(this);
calcVolume.setBackground(Color.white);
Pools.add(calcVolume);
JButton Close = new JButton("Close");
Close.setBounds(350,250,80,20);
Close.addActionListener(this);
Close.setBackground(Color.white);
Pools.add(Close);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton)event.getSource();
String buttonLabel = button.getText();
if ("Close".equalsIgnoreCase(buttonLabel)){
Exit_pressed(); return;
}
if ("Calculate Volume".equalsIgnoreCase(buttonLabel)){
Calculate_Volume(); return;
}
if ("Calculate Volume".equalsIgnoreCase(buttonLabel)){
Calculate_Volume(); return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void Calculate_Volume(){
String lengthString, widthString, depthString;
int length=0;
int width=0;
int depth=0;
lengthString = lengthText.getText();
widthString = widthText.getText();
depthString = depthText.getText();
if (lengthString.length() < 1 || widthString.length() < 1 || depthString.length() < 1 ){
volumeText.setText("Enter All 3 Numbers"); return;
}
length = Integer.parseInt(lengthString);
width = Integer.parseInt(widthString);
depth = Integer.parseInt(depthString);
if (length != 0 || width != 0 || depth != 0 ){
volumeText.setText((length * width * depth) + "");
} else{
volumeText.setText("Enter All 3 Numbers"); return;
}
}
public static void main(String[] args){
JFrame frame = new test();
frame.setSize(500, 350);
frame.setVisible(true);
}
}
HOT TUB CLASS:
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public abstract class HotTub extends JFrame implements ActionListener{
private JTabbedPane jtabbedPane;
private Component HotTub;
{
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Hot Tub", HotTub);
JPanel HotTub;
JTextField lengthText, widthText, depthText, volumeText;
/* CREATE HOT TUB */
HotTub = new JPanel();
HotTub.setLayout( null );
JLabel lengthLabel = new JLabel("Length of hot tub (ft):");
lengthLabel.setBounds(10, 15, 260, 20);
HotTub.add( lengthLabel );
lengthText = new JTextField();
lengthText.setBounds(260, 15, 150, 20);
HotTub.add( lengthText );
JLabel widthLabel = new JLabel("Width of hot tub (ft):");
widthLabel.setBounds(10, 60, 260, 20);
HotTub.add( widthLabel );
widthText = new JTextField();
widthText.setBounds(260, 60, 150, 20);
HotTub.add( widthText );
JLabel depthLabel = new JLabel("Average Depth of hot tub (ft):");
depthLabel.setBounds( 10, 100, 260, 20 );
HotTub.add( depthLabel );
depthText = new JTextField();
depthText.setBounds(260, 100, 150, 20);
HotTub.add( depthText );
JLabel volumeLabel = new JLabel("The hot tub's volume is:(ft ^3");
volumeLabel.setBounds(10, 200, 260, 20);
HotTub.add( volumeLabel );
volumeText = new JTextField();
volumeText.setBounds(260, 200, 150, 20);
volumeText.setEditable(false);
HotTub.add(volumeText);
JButton calcVolume = new JButton("Calculate Volume");
calcVolume.setBounds(150,250,150,20);
calcVolume.addActionListener((ActionListener) this);
calcVolume.setBackground(Color.white);
HotTub.add(calcVolume);
JButton Close = new JButton("Close");
Close.setBounds(350,250,80,20);
Close.addActionListener((ActionListener) this);
Close.setBackground(Color.white);
HotTub.add(Close);
}
}
Right now both the Pool tab and the Hot Tub tab are the same. No matter what tab I'm on, the same results show up on each tab. Is it a naming issue?
This should not be all in one class.
If your pool and hot tub tabs are so similar that you are copying code. Instead create a new class that extends JPanel and sets up the panel based on some parameters. (Or even just a factory method.) Then add two of these classes to the JTabbedPane, one with parameters for a HotTub and the other for a Pool.
Use LayoutManagers. It will be worth the learning curve and will greatly improve your GUI.
in createHotTub() method:
replace HotTub.add( lengthText ); with HotTub.add( lengthText2 );
replace HotTub.add( widthText ); with HotTub.add( widthText2 );
replace HotTub.add( depthText ); with HotTub.add( depthText2 );
replace HotTub.add( volumeText ); with HotTub.add( volumeText2 );