I have my GUI set up the way I want it now I'm trying to output a string called AnswerKey i have predefined in dashReplace() I tried to draw the string and use JLabel but i just can't seem to find the right method of doing such.
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
public class HangmanPanel extends JPanel {
private static final long serialVersionUID = -5793357804828609325L;
public static String answerKey() {
//get random array element
String array[] = new String[10];
array[0] = "hamlet";
array[1] = "mysts of avalon";
array[2] = "the iliad";
array[3] = "tales from edger allan poe";
array[4] = "the children of hurin";
array[5] = "the red badge of courage";
array[6] = "of mice and men";
array[7] = "utopia";
array[8] = "chariots of the gods";
array[9] = "a brief history of time";
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
Collections.shuffle(list);
String s = list.get(0);
return s;
}
public static StringBuilder dashReplace(String s) {
//replace non-white space char with dashes and creates StringBuilder Object
String tW = s.replaceAll("\\S", "-");
System.out.print(tW + "\n");
StringBuilder AnswerKey = new StringBuilder(tW);
return AnswerKey;
}
public HangmanPanel(){
this.setLayout(null);
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener((ActionListener) this);
JLabel tfLable = new JLabel("Please Enter a Letter:");
//trying to out put predefined string
JLabel AnswerKey = new JLabel(AnswerKey);
JTextField text = new JTextField(10);
//String input = text.getText();
heading.setSize(200, 50);
tfLable.setSize(150, 50);
text.setSize(50, 30);
Button.setSize(60, 20);
heading.setLocation(300, 10);
tfLable.setLocation(50, 40);
text.setLocation(50, 80);
Button.setLocation(100, 85);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
The method is called answerKey, not AnswerKey. In fact, this surely won't compile as you've currently written it - you're trying to assign a variable to something while using that variable as a constructor parameter. It should be:
JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString());
To make this work, however, you'll need to make the method non-static. Also, having a variable named AnswerKey and a method named answerKey is just crying out for confusion - I'd suggest a better name for the JLabel.
Related
I have been trying to create a (ugly) calculator and I am having problems with "=" sign. I know how to convert numbers (in string) to numbers (in int), but the problem here is mainly */-+. I have absolutely no idea what to do when they are added to the situation.
Here is a gif of the calculator: http://gyazo.com/98781eaaca0b3152967e6370cad3df15
package megetenkelkalkis;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
class Kalkulator extends JFrame{
private String textfield = "";
private String replace ="";
private JButton btn0 = new JButton("0");
private JButton btn1 = new JButton("1");
private JButton btn2 = new JButton("2");
private JButton btn3 = new JButton("3");
private JButton btn4 = new JButton("4");
private JButton btn5 = new JButton("5");
private JButton btn6 = new JButton("6");
private JButton btn7 = new JButton("7");
private JButton btn8 = new JButton("8");
private JButton btn9 = new JButton("9");
private JButton btnlik = new JButton("=");
private JButton btngange = new JButton("*");
private JButton btndele = new JButton("/");
private JButton btnpluss = new JButton("+");
private JButton btnminus = new JButton("-");
private JTextField tekst = new JTextField();
private JButton btndel= new JButton("DEL");
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
public Kalkulator(String tittel){
tekst.setPreferredSize(new Dimension(310,25));
setTitle(tittel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.add(btn0);
p.add(btn1);
p.add(btn2);
p.add(btn3);
p.add(btn4);
p.add(btn5);
p.add(btnlik);
p2.add(btn6);
p2.add(btn7);
p2.add(btn8);
p2.add(btn9);
p2.add(btndele);
p2.add(btngange);
p2.add(btnpluss);
p2.add(btnminus);
p3.add(tekst);
p3.add(btndel);
add(p, BorderLayout.SOUTH);
add(p2, BorderLayout.CENTER);
add(p3, BorderLayout.NORTH);
pack();
Knappelytter knappelytteren = new Knappelytter();
btn0.addActionListener(knappelytteren);
btn1.addActionListener(knappelytteren);
btn2.addActionListener(knappelytteren);
btn3.addActionListener(knappelytteren);
btn4.addActionListener(knappelytteren);
btn5.addActionListener(knappelytteren);
btn6.addActionListener(knappelytteren);
btn7.addActionListener(knappelytteren);
btn8.addActionListener(knappelytteren);
btn9.addActionListener(knappelytteren);
btnlik.addActionListener(knappelytteren);
btndele.addActionListener(knappelytteren);
btngange.addActionListener(knappelytteren);
btnminus.addActionListener(knappelytteren);
btnpluss.addActionListener(knappelytteren);
btndel.addActionListener(knappelytteren);
}
class Knappelytter implements ActionListener{
public void actionPerformed (ActionEvent hendelse){
JButton valgtKnapp = (JButton) hendelse.getSource();
String knapp = valgtKnapp.getText();
if (knapp.equals("0")){
textfield += "0";
tekst.setText(textfield);
}else if(knapp.equals("1")){
textfield += "1";
tekst.setText(textfield);
}else if(knapp.equals("2")){
textfield += "2";
tekst.setText(textfield);
}else if(knapp.equals("3")){
textfield += "3";
tekst.setText(textfield);
}else if(knapp.equals("4")){
textfield += "4";
tekst.setText(textfield);
}else if(knapp.equals("5")){
textfield += "5";
tekst.setText(textfield);
}else if(knapp.equals("6")){
textfield += "6";
tekst.setText(textfield);
}else if(knapp.equals("7")){
textfield += "7";
tekst.setText(textfield);
}else if(knapp.equals("8")){
textfield += "8";
tekst.setText(textfield);
}else if(knapp.equals("9")){
textfield += "9";
tekst.setText(textfield);
}else if(knapp.equals("*")){
textfield += "*";
tekst.setText(textfield);
}else if(knapp.equals("/")){
textfield += "/";
tekst.setText(textfield);
}else if(knapp.equals("-")){
textfield += "-";
tekst.setText(textfield);
}else if(knapp.equals("+")){
textfield += "+";
tekst.setText(textfield);
}else if(knapp.equals("DEL")){
tekst.setText(" ");
textfield = " ";
}else if(knapp.equals("=")){
else if(knapp.equals("=")){
/EDIT RIGHT HERE
String[] parts = textfield.split("-*/+");
for (int i = 0; i < textfield.length(); i++){
if (textfield.charAt(i) == ('-')){
String one = parts[0];
String two = parts[1];
int one1 = Integer.parseInt(one);
int one2 = Integer.parseInt(two);
int one3 = one1-one2;
String one4 = String.valueOf(one3);
tekst.setText(one4);
}
}
}
}
public class MegetEnkelKalkis {
public static void main(String[] args) {
Kalkulator Skole = new Kalkulator("Kalkulator");
Skole.setVisible(true);
}
}
Get the Input
Seperate it from the Operands ( *, /, -, + )
Cast the strings to int's ( Integer.valueOf() throws a NumberFormatException)
Do a if else for the operands and then multiply, divide, add or substract the ints
What you need is a string calculator. You basically parse the contents of textfield following the regular maths rules. It is a bit of work but not too hard.
Basically just follow this:
Recursion might be quite suitable for that, so build a function that takes a string and returns the result as an int.
Search for all occurrences of a parameter (e.g. ) starting with the highest priority ones ( and /)
If you encounter that parameter split the string there into two halves (left of the parameter and right of the parameter)
Recursively follow the same rules with the left and right part of the string.
If the String only contains one number, parse that number using Integer.parseInt() and return it.
Calculate the result of left operator right, so e.g. left * right, if the operator is *
Return the result of the calculation.
Or you calculate via nashorn (javascript) engine ;)
private ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
double result = (double) scriptEngine.eval(formula)
You should build a reverse polish notation, which is the easiest way to parse and evaluate methmatical formulas. there are plenty of examples how to do that in Java on the web.
There are anumber of ways to do this, but recommendation is that you create two doubles. When the user clicks +,-,\ or * parse the number before it into a double. Thenwhen they press = parse everything between + and = into a double, then perform the calculation using those two doubles and output the result. You can set a flag to determine which operation to perform. for example the + button could set a boolean called Plus = true; Then when you perform the operation check which bools are true. IF more or less than one, tell the user the input was invalid, otherwise perform the operation
There is definitely lot of scope of improvement in the code, as suggested by others, but if you want to keep it as it is and working, then here is the code:
.
.
.
}else if(knapp.equals("=")){
String nytekst = textfield;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
Double result = (Double) engine.eval(nytekst);
System.out.println(result);
tekst.setText(result.toString());
} catch (ScriptException e) {
e.printStackTrace();
}
}
.
.
.
I am trying to add the contents of two arrays to two TextFields. When you run the program the problem is the current TextFields that I try to display (lines 70 - 83) when the window is redrawn, they only show the last item in their array. Is there any way to add all the items in a stacked list (one ontop of another.)
This is my first class ClassNameSorting
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class ClassNameSorting extends JFrame {
JTextField studentNameInputFirst, studentNameInputLast, studentNamesEneteredLast, studentNamesEnteredFirst;
JButton nextName, sort, backToStart;
JLabel firstName, lastName, classList;
String disp = "";
ArrayList<String> studentNameFirst = new ArrayList<String>();
ArrayList<String> studentNameLast = new ArrayList<String>();
ArrayList<String> sortedStudentNameFirst = new ArrayList<String>();
ArrayList<String> savedUnsortedStudentNameLast = new ArrayList<String>();
Container container = getContentPane();
public ClassNameSorting() {
container.setLayout(new FlowLayout());
studentNameInputFirst = new JTextField(15);
studentNameInputLast = new JTextField(15);
nextName = new JButton("Save");
sort = new JButton("Sort");
firstName = new JLabel("First Name: ");
lastName = new JLabel("Last Name: ");
nextName.setPreferredSize(new Dimension(110, 20));
sort.setPreferredSize(new Dimension(110, 20));
container.add(firstName);
container.add(studentNameInputFirst);
container.add(lastName);
container.add(studentNameInputLast);
container.add(nextName);
container.add(sort);
nextName.addActionListener(new nextNameListener());
sort.addActionListener(new sortListener());
setSize(262, 120);
setVisible(true);
}
private class nextNameListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
studentNameFirst.add(studentNameInputFirst.getText());
studentNameLast.add(studentNameInputLast.getText());
studentNameInputLast.setText(null);
studentNameInputFirst.setText(null);
}
}
private class sortListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
savedUnsortedStudentNameLast = new ArrayList<String>(studentNameLast);
Collections.sort(studentNameLast);
int totalSizeOfArray = studentNameLast.size();
for(int i = 0; i < totalSizeOfArray; i++){
boolean containsYorN = false;
String tempElementForContains = studentNameLast.get(i);
String tempElementFromStudentNameLast = savedUnsortedStudentNameLast.get(i);
containsYorN = savedUnsortedStudentNameLast.contains(tempElementForContains);
if(containsYorN == true){
int tempIndexPos = savedUnsortedStudentNameLast.indexOf(tempElementForContains);
String tempIndexElement = studentNameFirst.get(tempIndexPos);
sortedStudentNameFirst.add(i, tempIndexElement);
}
}
studentNamesEneteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
}
studentNamesEneteredLast.setEditable(false);
studentNamesEnteredFirst.setEditable(false);
container.add(studentNamesEneteredLast);
container.add(studentNamesEnteredFirst);
setSize(262, 500);
revalidate();
}
}
}
My second class is: (DrawMainWindow)
import javax.swing.JFrame;
public class DrawMainWindow {
public static void main(String[] args) {
ClassNameSorting drawGui = new ClassNameSorting();
drawGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawGui.setLocationRelativeTo(null);
}
}
The first array is studentNameLast. I am trying to add that to studentNamesEnteredLast text field. The second is sortedStudentNameFirst being added to studentNamesEnteredFirst.
Thanks for the help!
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEneteredLast.setText(studentNameLast.get(i));
}
The text in the JTextField will only reflect the last item of the List. If you wish to append the entire list, create a String from the List and set the text of the JTextField with that String (you might wish to have them separated by some character - below uses a comma)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < totalSizeOfArray; i++){
sb.append(studentNameLast.get(i)).append(",");//comma delim
}
studentNamesEneteredLast.setText(sb.toString());
Not entirely sure what you are after, but a JList or JTable might be more appropriate to display List information
Was able to switch to a GridLayout and then added each last name and then first name together.
Code:
container.setLayout(new GridLayout(totalSizeOfArray+3,2));
for(int i = 0; i < totalSizeOfArray; i++){
studentNamesEnteredLast = new JTextField();
studentNamesEnteredFirst = new JTextField();
studentNamesEnteredFirst.setEditable(false);
studentNamesEnteredLast.setEditable(false);
studentNamesEnteredLast.setText(studentNameLast.get(i));
studentNamesEnteredFirst.setText(sortedStudentNameFirst.get(i));
container.add(studentNamesEnteredLast);
container.add(studentNamesEnteredFirst);
}
Example:
I'm trying to replace setCharAt with something that can be used with a JLabel... I've been on oracle doc's looking for a solution. i don't know if I'm looking for the wrong thing or it just doesn't exists.. if it doesn't exists how could i work around that? i understand my naming convention is off and will be changing them as soon as possible...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.*;
public class HangmanPanel extends JPanel {
static Boolean FOUND;
private static final long serialVersionUID = -5793357804828609325L;
public static String answerKey() {
//get random array element
String array[] = new String[10];
array[0] = "hamlet";
array[1] = "mysts of avalon";
array[2] = "the iliad";
array[3] = "tales from edger allan poe";
array[4] = "the children of hurin";
array[5] = "the red b" +
"+adge of courage";
array[6] = "of mice and men";
array[7] = "utopia";
array[8] = "chariots of the gods";
array[9] = "a brief history of time";
ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
Collections.shuffle(list);
String s = list.get(0);
return s;
}
public StringBuilder dashReplace(String s) {
//replace non-white space char with dashes and creates StringBuilder Object
String tW = s.replaceAll("\\S", "-");
System.out.print(tW + "\n");
StringBuilder AnswerKey = new StringBuilder(tW);
return AnswerKey;
}
public static int findAndReplace(String s, JLabel answerKey, String sc,
char ch) {
//find position of user input and replace
int pos = -1;
FOUND = false;
while(true){
pos = s.indexOf(sc, pos+1);
if(pos < 0){
break;
}else{
FOUND = true;
//setCharAt dosen't work for JLable
answerKey.setCharAt(pos, ch);
}
}
JLabel AnswerKey2 = new JLabel(answerKey.toString());
return pos;
}
public HangmanPanel(final String s){
this.setLayout(null);
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//get input
JLabel tfLable = new JLabel("Please Enter a Letter:");
final JLabel AnswerKey = new JLabel(dashReplace(answerKey()).toString());
final JTextField text = new JTextField(10);
heading.setSize(200, 50);
tfLable.setSize(150, 50);
text.setSize(50, 30);
Button.setSize(60, 20);
AnswerKey.setSize(200, 100);
heading.setLocation(300, 10);
tfLable.setLocation(50, 40);
text.setLocation(50, 80);
Button.setLocation(100, 85);
AnswerKey.setLocation(100,85);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
this.add(AnswerKey);
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// can't access text
String sc = text.getText();
char ch = sc.charAt(0);
findAndReplace(s, AnswerKey, sc, ch);
}
});
}
}
Why are you trying to use setCharAt(...) with a JLabel. A label is meant to display static text. The only way to change it is to replace the entire string.
I guess you could do something like:
StringBuilder text = label.getText();
text.setCharAt(...);
label.setText( text.toString() );
Another option would be to use a JTextField that looks like a JLabel:
JTextField label = new JTextField(...);
label.setEditable(false);
label.setBorder(null);
label.setOpaque(false);
Then when you need to change the text you could do:
label.select(...);
label.replaceSelection(...);
The only method available for setting text for JLabel components is setText. Also Strings are immutable. Therefore, you can use StringBuilder:
StringBuilder builder = new StringBuilder(answerKey.getText());
builder.setCharAt(pos, ch);
answerKey.setText(builder.toString());
I'm trying to create a program that will take data in from a random access file and sort it based on whichever checkbox the user selects. The data should be sorted by either the bank account number, customer name or balance (when a user clicks that checkbox the data in the text area becomes sorted based on that). Once the data is sorted, it is outputted into the JTextArea. I'm also trying to output the total amount of entries from the file in the text field below the check boxes.
Thanks!
import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;
public class GUIBankAcctSorter extends JFrame implements ItemListener {
public static void main(String[] args) {
GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
myFrame.setVisible(true);
Path file = Paths.get("C:\\Java\\Bank.txt");
final String ID_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final String EMPTY_ACCT = "0000";
String[] array = new String[3];
double balance = 0;
output(s, array, delimiter, balance, EMPTY_ACCT, file);
}
private static final long serialVersionUID = 1L;
private static final int WIDTH = 450;
private static final int HEIGHT = 310;
private static final int X_ORIGIN = 200;
private static final int Y_ORIGIN = 200;
JLabel title = new JLabel("Bank Account Sorter");
JLabel sort = new JLabel("Sort By ");
JLabel total = new JLabel("Total # of Bank Accounts ");
private Container con = getContentPane();
private FlowLayout layout = new FlowLayout();
static JTextArea area = new JTextArea(10, 35);
static JTextField field = new JTextField(5);
JCheckBox cust = new JCheckBox(" Cust # ", false);
JCheckBox bal = new JCheckBox(" Balance ", false);
JCheckBox name = new JCheckBox(" Name ", false);
public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){
String temp = "";
try{
InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
while(s != null){
array = s.split(delimiter);
if(!array[0].equals(EMPTY_ACCT)){
balance = Double.parseDouble(array[2]);
area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2] + "\n");
}
s = reader.readLine();
}
reader.close();
}catch(Exception e){
System.out.println("Message: " + e);
}
field.setText(temp);
}
public GUIBankAcctSorter(){
super("Bank Account Sorter");
Font headFont = new Font("Arial", Font.BOLD, 28);
con.setLayout(layout);
title.setFont(headFont);
con.add(title);
area.setEditable(false);
field.setEditable(false);
con.add(new JScrollPane(area));
cust.addItemListener(this);
bal.addItemListener(this);
name.addItemListener(this);
con.add(sort);
con.add(cust);
con.add(bal);
con.add(name);
con.add(total);
con.add(field);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == cust){
if(select == ItemEvent.SELECTED){
bal.setSelected(false);
name.setSelected(false);
}
}
if(source == bal){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
name.setSelected(false);
}
}
if(source == name){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
bal.setSelected(false);
}
}
}
}
Here you can see a good example using comparator to sort the object.
Let us suppose:
RowTest is a class that represent a single row of grid.
orderAMT is a class variable/Column/JTextField of Row.
Now the code below show how to sort the List of RowTest according to its attribute orderAMT.
List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
Comparator comparator = new OrderAMTComparator();
Collections.sort(sortedList, comparator);
public class OrderAMTComparator implements Comparator<RowTest> {
#Override
public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list
//repace getOrderAMT with other fields.
BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());
//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement
if (compareRes.compareTo(new BigDecimal(0)) == -1) {
return -1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
return 1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
return 0;
}
return compareRes.intValue();
}
}
I hope you have understand this. If not I will elaborate.
Thankyou.
Is there anyway to do it with checkboxes?
Certainly:
Declare an Account class that stores the account number, name & balance.
Add each new Account to a List structure such as ArrayList.
Create a Comparator relevant to each of the 2 fields.
At time of sort, use Collections.sort(list,comparator).
Refresh the text area with the content of the sorted list.
Other tips
Since those check boxes are mutually exclusive, they should really be a ButtonGroup of JRadioButton instances.
Change setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); & setLocationRelativeTo(null) to setLocationByPlatform(true). See this answer for a demo.
Change setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT); for pack() (& use layouts more effectively).
So i was writing a program to solve a quadratic equation, and everything works apart from when it comes to making 2 JLabels (previously empty) show the answers, (this happens when the user clicks a JButton)
Here is the whole program, because i have no idea where the error is.
import java.awt.event.*;
import javax.swing.*;
public class Third implements ActionListener {
//--------------
//Data Members
//--------------
/**
* Top level window
*/
JFrame top;
/**
* Changed into a string by ConvertToDouble(string str);
*/
double a, b, c;
double answer1,answer2;
JTextField inputA, inputB, inputC;
JLabel describeA, describeB, describeC, print1, print2;
JButton submit;
String aa, bb, cc;
String result1, result2;
String strA, strB, strC;
public Third(){
top = new JFrame("Ned's quadratic equation solver");
top.setVisible(true);
top.setLayout(null);
top.setBounds(50,50,250,250);
inputA = new JTextField(12);
inputA.setBounds(100,30,200,25);
inputB = new JTextField(12);
inputB.setBounds(100,105,200,25);
inputC = new JTextField(12);
inputC.setBounds(100,185,200,25);
describeA = new JLabel("Enter A here:");
describeA.setBounds(10,30,200,25);
describeB = new JLabel("Enter B here:");
describeB.setBounds(10,105,200,25);
describeC = new JLabel("Enter C here:");
describeC.setBounds(10,185,200,25);
print1 = new JLabel();
print1.setBounds(15,290,1000,10);
print2 = new JLabel();
print2.setBounds(15,310,1000,10);
submit = new JButton ("WHAT DOES X = ???");
submit.setBounds(50,230,150,25);
submit.addActionListener(this);
top.add(inputA);
top.add(inputB);
top.add(inputC);
top.add(describeA);
top.add(describeB);
top.add(describeC);
top.add(submit);
top.doLayout();
}
public void actionPerformed(ActionEvent event) {
aa = inputA.getText();
bb = inputB.getText();
cc = inputC.getText();
a = convertToDouble(aa);
b = convertToDouble(bb);
c = convertToDouble(cc);
makeAns(a,b,c);
/*
* DEBUG CODE
*
* System.out.println(a);
* System.out.println(b);
* System.out.println(c);
* System.out.println(answer1);
* System.out.println(answer2);
*/
result1 = "x = " + answer1;
result2 = "x = " + answer2;
print1.setText(result1);
print2.setText(result2);
//System.out.println(result1);
top.doLayout();
}
private void makeAns(double x,double y,double z){
answer1 =(-y + Math.sqrt (y*y-4*x*z))/(2*x);
answer2 =(-y - Math.sqrt (y*y-4*x*z))/(2*x);
}
private double convertToDouble (String str) {
Double dubb = new Double(str);
return dubb.doubleValue();
}
}
You've got to add a component to the GUI first before it can display anything. Where do you add your print1 and print2 JLabels to the GUI or to any container for that matter?
Also, you'll want to use layout managers rather than null layout and absolute positioning to make coding your GUI's much easier.
Also, you'll want to call setVisible(true) on the JFrame after adding all components.