I am using windows 8, 64 bit.
I am learning GUI in Java. Generally I use eclipse IDE. I have also installed Net-beans.
I am trying to do a simple GUI program which will add two number and show their result. But the problem is that when I am running the program from IDE it is looking like this. . But when I am running this same class file from command line it is showing correctly. I have test the same code in both eclipse and Net-beans. But the result is same.
Source code for first picture.
import javax.swing.JOptionPane; // program uses JOptionPane
public class Addition
{
public static void main( String[] args )
{
// obtain user input from JOptionPane input dialogs
String firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert String inputs to int values for use in a calculation
int number1 = Integer.parseInt( firstNumber );
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum Integers", JOptionPane.PLAIN_MESSAGE );
} // end method main
} // end class Addition
then I have made another simple program by window-builder which will perform the four arithmetic operattion between two number. But the result is same for this case. Another picture has added named picture two.
source code for second picture.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Button;
import java.awt.Label;
import javax.swing.JMenuBar;
import javax.swing.JToggleButton;
import javax.swing.JCheckBox;
import java.awt.Color;
import java.awt.SystemColor;
import javax.swing.SwingConstants;
import javax.swing.JTable;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class test extends JFrame {
private JPanel contentPane;
private JTextField one;
private JTextField two;
private JTextField ans;
private JLabel lblNumone;
private JLabel lblNumtwo;
private JButton btnDiv;
private JButton btnMult;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
test frame = new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public test()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 294, 322);
contentPane = new JPanel();
contentPane.setBackground(Color.GREEN);
contentPane.setForeground(SystemColor.desktop);
contentPane.setBorder(new EmptyBorder(19, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
one = new JTextField();
one.setBounds(125, 5, 89, 25);
contentPane.add(one);
one.setColumns(10);
two = new JTextField();
two.setBounds(125, 50, 89, 25);
contentPane.add(two);
two.setColumns(20);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 + num2;
ans.setText(Integer.toString(answer));
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnAdd.setBounds(125, 86, 89, 23);
contentPane.add(btnAdd);
JButton btnMinus = new JButton("Minus");
btnMinus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 - num2;
ans.setText(Integer.toString(answer));
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnMinus.setBounds(125, 119, 89, 23);
contentPane.add(btnMinus);
ans = new JTextField();
ans.setBounds(125, 221, 89, 25);
contentPane.add(ans);
ans.setColumns(10);
JLabel lblAnswer = new JLabel("Answer");
lblAnswer.setBounds(58, 230, 46, 14);
contentPane.add(lblAnswer);
lblNumone = new JLabel("NumberOne ");
lblNumone.setBounds(10, 10, 78, 14);
contentPane.add(lblNumone);
lblNumtwo = new JLabel("NumberTwo");
lblNumtwo.setBounds(10, 55, 78, 14);
contentPane.add(lblNumtwo);
btnDiv = new JButton("Div");
btnDiv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 / num2;
ans.setText(Integer.toString(answer));
}catch (Exception eDiv)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnDiv.setBounds(125, 153, 89, 23);
contentPane.add(btnDiv);
btnMult = new JButton("Mult");
btnMult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,answer;
try{
num1=Integer.parseInt(one.getText());
num2=Integer.parseInt(two.getText());
answer =num1 * num2;
ans.setText(Integer.toString(answer));
}catch (Exception eMult)
{
JOptionPane.showMessageDialog(null, "Please Enter Correct Number:");
}
}
});
btnMult.setBounds(125, 187, 89, 23);
contentPane.add(btnMult);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(293, 28, 200, 50);
contentPane.add(menuBar);
}
}
it is not appearing correctly in IDE, but when the class file is running in command line, it is appearing correctly.
I have updated my JDK.
what may the cause and solution?
Related
I'm currently making a user-input based program on Java Eclipse that is supposed perform calculations on data from a local csv file the user selects. The GUI code below is the source code that I have been using to make the GUI for the program. While I have managed to create the GUI, I am having trouble with "combining" the code listed under "CSVReader," which is a class I created, with the code for the GUI so that the user can select the CSV file. The user is supposed to select this CSV file by typing its path name into the text field box on the GUI.
Any help would be appreciated
GUI CODE
//GUI CODE
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JTextField;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField txtCountryChosen;
/**
* #wbp.nonvisual location=71,14
*/
private final JTextField Program = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Program.setText("Statistics Manager");
Program.setColumns(10);
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Submit file path");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String textFieldValue = textField.getText();
}
});
btnNewButton.setBounds(145, 48, 150, 25);
frame.getContentPane().add(btnNewButton);
textField = new JTextField();
textField.setBounds(116, 13, 200, 22);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Mean GDP");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_1.setBounds(0, 154, 97, 25);
frame.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Mean GDP_per_capita");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNewButton_2.setBounds(250, 154, 170, 25);
frame.getContentPane().add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("Mean pop");
btnNewButton_3.setBounds(109, 154, 120, 25);
frame.getContentPane().add(btnNewButton_3);
txtCountryChosen = new JTextField();
txtCountryChosen.setBounds(42, 104, 116, 22);
frame.getContentPane().add(txtCountryChosen);
txtCountryChosen.setColumns(10);
JButton btnNewButton_4 = new JButton("Select country");
btnNewButton_4.setBounds(270, 103, 150, 25);
frame.getContentPane().add(btnNewButton_4);
JButton btnNewButton_5 = new JButton("Print Results in Txt File");
btnNewButton_5.setBounds(131, 201, 200, 20);
frame.getContentPane().add(btnNewButton_5);
}
}
CSVReader
//CSVREADER
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class CSVReader {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter file path name");
String file_path_name = scan.nextLine();
System.out.println(file_path_name);
String path= file_path_name;
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while((line = br.readLine()) !=null){
String[] values = line.split(",");
System.out.println("Country: " + values[0] + ", Year: " + values[2] + ", GDP: " + values[6] + ", GDP_per_capita: " + values[12] + ", Population: " + values[10]);
/*PrintStream myconsole= new PrintStream(new File("E://java.txt"));
System.setOut(myconsole);
myconsole.print(path);*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have tried to code a simple calculator using GUI in java but got stuck with this code and repeatedly getting a message of 'ENTER VALID NUMBERS' .I'm open to suggestions. Suggest the possible corrections in my code.I think I have wrongly used the try and check the exception feature of the java.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtfield1 = new JTextField();
txtfield1.setHorizontalAlignment(SwingConstants.LEFT);
txtfield1.setText("ENTER NUMBER 1 : ");
txtfield1.setBounds(28, 11, 178, 68);
frame.getContentPane().add(txtfield1);
txtfield1.setColumns(10);
txtfield2 = new JTextField();
txtfield2.setHorizontalAlignment(SwingConstants.LEFT);
txtfield2.setText("ENTER NUMBER 2 : ");
txtfield2.setBounds(228, 11, 175, 68);
frame.getContentPane().add(txtfield2);
txtfield2.setColumns(10);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1+num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1,num2,sum;
try
{
num1=Integer.parseInt(txtfield1.getText());
num2=Integer.parseInt(txtfield2.getText());
sum=num1-num2;
textfieldans.setText(Integer.toString(sum));
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, "ENTER VALID NUMBER");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setBounds(251, 196, 109, 48);
frame.getContentPane().add(textfieldans);
textfieldans.setColumns(10);
}
}
You are obviously getting an exception because you are appending or adding the entered number to the text already contained within one of the JTextFields. This would generate a NumberFormatException when trying to parse the string contained within JTextField to a Integer value with the Integer.parseInt() method. If anything other than numerical digits are supplied then this exception would be thrown. You're just making the exception display a Message Box indicating to the User to "ENTER VALID NUMBER".
If you want to keep the text within you text field components then apply a Focus Listener to highlight the text currently in the component so that it gets overwritten when the User enters a number. Generally this pre-text is in a lighter gray color. Here is an example:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class FIRSTCALC {
private JFrame frame;
private JTextField txtfield1;
private JTextField txtfield2;
private JTextField textfieldans;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FIRSTCALC window = new FIRSTCALC();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FIRSTCALC() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setAlwaysOnTop(true);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtfield1 = new JTextField("Enter First Number");
txtfield1.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield1
txtfield1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield1.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield1.setForeground(Color.black);
}
});
txtfield1.setHorizontalAlignment(SwingConstants.CENTER);
txtfield1.setBounds(28, 11, 178, 68);
txtfield1.setColumns(10);
frame.getContentPane().add(txtfield1);
txtfield2 = new JTextField("Enter Second Number");
txtfield2.setForeground(Color.lightGray);
// Add a Focus Listener to txtfield2
txtfield2.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
txtfield2.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
txtfield2.setForeground(Color.black);
}
});
txtfield2.setHorizontalAlignment(SwingConstants.CENTER);
txtfield2.setBounds(228, 11, 175, 68);
txtfield2.setColumns(10);
frame.getContentPane().add(txtfield2);
JButton btnNewButton = new JButton("ADD");
btnNewButton.setToolTipText("TO ADD NUMBERS");
btnNewButton.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 + num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> + <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton.setBounds(61, 121, 120, 42);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("SUBTRACT");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int num1, num2, sum;
try {
num1 = Integer.parseInt(txtfield1.getText());
num2 = Integer.parseInt(txtfield2.getText());
sum = num1 - num2;
textfieldans.setText(Integer.toString(sum));
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "<html><center>The following formula:<br><br>"
+ "<font size='4' color=red>" + txtfield1.getText() +
"</font> - <font size='4' color=red>"+ txtfield2.getText() +
"</font><br><br>contains invalid digits!</center></html>");
}
}
});
btnNewButton_1.setToolTipText("TO SUBTRACT NUMBERS");
btnNewButton_1.setFont(new Font("Sitka Text", Font.BOLD, 16));
btnNewButton_1.setBounds(251, 121, 128, 42);
frame.getContentPane().add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("THE ANSWER IS :");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Sitka Text", Font.BOLD, 18));
lblNewLabel.setBounds(28, 192, 193, 58);
frame.getContentPane().add(lblNewLabel);
textfieldans = new JTextField();
textfieldans.setHorizontalAlignment(SwingConstants.CENTER);
textfieldans.setBounds(251, 196, 109, 48);
textfieldans.setColumns(10);
frame.getContentPane().add(textfieldans);
frame.setLocationRelativeTo(null);
}
}
I need to make my login button go to the next Class(page) of the system
atm i have add a few buttons i saw in videos and read about and really will like to make this work.
so I played around with a few commands but dont think i got it right.
Can you maybe tell me what I am doing extremely wrong?
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Scanner;
public class system {
protected static final int Admin = 0;
private JFrame frame;
private JTextField Usernameinput;
private JTextField Passwordinput;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
Scanner input = new Scanner(System.in);
public void run() {
try {
system window = new system();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public system() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 534, 365);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username;
String password;
System.out.println("Log in:");
System.out.println("username: ");
Scanner input = null;
username = input.next();
System.out.println("password: ");
password = input.next();
//users check = new users(username, password);
if (Usernameinput.equals(Admin) && Passwordinput.equals(Admin)) {
System.out.println("Welcome");
};
}
});
btnLogin.setBounds(29, 242, 89, 23);
frame.getContentPane().add(btnLogin);
JButton btnReset = new JButton("Reset");
btnReset.setBounds(144, 242, 89, 23);
frame.getContentPane().add(btnReset);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setBounds(397, 282, 89, 23);
frame.getContentPane().add(btnExit);
Usernameinput = new JTextField();
Usernameinput.setBounds(144, 74, 209, 20);
frame.getContentPane().add(Usernameinput);
Usernameinput.setColumns(10);
Passwordinput = new JTextField();
Passwordinput.setColumns(10);
Passwordinput.setBounds(144, 106, 209, 20);
frame.getContentPane().add(Passwordinput);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(73, 77, 55, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(73, 108, 55, 17);
frame.getContentPane().add(lblPassword);
JSeparator separator = new JSeparator();
separator.setBounds(10, 211, 498, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(10, 57, 498, 2);
frame.getContentPane().add(separator_1);
JLabel lblNewLabel = new JLabel("Welcome to The System v 0.1");
lblNewLabel.setBounds(182, 5, 151, 41);
frame.getContentPane().add(lblNewLabel);
}
}
There's a mistake in your btnLogin.addActionListener. You don't need the input here. Usually we need Scanner to read the input from the console.
But now as we have a UI we can get the user input from the specific JTextFields. In your case username from Usernameinput and password from Passwordinput.
username = Usernameinput.getText();
password = Passwordinput.getText();
Next the if statement in your btnLogin.addActionListener must check the text inside the JTextFields. As we have already obtained those and kept in the variables username and password you can use those.
And you can't use String.equals method with an int. username.equals(Admin) will always return false since the variable Admin is an int. So change,
if (username.equals("username") && password.equals("password")) {
System.out.println("Welcome");
};
Finally you can remove unused import statements (optional).
import javax.swing.JToolBar;
import javax.swing.JTable;
Hi Thank you for the help
But like now if i press Login it goes to a consol page where is says welcome but will like it to go to the next class??
never mind found out how to add it
now i just need to make use of the second frame
I am creating a small program in Java eclipse windowbuilder. The user inputs the left hand side (LHS) and right hand side (RHS) of the inequality statement such that LHS < (m/n) < RHS. The program will output the lowest integer values m and n which satisfy the condition. I have the logic/code required to do this, but I am unsure how to get the user values of LHS and RHS in windowbuilder. The text field to the left is called lhs and the text field on the right is called rhs, which you can see in the image below. How can I get the user's inputs for these (as double data type)? When the user enters these two values, I will put the code logic under actionPerformed. Thanks!
JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
package ntheory;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Ntheory {
private JFrame frame;
private JTextField lhs;
private JTextField rhs;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Ntheory window = new Ntheory();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Ntheory() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
lhs = new JTextField();
lhs.setBounds(6, 46, 68, 26);
frame.getContentPane().add(lhs);
lhs.setColumns(10);
JLabel label = new JLabel("<");
label.setBounds(86, 51, 10, 16);
frame.getContentPane().add(label);
JLabel label_1 = new JLabel("<");
label_1.setBounds(159, 51, 10, 16);
frame.getContentPane().add(label_1);
rhs = new JTextField();
rhs.setColumns(10);
rhs.setBounds(181, 46, 68, 26);
frame.getContentPane().add(rhs);
JLabel lblmn = new JLabel("(m/n)");
lblmn.setBounds(108, 51, 61, 16);
frame.getContentPane().add(lblmn);
JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnCompute.setBounds(261, 46, 117, 29);
frame.getContentPane().add(btnCompute);
}
}
JButton btnCompute = new JButton("Compute");
btnCompute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double leftValue = Double.parseDouble(lhs.getText());
double rightValue = Double.parseDouble(rhs.getText());
// Do your stuff with it.
}
catch ( NumberFormatException ex ) {
// Do stuff if the input is not a number.
}
}
}
Hello I am working on this project to store student names and record their grades. I have the entire program mapped out and all I need to do now is record the integers and strings from the user input and call it from different classes. I am having trouble with this. Do I use an array? How do I call from another class? Thank you.
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
private JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
Is it something along the lines of this?
studentNameTextField = new JTextField("Enter here");
String stdname = studentNameTextField.getText();
I know this would be storing it but how do I call that in a different class so I can make it appear on a different Frame?
Update: Okay so I've done this
Student frame = new Student();
String stdname = frame.studentNameTextField.getText();
JLabel addgradesLabel = new JLabel("Add grades for" + frame.studentNameTextField);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
And it's still not working. I believe I'm not implementing this correctly. I'm trying to title the label with what the user inputs for the name. So it would but "Add grades for" + stdname But it's not calling it correctly. How can I fix this?
Here is my code from the AddStudentName class
studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student.this.dispose();
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
What should I add here to save the input that the user is inputting into the JTextField? Thanks for the help
Here's the full code for the classes:
package gradebook;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class Student extends JFrame {
private JFrame studentFrame;
private JPanel contentPane;
public JTextField studentNameTextField;
protected Component frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Student frame = new Student();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel lblPleaseEnterThe = new JLabel("Please enter the student name");
lblPleaseEnterThe.setBounds(130, 105, 194, 16);
contentPane.add(lblPleaseEnterThe);
JTextField studentNameTextField = new JTextField();
studentNameTextField.setBounds(130, 133, 194, 26);
contentPane.add(studentNameTextField);
studentNameTextField.setColumns(10);
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades();
addGradesScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a) {
if(cancelButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
contentPane.setVisible(false);
contentPane.disable();
}
}
});
cancelButton.setBounds(207, 243, 117, 29);
contentPane.add(cancelButton);
}
private void initizalize() {
// TODO Auto-generated method stub
}
}
and:
package gradebook;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddGrades extends JFrame {
private JPanel contentPane;
private JTextField Assignment1;
private JTextField Assignment2;
private JTextField Assignment3;
private JTextField Assignment4;
private JLabel testsLabel;
private JTextField Test1;
private JTextField Test2;
public JTextField Test3;
public JTextField Test4;
/**
* Launch the application.
*/
public JFrame frame;
public JButton continueButton;
public JButton exitButton;
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddGrades() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel gradebookLabel = new JLabel("Gradebook");
gradebookLabel.setBounds(189, 6, 68, 16);
contentPane.add(gradebookLabel);
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
addgradesLabel.setBounds(139, 34, 167, 29);
contentPane.add(addgradesLabel);
JLabel assignmentsLabel = new JLabel("Assignments:");
assignmentsLabel.setBounds(19, 75, 86, 16);
contentPane.add(assignmentsLabel);
Assignment1 = new JTextField();
Assignment1.setBounds(54, 91, 130, 26);
contentPane.add(Assignment1);
Assignment1.setColumns(10);
Assignment2 = new JTextField();
Assignment2.setBounds(54, 129, 130, 26);
contentPane.add(Assignment2);
Assignment2.setColumns(10);
Assignment3 = new JTextField();
Assignment3.setBounds(54, 167, 130, 26);
contentPane.add(Assignment3);
Assignment3.setColumns(10);
Assignment4 = new JTextField();
Assignment4.setBounds(54, 205, 130, 26);
contentPane.add(Assignment4);
Assignment4.setColumns(10);
testsLabel = new JLabel("Tests:");
testsLabel.setBounds(243, 75, 38, 16);
contentPane.add(testsLabel);
Test1 = new JTextField();
Test1.setBounds(262, 91, 130, 26);
contentPane.add(Test1);
Test1.setColumns(10);
Test2 = new JTextField();
Test2.setBounds(262, 129, 130, 26);
contentPane.add(Test2);
Test2.setColumns(10);
Test3 = new JTextField();
Test3.setBounds(262, 167, 130, 26);
contentPane.add(Test3);
Test3.setColumns(10);
Test4 = new JTextField();
Test4.setBounds(262, 205, 130, 26);
contentPane.add(Test4);
Test4.setColumns(10);
continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
if (continueButton.isEnabled()){
MainScreen mainScreenScreen = new MainScreen();
mainScreenScreen.setVisible(true);
}
}
});
continueButton.setBounds(327, 243, 117, 29);
contentPane.add(continueButton);
exitButton = new JButton("Exit");
exitButton.setBounds(208, 243, 117, 29);
contentPane.add(exitButton);
}
}
I'm trying to take the input from the JTextField
JTextField studentNameTextField = new JTextField();
and set it on the label
JLabel addgradesLabel = new JLabel("Add grades for" + stdname);
Where stdname would be the user input from the JTextField.
Now I'm getting errors from
public static void main(String[] args) {
AddGrades frame = new AddGrades();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddGrades frame = new AddGrades();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
AddGrades frame = new AddGrades(); gives me error Add argument to match AddGrades(String)
The constructor AddGrades() is undefined
Edit: The best way to do this is to pass an argument to your newly created AddGrades class. See below:
public AddGrades(String stdname) {
JLabel addgradesLabel = new JLabel("Add grades for " + stdname);
}
You will need to modify your code to pass a string to your AddGrades class wherever you create it:
JButton continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(continueButton.isEnabled()){
Student studentScreen = new Student();
studentScreen.dispose();
AddGrades addGradesScreen = new AddGrades(studentNameTextField.getText());
addGradesScreen.setVisible(true);
}
}
});
That worked for me - I downloaded your code and tested it.
JSpinner or JFormattedTextField would be my first thought, but if you can't do that then you could use Integer.parseInt to parse a String to int and a NumberFormat to format the numbers to Strings
Maybe have a look at How to Use Spinners and How to Use Formatted Text Fields for starters
I know this would be storing it but how do I call that in a different class so I can make it appear on a different JFrame?
That's a open question with little context. You might use some kind of "model" which represented one or more Student values; you might use a Observer Pattern to allow the editor to generate events to interested parties which would tell them that something has changed; you might use a Model-View-Controller; you might use a modal dialog and when it's closed, ask the editor for the values via getters.
Have a look at How to Make Dialogs for more details
One of things you want to keep in mind is "responsibility" and "encapsulation". You don't want outside parties to have uncontrolled access into your editor or model, this could allow them to modify the state in an uncontrolled way leading to inconsistencies in your data or UI.
You need to decide who is actually responsible for modifying the state of the model. There's no "right" answer, for example, you could have the editor either be capable of editing existing student objects or creating new ones based on how it's configured, equally, you could also have the editor be "dumb" and simply use setters to setup the editor and getters to get the values.
There are lots of options available to you, which you would use would be based on the context in which you want to use it. My gut feeling is start with an observer pattern and a modal dialog.