Java Syntax error on token(s), misplaced construct(s) - java

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.

Related

Overlaping when using .setText() for some reason

I have a Jlabel called status that is empty. When I do status.setText() the first time it works normally but when I change it again it overlaps the first change instead of replacing it like it should. What is going on?
package panda.org;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Math;
public class NumberGame implements ActionListener{
JFrame frame;
JLabel rules;
JLabel rulesText;
JLabel rulesText2;
JLabel lets;
JButton play;
JButton exit;
JPanel panel;
Font myFont = new Font("Serif Plain", Font.BOLD, 15);
NumberGame() {
frame = new JFrame("NumberGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 500);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.setResizable(true);
Image icon = Toolkit.getDefaultToolkit().getImage("C:\\Users\\Gaming MSI\\Pictures\\Saved Pictures\\download (1).png");
frame.setIconImage(icon);
rules = new JLabel("Rules: ");
rules.setFont(myFont);
rules.setBounds(50, 100, 100, 75);
rulesText = new JLabel("We will pick a random number in the range of 1 -> 50.");
rulesText.setBounds(100, 100, 315, 75);
rulesText2 = new JLabel("Your job is to guess that number!");
rulesText2.setBounds(100, 120, 315, 75);
play = new JButton("Play");
play.setBounds(150, 300, 100, 75);
play.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int failedAttempts = 0;
JLabel label = new JLabel("Guess the number from 1 till 50");
label.setFont(myFont);
label.setBounds(150, 75, 315, 75);
JLabel hints = new JLabel("");
JTextField text = new JTextField();
text.setBounds(250, 150, 100, 25);
JButton check = new JButton("Check");
check.setBounds(150, 150, 75, 25);
double randomDouble = Math.random();
randomDouble = randomDouble * 50 + 1;
int randomInt = (int) randomDouble;
double finalRandomDouble = randomDouble;
check.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(randomInt);
String nb = text.getText();
int change = Integer.parseInt(nb);
JLabel status = new JLabel("");
status.setBounds(150, 160, 1000, 100);
frame.add(status);
if(randomInt == change) {
status.setText("You chose the correct number!");
status.setForeground(Color.green);
}
if(randomInt != change) {
status.setText("Wrong choice! Try again.");
status.setForeground(Color.red);
}
}
});
rules.setText("");
rulesText.setText("");
rulesText2.setText("");
frame.add(hints);
frame.add(label);
frame.add(check);
frame.add(text);
}
});
exit = new JButton("Exit");
exit.setBounds(350, 300, 100, 75);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(frame,"Are you sure want to exit?", "Exit",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(result == JOptionPane.YES_OPTION){
System.exit(0);
}else if (result == JOptionPane.NO_OPTION){
}else {
}
}
});
frame.add(play);
frame.add(exit);
frame.add(rules);
frame.add(rulesText);
frame.add(rulesText2);
frame.setVisible(true);
}
public static void main(String[] args) {
NumberGame number = new NumberGame();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Someone asked for more code so this is all of my code! I hope this helps :D
The problem is in these lines
if(randomInt == change) {
status.setText("You chose the correct number!");
status.setForeground(Color.green);
}
if(randomInt != change) {
status.setText("Wrong choice! Try again.");
status.setForeground(Color.red);
}
}
This is how the result appears:
There are some improvements to do in your code:
You're using null-layout and setBounds(...) which is not advised it will give you more headaches than solutions, it may seem like the best / easiest way to build complex GUIs but it's not, here's an example of why. Swing has to deal with multiple OS, PLAFs, screen sizes and resolutions, let the layout managers do that work for you, all you have to do is combine them.
Every time you call check.addActionListener(new ActionListener() {, you're creating a new instance of your JLabel named status, and because you're using null-layout and you're placing it in the same position, they're overlapping.
Follow the first advice given in this answer, rebuild the whole thing with layout managers, move the status label as a class member and you shouldn't have any problems.
try this:
if(randomInt == change) {
status.setText("You chose the correct number!");
status.setForeground(Color.green);
}else{
status.setText("Wrong choice! Try again.");
status.setForeground(Color.red);
}

How to display an image that a user has selected on the JFrame using JavaSwing

I am trying to add a "profile picture" to a user's profile page. Basically, I have it to where they can select a file from their computer and upload it to the application, and it will display their profile picture. However it is not working, I think that it currently cannot display it, but generates it incorrectly.
Here is my code
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFileChooser;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage()
{
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize()
{
//Setting location and Size of each components using setBounds() method.
name.setBounds(50,100,100,30);
age.setBounds(50,170,100,30);
phoneNum.setBounds(50,240,100,30);
interest.setBounds(50,310,100,30);
aboutMe.setBounds(50,380,100,30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350,310,150,30);
uploadPic.setBounds(350,380,150,30);
nameField.setBounds(150,100,150,30);
ageField.setBounds(150,170,150,30);
phoneNumberField.setBounds(150,240,150,30);
interestField.setBounds(150,310,150,30);
aboutMeField.setBounds(150,380,150,30);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
String name = nameField.getText();
String age = ageField.getText();
String phoneNum = phoneNumberField.getText();
String interest = interestField.getText();
String aboutMe = aboutMeField.getText();
try {
Socket socket = new Socket("localhost", 4242);
ObjectInputStream reader = new ObjectInputStream(socket.getInputStream());
//creating user object to send to the server
User user = new User();
} catch (IOException b) {
b.printStackTrace();
}
JOptionPane.showMessageDialog(this, "Profile Creation Successful");
} else if (e.getSource() == deleteProfile) {
String name = null;
String age = null;
String phoneNum = null;
String interest = null;
String aboutMe = null;
JOptionPane.showMessageDialog(this, "Profile Deletion Successful");
} else if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
//ImageDrawer drawer = new ImageDrawer();
Toolkit toolkit = Toolkit.getDefaultToolkit();
String stringFile = file.toString();
Image image = toolkit.getImage(stringFile);
Path path = Paths.get(stringFile);
Path imagePath = path.toAbsolutePath();
String newStr = imagePath.toString();
BufferedImage picture = ImageIO.read(new File(newStr));
JLabel picLabel = new JLabel(new ImageIcon(picture));
picLabel.setBounds(350, 170, 150, 30);
add(picLabel);
} catch (IOException g) {
JOptionPane.showMessageDialog(null,"ERROR");
}
}
}
}
}
Well it 'works' now. This code can open and display an image the user selects. The layout is still broken(1), as hinted by Upload Profile Pict.... That guessed width and cut off text on this computer is one of the many reasons to use layout managers, padding & borders to position elements in a GUI.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
final class createProfilePage extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JLabel picLabel = new JLabel();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
createProfilePage() {
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setTitle("Welcome");
setSize(600, 500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
//Setting location and Size of each components using setBounds() method.
name.setBounds(50, 100, 100, 30);
age.setBounds(50, 170, 100, 30);
phoneNum.setBounds(50, 240, 100, 30);
interest.setBounds(50, 310, 100, 30);
aboutMe.setBounds(50, 380, 100, 30);
submit.setBounds(350, 240, 150, 30);
deleteProfile.setBounds(350, 310, 150, 30);
uploadPic.setBounds(350, 380, 150, 30);
nameField.setBounds(150, 100, 150, 30);
ageField.setBounds(150, 170, 150, 30);
phoneNumberField.setBounds(150, 240, 150, 30);
interestField.setBounds(150, 310, 150, 30);
aboutMeField.setBounds(150, 380, 150, 30);
picLabel.setBounds(350, 50, 150, 150);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(picLabel);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
BufferedImage picture = ImageIO.read(file);
picLabel.setIcon(new ImageIcon(picture));
add(picLabel);
} catch (IOException ioe) {
ioe.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
}
}
}
public static void main(String[] args) {
Runnable r = () -> {
new createProfilePage().setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
Personally, I'd take a different approach to the look of this. A toolbar at top for all the buttons. the two columns of labels and fields on the left as seen there, but with the label text aligned right, and the fields different sizes as per need. Maybe even make the "About me:" a text area, rather than a field. Then, to the right of the label/field combos, the rest of the width
and height devoted to the picture label. It would be shown in a
scroll pane (unless the pictures are all the same size).

Swing designer & Layout & textField Restriction

I tried to implement a simple user interface of my programm.It is the first time that I used swing designer plugin.
1st problem :User enters start and end date and program automatically calculates the duration. But i dont know how i can write the restriction of the yyyy/MM/dd. I mean that user begins to enter year then skip the another block without make anything.
Here is my code:
public class MyFrame extends JFrame {
public MyFrame() {
}
private static JLabel labelBegin;
private static JLabel labelEnd;
private static JLabel labelDuration;
private static JLabel labelA;
private static JLabel labelB;
private static JLabel labelC;
private static JLabel labelD;
private static JLabel labelTotal;
private static JLabel labelSafety;
private static JLabel labelSpeed;
private static JLabel labelEfficiency;
private static JLabel message;
private static JTextField textFieldBegin;
private static JTextField EndingField;
private static JTextField DurationField;
private static JTextField AField;
private static JTextField BField;
private static JTextField CField;
private static JTextField DField;
private static JTextField TotalField;
private static JTextField SafetyField;
private static JTextField SpeedField;
private static JTextField EfficiencyField;
private static JButton clear;
private static JButton buttonNext;
private static JButton buttonBack;
private static JRadioButton PlacementResult;
private static JRadioButton Collision;
private static JPanel panelOptions;
private static JPanel panelLogin;
private static JFrame frame;
private static JButton Mybutton;
private static JPanel panelCons;
private static void mydesign() {
frame = new JFrame("Placement Tool V1.0");
frame.getContentPane().setLayout(new GridLayout(1, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelLogin = new JPanel();
panelLogin.setLayout(null);
message = new JLabel ("In order to begin your testing, please enter the data");
labelBegin = new JLabel("Enter Begin Date :");
textFieldBegin = new JTextField(10);
labelEnd = new JLabel("Test Duration :");
EndingField = new JTextField(10);
labelDuration = new JLabel ("Enter End Date :");
DurationField = new JTextField(10);
labelA = new JLabel ("Enter Group A :");
AField = new JTextField (10);
labelB = new JLabel ("Enter Group B:");
BField = new JTextField (10);
labelC = new JLabel ("Enter Group C:");
CField = new JTextField (10);
labelD = new JLabel ("Enter Group D:");
DField = new JTextField (10);
labelTotal = new JLabel ("Total Test Devices :");
TotalField = new JTextField (10);
labelSafety = new JLabel ("Enter Safety (%) : ");
SafetyField = new JTextField (10);
labelSpeed = new JLabel ("Enter Speed (kpbs)");
SpeedField = new JTextField (10);
labelEfficiency = new JLabel ("Enter Efficiency (%)");
EfficiencyField = new JTextField (10);
buttonNext = new JButton("Next");
clear = new JButton("Cancel");
panelLogin.add(buttonNext);
panelLogin.add(clear);
panelLogin.add(labelBegin);
panelLogin.add(message);
panelLogin.add(textFieldBegin);
panelLogin.add(labelEnd);
panelLogin.add(EndingField);
panelLogin.add(labelDuration);
panelLogin.add(DurationField);
panelLogin.add (labelA);
panelLogin.add(labelB);
panelLogin.add(labelC);
panelLogin.add(labelD);
panelLogin.add(labelTotal);
panelLogin.add(AField);
panelLogin.add(BField);
panelLogin.add(CField);
panelLogin.add(DField);
panelLogin.add(TotalField);
panelLogin.add(labelSafety);
panelLogin.add(labelSpeed);
panelLogin.add(labelEfficiency);
panelLogin.add(SpeedField);
panelLogin.add(EfficiencyField);
panelLogin.add(SafetyField);
message.setBounds(50, 70, 500, 20);
textFieldBegin.setBounds(200, 120, 100, 20);
labelBegin.setBounds(50, 120, 120, 20);
EndingField.setBounds(200, 140, 100, 20);
labelEnd.setBounds(50, 160, 120, 20);
DurationField.setBounds(200, 160, 100, 20);
labelDuration.setBounds(50, 140, 120, 20);
AField.setBounds(200, 180, 100, 20);
labelA.setBounds(50, 180, 120, 20);
BField.setBounds(200, 200, 100, 20);
labelB.setBounds(50, 200, 120, 20);
CField.setBounds(200, 220, 100, 20);
labelC.setBounds(50, 220, 120, 20);
DField.setBounds(200, 240, 100, 20);
labelD.setBounds(50, 240, 120, 20);
TotalField.setBounds(200, 260, 100, 20);
labelTotal.setBounds(50, 260, 120, 20);
SafetyField.setBounds(200, 280, 100, 20);
labelSafety.setBounds(50, 280, 120, 20);
SpeedField.setBounds(200, 300, 100, 20);
labelSpeed.setBounds(50, 300, 120, 20);
EfficiencyField.setBounds(200, 320, 100, 20);
labelEfficiency.setBounds(50, 320, 120, 20);
buttonNext.setBounds(70, 350, 100, 20);
clear.setBounds(200, 350, 100, 20);
buttonNext.addActionListener(actionEvent);
clear.addActionListener(actionEvent);
frame.getContentPane().add(panelLogin);
//frame ends.
//Options frame starts.
panelOptions = new JPanel();
panelOptions.setLayout(null);
PlacementResult = new JRadioButton ("Show the placement result.");
Collision = new JRadioButton ("Show the collision (%)");
buttonBack = new JButton("Back");
buttonNext = new JButton("Next");
panelOptions.add(buttonBack);
panelOptions.add(buttonNext);
panelOptions.add(Collision);
panelOptions.add(PlacementResult);
Collision.setBounds(150, 25, 200, 25);
PlacementResult.setBounds(150, 50, 200, 25);
buttonBack.setBounds(150, 100, 200, 25);
buttonNext.setBounds(150, 150, 200, 25);
buttonBack.addActionListener(actionEvent);
buttonNext.addActionListener(actionEvent);
//Options Frame ends.
panelCons = new JPanel();
panelCons.setLayout(null);
Mybutton = new JButton("Button");
panelCons.add(Mybutton);
Mybutton.setBounds(180, 180, 150, 25);
Mybutton.addActionListener(actionEvent);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
mydesign();
}
});
}
private static ActionListener actionEvent = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(frame == null)
frame = new JFrame();
else {
//remove the previous JFrame
frame.setVisible(false);
frame.dispose();
//create a new one
frame = new JFrame();
}
String action = e.getActionCommand();
if ("Login".equals(action)) {
System.out.println("Login action" + e.getActionCommand());
if ("".equals(textFieldBegin.getText()) || "".equals(EndingField.getText()) ||"".equals(DurationField.getText()) ) {
JOptionPane.showMessageDialog(null,
"Enter Both begin test date and end test date");
} else if ("admin".equals(textFieldBegin.getText())&&"admin".equals(AField.getText())&&
"admin".equals(BField.getText())&&
"admin".equals(CField.getText())&&"admin".equals(DField.getText())&& "admin".equals(TotalField.getText())&&
"admin".equals(EfficiencyField.getText()) && "admin".equals(SafetyField.getText()) &&
"admin".equals(SpeedField.getText()) && "admin".equals(EndingField.getText()))
{
System.out.println("Test begin date" + textFieldBegin.getText() + " Test end date" + EndingField.getText()
//+" Test duration" + (EndingField.getText() - textFieldBegin.getText())
+" Group A devices" + AField.getText() +" Group B devices"+ BField.getText()
+ " Group C devices "+ CField.getText()
+ "Group D devices"+ DField.getText()
+ "Total devices" + (AField.getText() + BField.getText() + CField.getText() + DField.getText())
+"Max speed (kbps)" + SpeedField.getText()
+ "Efficiency (%)" + EfficiencyField.getText() + "Safety (%)" + SafetyField.getText()
);
frame.remove(panelLogin);
frame.getContentPane().add(panelOptions);
frame.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,
"Date format that you entered is not appropriate! Hint: YYYY/MM/DD");
}
} else if ("Cancel".equals(action)) {
System.out.println(e.getActionCommand());
System.exit(0);
}
{
frame.remove(panelOptions);
frame.getContentPane().add(panelCons);
frame.setVisible(true);
}
}
;
};
}
2nd problem is i want to make my program user friendly so i want to make a group every component that are similar each other.Here is output:
Advance thanks for all helps
SOLUTION :
Use TF(For 4 digits) + LB(For Slash) + TF(For 2 digits) + LB(For Slash) + TF(For 2 digits) to achive that format in date [TF : TextField and LB : Label] OR you can simply validate on Next button click whether date format match the specific format or not or even precisely date is valid or not.
Use JPanel and set border of it for grouping. (Hint : Use BorderFactory)
I didn't get you in this specific problem.SO can't say anything.

Trying to implement JComboBox into program - Java

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

java.lang.NoClassDefFoundError:

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

Categories

Resources