I've got probably trivial problem but I've spent hours in looking for answer.
I would like to create a button (ENTER button) that once clicked, removes certain components on the GUI (like numpad). The problem is that the class that defines instructions to do once button clicked doesn't see the components. I've tried to add implements ATM to this class but then the console returned very weird errors (when executing). Is there any 'clean' way to do this?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ATM extends JFrame{
// Container
int state = 0; // PIN screen
// ELEMENTS
JPanel container = new JPanel();
JTextArea display = new JTextArea("Please enter your PIN", 10, 50);
JTextField inputArea = new JTextField("");
JPanel buttons = new JPanel();
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton zero = new JButton("0");
JButton clear = new JButton("Clear");
JButton enter = new JButton("Enter");
JButton quit = new JButton("Quit");
// EVENTS
ButtonPresser buttonPress = new ButtonPresser(inputArea, display);
EnterPresser enterPress = new EnterPresser(inputArea, display, state, buttons);
ATM(){
super("ATM Cash Machine");
buildGUI();
pack();
setVisible(true);
}
private void buildGUI(){
// EVENT BINDINGS
one.addActionListener(buttonPress);
two.addActionListener(buttonPress);
three.addActionListener(buttonPress);
four.addActionListener(buttonPress);
five.addActionListener(buttonPress);
six.addActionListener(buttonPress);
seven.addActionListener(buttonPress);
eight.addActionListener(buttonPress);
nine.addActionListener(buttonPress);
zero.addActionListener(buttonPress);
clear.addActionListener(buttonPress);
quit.addActionListener(buttonPress);
enter.addActionListener(enterPress);
// ELEMENT SETTINGS
inputArea.setEditable(false);
display.setEditable(false);
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(display);
container.add(inputArea);
// Numeric pad
buttons.setLayout(new GridLayout(5,3));
buttons.add(one);
buttons.add(two);
buttons.add(three);
buttons.add(four);
buttons.add(five);
buttons.add(six);
buttons.add(seven);
buttons.add(eight);
buttons.add(nine);
buttons.add(clear);
buttons.add(zero);
buttons.add(enter);
buttons.add(quit);
container.add(buttons);
add(container, BorderLayout.NORTH);
}
// Main method
public static void main(String[] args){
ATM atm = new ATM();
}
}
class ButtonPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
ButtonPresser(JTextField in, JTextArea out){
iField = in;
oArea = out;
}
public void actionPerformed(ActionEvent e){
switch(e.getActionCommand()){
case "Quit":
System.exit(0);
break;
case "Clear":
iField.setText("");
break;
default:
String fieldText = iField.getText();
if(fieldText.length() < 4){
iField.setText(fieldText+e.getActionCommand());
}
break;
}
}
}
class EnterPresser implements ActionListener{
private JTextField iField;
private JTextArea oArea;
private int state;
private JPanel buttons;
private final String PIN = "1234";
EnterPresser(JTextField in, JTextArea out, int st, JPanel but){
iField = in;
oArea = out;
state = st;
buttons = but;
}
public void actionPerformed(ActionEvent e){
if(state == 0){
String fieldText = iField.getText();
if(fieldText.equals(PIN)){
iField.setText("");
state = 1;
uiState0To1();
}
}
}
public void uiState0To1(){
buttons.remove(one);
}
}
The solution to your problem is simple. You need some way for your ButtonPresser class to talk with your ATM class, this is a classic example of an Observer Pattern
The idea is, you would provide some kind of event notification that your ButtonPresser will trigger under certain conditions, then your ATM class would listen for those events, it would then decide what it should do based on those events.
It is not the responsibility of the ButtonPresser to modify the state of ATM, just so we're clear.
You're now moving into the realm of Model-View-Controller, which could provide you a means to utilise CardLayout, which will further reduce the overall complexity of your problem, but also isolate responsibility and decouple your code
I am not sure which components you are trying to remove, but your problem is pretty clear. All of the components defined in the ATM class are not public. One way to manipulate these components from other classes would be to set them public.
The simplest way is to declare them as "public static" and reference them statically through the ATM class. Depending on your case you may need multiple instances of ATM, in which case you would not declare them static.
Here is another question with good info: Difference between public static and private static variables
Related
Hi though i did complete the basics of java which im fairly new of, i keep getting errors when i try to add buttons on a new Frame/Panel. Care to educate me on what the problem might be?
import javax.swing.*;
import java.awt.*;
class MainClass {
String cont_orders;
private JFrame frame1;
private JPanel mainpanel;
JButton bt1, bt2, bt3, bt4, bt5;
private JButton btotal = new JButton("Order");
private JButton clearOr = new JButton("Clear");
private JTextField pricetotal = new JTextField();
private JTextField list_of_orders = new JTextField();
public MainClass(){
gui();
}
private void gui(){
frame1 = new JFrame("Order");
frame1.setSize(500,430);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setResizable(false);
mainpanel = new JPanel();
mainpanel.setBackground(Color.BLUE);
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
frame1.add(mainpanel,BorderLayout.CENTER);
}
public static void main (String[]args){
new MainClass();
}
}
im trying to practice on coding normally instead of relying on that automatic one in NetBeans [JFrame Form/JPanel Form]
care to help?
Now this cannot be done in java
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
Turn it around.
Explanation: the field bt1 is at that time a variable holding the null object.
That object (value) is added, not some variable address as in other languages.
Reverse it bt1 = new JButton("M-Item 1 [Soda]"
mainpanel.add(bt1);
Because if not the value of bt1 would be null so you must fill it first then use it .
Or
mainpanel.add(new JButton("..."));
I am a beginner Java-coder and a few days ago I felt confident enough in my skills to start my first "big" project. It was basically a calculator, a GUI(only JFrame, JPanels, JLabels and Buttons) that would display data, accept user input, grab some more data from other classes, then calculate stuff and finally update the GUI with the new JLabel values. However I never managed to get the update part done properly, whenever I would press the 'process'-button it would create a new JFrame with the new values, while the old one was still up.
I tried the obvious stuff (repaint(), revalidate(), etc) but that didn't work at all, then I started to shift things around, put parts of the code into new classes, copied code from the net until it eventually worked. However the code was a total mess and I didn't even really understand what went exactly wrong in the first place, so I trashed the entire thing.
Here is a very simplified version of my code before things went downhill:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
public Test_1(){
clicks getNumber = new clicks();
int x = getNumber.getclicks();
//FRAME AND LAYOUT
JFrame window = new JFrame();
window.getContentPane().setBackground(Color.darkGray);
window.getContentPane().setLayout(new BorderLayout(20,10));
window.setTitle("Test Frame 1");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);
// Top JPanel
JPanel northpanel = new JPanel();
LayoutManager northlayout = new FlowLayout();
northpanel.setLayout(northlayout);
// Top JPanel content
JLabel nlabel1 = new JLabel("Hello North");
nlabel1.setPreferredSize(new Dimension(100,20));
northpanel.add(nlabel1);
JPanel westpanel = new JPanel();
LayoutManager westlayout = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(westlayout);
JLabel wlabel1 = new JLabel("Hello West");
wlabel1.setPreferredSize(new Dimension(100,20));
westpanel.add(wlabel1);
JPanel eastpanel = new JPanel();
LayoutManager eastlayout = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eastlayout);
JLabel elabel1 = new JLabel ("Hello East");
elabel1.setPreferredSize(new Dimension(100,20));
eastpanel.add(elabel1);
JButton southbutton = new JButton("start");
southbutton.setPreferredSize(new Dimension(400,50));
southbutton.addActionListener(new Action());
JPanel centralpanel = new JPanel();
JLabel clabel1 = new JLabel("Clicks: " + x);
centralpanel.add(clabel1);
window.add(centralpanel, BorderLayout.CENTER);
window.add(southbutton, BorderLayout.SOUTH);
window.add(eastpanel, BorderLayout.EAST);
window.add(westpanel, BorderLayout.WEST);
window.add(northpanel, BorderLayout.NORTH);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
System.out.println("Button works, Number of clicks: "+test);
Test_1 updateData = new Test_1();
}
}
}
I know that the ActionListener creates a new instance of my JFrame, however that was the closest I ever came to "updating the JFrame" before I turned the code into Spaghetti. I assume that the way I build my code is the cause of my problem but creating the Frame and its content it different classes didn't work at all.
So my questions are:
Is there something really obvious I missing? Would it be possible to make this run the way I want to without completely changing it?
Is there a more efficient way to create a GUI? I get the feeling that the way I made this is total garbage.
I read other questions that dealt with similar problems but maybe it's because I am still pretty bad at Java but I couldn't really tell if they were related to my problem. Also I really want to understand this, so copying someone elses code wouldn't help at all.
Any help or comments are appreciated.
btw, the class click is something I just put there as a placeholder.
Alrighty I managed to get it to work. It's probably against the Etiquette to answer to his own question but I thought it might be useful for some beginners(like me yesterday). So here is my new code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test_1 extends JFrame {
public static class clicks{
static int clicks = 0;
public int getclicks(){
return clicks;
}
public void setclicks(){
clicks = clicks+1;
}
}
clicks getNumber = new clicks();
int x = getNumber.getclicks();
JPanel northpanel, westpanel, eastpanel, southpanel, centralpanel;
static JLabel nlabel1, nlabel2, nlabel3, nlabel4, nlabel5;
static JLabel wlabel1, wlabel2, wlabel3, wlabel4, wlabel5;
static JLabel elabel1, elabel2, elabel3, elabel4, elabel5;
static JLabel clabel1;
JButton southbutton;
String TextnL, TextwL, TexteL;
public Test_1(){
setBackground(Color.darkGray);
setLayout(new BorderLayout(20,10));
setTitle("Test Frame 1");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
nlabel1 = new JLabel("North_1");
nlabel2 = new JLabel("North_2");
nlabel3 = new JLabel("North_3");
nlabel4 = new JLabel("North_4");
nlabel5 = new JLabel("North_5");
wlabel1 = new JLabel("West_1 ");
wlabel2 = new JLabel("West_2 ");
wlabel3 = new JLabel("West_3 ");
wlabel4 = new JLabel("West_4 ");
wlabel5 = new JLabel("West_5 ");
elabel1 = new JLabel("East_1");
elabel2 = new JLabel("East_2");
elabel3 = new JLabel("East_3");
elabel4 = new JLabel("East_4");
elabel5 = new JLabel("East_5");
clabel1 = new JLabel("START");
southbutton = new JButton("Process");
southbutton.addActionListener(new Action());
northpanel = new JPanel();
northpanel.add(nlabel1);
northpanel.add(nlabel2);
northpanel.add(nlabel3);
northpanel.add(nlabel4);
northpanel.add(nlabel5);
add(northpanel, BorderLayout.NORTH);
westpanel = new JPanel();
LayoutManager wBox = new BoxLayout(westpanel, BoxLayout.Y_AXIS);
westpanel.setLayout(wBox);
westpanel.add(wlabel1);
westpanel.add(wlabel2);
westpanel.add(wlabel3);
westpanel.add(wlabel4);
westpanel.add(wlabel5);
add(westpanel, BorderLayout.WEST);
eastpanel = new JPanel();
LayoutManager eBox = new BoxLayout(eastpanel, BoxLayout.Y_AXIS);
eastpanel.setLayout(eBox);
eastpanel.add(elabel1);
eastpanel.add(elabel2);
eastpanel.add(elabel3);
eastpanel.add(elabel4);
eastpanel.add(elabel5);
add(eastpanel, BorderLayout.EAST);
centralpanel = new JPanel();
centralpanel.add(clabel1);
add(centralpanel, BorderLayout.CENTER);
add(southbutton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Test_1 window_start = new Test_1();
}
static class Action implements ActionListener{
#Override
public void actionPerformed (ActionEvent e){
clicks Numbers = new clicks();
Numbers.setclicks();
int test = Numbers.getclicks();
clabel1.setText("clicks: "+test);
}
}
}
And again, any comments/suggestions are welcome.
I'm trying to make a program that will do some fairly simple calculations in a JPanel. One of the requirements is that it will repeat until the user says otherwise. Unfortunately when the JPanel opens it does not wait for any user input, but instead moves right on to the next thing (as I have yet written the part that asks the user if he would like to continue or quit, it's currently in an infinite while loop which means that new JPanels just keep opening continually until I stop the program). My question is: Why isn't the program waiting until the user presses the Okay button to move on?
Here is my main():
public class Driver extends JFrame{
public static void main(String args[]){
do{
new GUI();
while (!GUI.isButtonPressed()){
}
//int choice = JOptionPane.showConfirmDialog(null, "Default tax rate is 7.5%\nDefault discount rate is 10%.\nKeep these default values?", "Choose an Option", JOptionPane.YES_NO_OPTION);
//switch (choice){
//case JOptionPane.YES_OPTION: {
//SaleItem newItem = new SaleItem();
//break;
//}
//case JOptionPane.NO_OPTION: {
//new GUI();
//break;
//}
//}
}while(true);
}
and here is my GUI:
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame {
JPanel panel;
JLabel priceLabel;
JLabel discountLabel;
JLabel taxLabel;
JTextField taxTextField;
JTextField priceTextField;
JTextField discountTextField;
JButton okayButton;
JButton defaultsButton;
final int WINDOW_WIDTH = 300;
final int WINDOW_HEIGHT = 250;
boolean buttonPressed = false;
public boolean isButtonPressed() {
return buttonPressed;
}
public void setButtonPressed(boolean buttonPressed) {
this.buttonPressed = buttonPressed;
}
public GUI(){
super("Item Properties");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel(){
priceLabel = new JLabel("Enter the item price:");
priceTextField = new JTextField(10);
discountTextField = new JTextField(10);
discountLabel = new JLabel("Enter the discount percent:");
taxLabel = new JLabel("Enter the tax percent:");
taxTextField = new JTextField(10);
okayButton = new JButton("Okay");
okayButton.addActionListener(new ButtonListener());
defaultsButton = new JButton("Use Defaults");
defaultsButton.addActionListener(new ButtonListener());
panel = new JPanel();
panel.add(priceLabel);
panel.add(priceTextField);
panel.add(discountLabel);
panel.add(discountTextField);
panel.add(taxLabel);
panel.add(taxTextField);
panel.add(okayButton);
panel.add(defaultsButton);
}
private class ButtonListener implements ActionListener {
private boolean buttonPressed = false;
public void actionPerformed(ActionEvent event){
GUI.setButtonPressed(true);
SaleItem newItem = new SaleItem(Double.parseDouble(priceTextField.getText()), Double.parseDouble(discountTextField.getText()), Double.parseDouble(taxTextField.getText()));
}
}
The stuff about getButtonPressed() and isButtonPressed() and all that was me trying (unsuccessfully) to solve the problem on my own.
Thanks in advance for any help!
Unfortunately when the JPanel opens it does not wait for any user input,
Panels don't open. You add a panel to a frame or dialog. If you want something to "open" or "popup" then you use a JDialog.
SaleItem newItem = new SaleItem(...);
SaleItem should be a modal JDialog. Then the dialog will not close until the user clicks on button that you create to close the dialog. A dialog is created exactly the same way as you create a JFrame.
I have two programs that each create a different tab in an applet where the user can enter pet types in one tab, and then select and add or remove the pet types to a list in the other tab. I thought I had managed to work out all the problems, but both are now giving me java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
I can't seem to figure out why I'm receiving these errors. Here are the two codes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CreatePanel extends JPanel
{
private Vector petList; //Instantiation of variables. To save space, multiple variables
private JButton button1; //were instantiated at a time when possible, such as the panels.
private SelectPanel sPanel;
private JLabel text1, redText;
private JTextField petInput;
private JTextArea petsIn;
private Panel wPanel, alertPanel, petPanel, createPanel;
public CreatePanel(Vector petList, SelectPanel sPanel)
{
this.petList = petList;
this.sPanel = sPanel;
// orgranize components here
// here is an example
setLayout(new GridLayout(1,2));
text1 = new JLabel("Enter a Pet Type"); //Creation of the visible portions of the applet
petInput = new JTextField();
button1 = new JButton("Create a Pet");
petsIn = new JTextArea("No Pet");
wPanel = new Panel(); //Panels have to be used to ensure the porper layout of the
petPanel = new Panel(); //applet so it conforms to assignment specifications
createPanel = new Panel(); //making for a pretty panel, but some very ugly code
alertPanel = new Panel();
alertPanel.setLayout(new GridLayout(1,2));
createPanel.setLayout(new GridLayout(2,3));
petPanel.setLayout(new GridLayout(1,2)); //Each panel has its own layout, making for layouts
wPanel.setLayout(new GridLayout(3,1)); //in layouts to get everything looking correct.
button1.addActionListener(new ButtonListener()); //adds the listener to the button
add(wPanel);
wPanel.add(alertPanel);
alertPanel.add(redText);
wPanel.add(petPanel);
petPanel.add(text1);
petPanel.add(petInput);
wPanel.add(createPanel);
createPanel.add(new JLabel());
createPanel.add(button1);
createPanel.add(new JLabel()); //Have to create several blank labels to get position of
createPanel.add(new JLabel()); //the create pet button to be positioned correctly.
createPanel.add(new JLabel());
createPanel.add(new JLabel());
add(petsIn);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inputPet = petInput.getText(); //Gets the user input pet
boolean checker = false; // A boolean check type so pets can't be added repeatedly
for (int p = 0; p < petList.size(); p++){ //Runs a check through the petList vector
if (inputPet.equalsIgnoreCase((String) petList.get(p))){ //If a pet already exists (ignoring case) then the check is set to true
checker = true; //for a later if loop to inform the user.
break;
}
}
if(inputPet.equals("")){
redText.setText("Please enter a pet type.");
redText.setForeground(Color.red);
} else if (checker == true){
redText.setText("The pet type already exists.");
redText.setForeground(Color.red);
} else {
petList.add(inputPet);
String addedPets = (String) petList.get(0);
for(int i = 1; i < petList.size(); i++){
addedPets += "\n" + (String) petList.get(i);
}
redText.setText("Pet type added.");
redText.setForeground(Color.red);
petsIn.setText(addedPets);
sPanel.updateUI();
}
redText.setText("");
} //end of actionPerformed method
} //end of ButtonListener class
} //end of CreatePanel class
and
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class SelectPanel extends JPanel
{
private Vector petList, selectList;
private Panel bPanel, nPanel;
private JLabel sPets, aPets, nPets;
private int numPets = 0;
private JButton addPet, remove;
private JList petsAvail, petTypes;
private JScrollPane sPane, sPane2;
public SelectPanel(Vector petList)
{
this.petList = petList;
this.setLayout(new BorderLayout());
bPanel = new Panel();
nPanel = new Panel();
nPanel.setLayout(new GridLayout(1,2));
bPanel.setLayout(new GridLayout(2,1));
petTypes = new JList(petList);
petTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sPane = new JScrollPane(petTypes);
petList.add(0, "Available pet(s)");
selectList = new Vector();
petsAvail = new JList(selectList);
petsAvail.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sPane2 = new JScrollPane(petsAvail);
selectList.add(0, "Selected pet(s)");
aPets = new JLabel("Available pet(s)");
nPets = new JLabel("Selected pet(s)");
nPets = new JLabel("The number of selected pets:" + numPets);
addPet = new JButton("Add");
remove = new JButton("Remove");
add(petsAvail, BorderLayout.EAST);
add(petTypes, BorderLayout.WEST);
add(nPanel, BorderLayout.SOUTH);
nPanel.add(nPets);
add(bPanel, BorderLayout.CENTER);
bPanel.add(addPet);
bPanel.add(remove);
addPet.addActionListener(new ButtonListener());
remove.addActionListener(new ButtonListener());
// orgranize components for the panel
}
public void updatePetList()
{
petTypes.updateUI();
petsAvail.updateUI();
//This method can refresh the appearance of the list of pets
//by calling updateUI() method for the JList.
//It can be called from the CreatePanel class whenever a new pet type
//is added to the vector and the JList appearence needs to be refreshed.
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object which = event.getSource();
if(which == addPet){
for (int p = 1; p < selectList.size(); p++){
boolean check = false;
if(selectList.contains(petTypes.getSelectedValue())){
check = true;
break;
} else if(check == false){
selectList.addElement(petTypes.getSelectedValue());
petsAvail.updateUI();
numPets++;
}
}
} else if (which == remove){
selectList.removeElement(petsAvail.getSelectedValue());
updatePetList();
numPets--;
}
//When the added button is pushed, the selected pet
//should be added to the right list and the number of
//selected pets is incremented by 1.
//When the remove button is pushed, the selected pet
//should be removed from the right list and the number of
//selected pets is decremented by 1.
//
//Be careful for the cases when no item has been selected.
}
} //end of ButtonListener class
} //end of SelectPanel class
Any insight as to the cause of these errors and what to do about them would be gratefully received.
You're getting that warning because you're using a generic class without specifying the generic type. It looks like your petList vector is supposed to be a vector of Strings. Your declaration of petList should look like
private Vector<String> petList
and somewhere later...
petList = new Vector<String>()
That warning is meant to help you realize that your code might not behave as expected at runtime if you starting mixing types (usually be accident) inside your vector. You can technically add multiple types of objects into your petList vector even though you really only want strings. There's nothing stopping you from adding integers, other classes, or even more vectors into your vector. Sometimes this is done on purpose by a programmer, but most of the time you really only want a single type of object to be usuable in your generic class (the vector in this case). By specifying the type of objects to put into your vector the compiler can help you catch these accidental mixing of types (such as if you tried to put an integer into your petList vector). It's much easier to fix those kinds of problems at compile time instead of trying to figure out what went wrong at runtime.
Read here to learn more about generics in Java:
http://docs.oracle.com/javase/tutorial/java/generics/
Right now, I'm just testing the to make sure the button works...but this is my code for an applet that expands a binomial using Pascal's triangle! I have the equations for the actually figuring out part, I just need to know how to store the information from the JTextFields! Thanks!
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.Action;
public class BinomialExpander extends JApplet implements ActionListener
{
JLabel welcome;
JLabel directions;
JLabel example;
JLabel instructions;
JLabel startOfBinomial;
JLabel plusSign;
JLabel forExponent;
JLabel endOfBinomial;
JTextField txtFirst;
JTextField firstVar;
JTextField txtSecond;
JTextField secondVar;
JTextField exp;
JLabel lblExpanded;
JLabel outputExpanded;
double degreesFahrenheit;
FlowLayout layout;
Timer timer;
Button compute;
private int[] pascal1 = {1,1};
private int[] pascal2 = {1,2,1};
private int[] pascal3 = {1,3,3,1};
private int[] pascal4 = {1,4,6,4,1};
private int[] pascal5 = {1,5,10,10,5,1};
private int[] pascal6 = {1,6,15,20,15,6,1};
private int[] pascal7 = {1,7,21,35,35,21,7,1};
private int[] pascal8 = {1,8,28,56,70,56,28,8,1};
private int[] pascal9 = {1,9,36,84,126,84,36,9,1};
private int[] pascal10 = {1,10,45,120,210,120,45,10,1};
public void init()
{
Container c = getContentPane();
c.setBackground(Color.cyan);
layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
c.setLayout(layout);
setSize(500,175);
welcome = new JLabel("Welcome to the Binomial Expander Applet!");
directions = new JLabel("Enter binomial in the form: '(number)(variable) + (number)(variable)^exponent'.");
example = new JLabel("Example: (4a + 2)^2.");
// instantiate JLabel object for Degrees Fahrenheit
instructions = new JLabel("Enter the first number of your binomial(if there is a variable, add it into the second box):");
// instantiate JTextField object for the degrees fahrenheit
startOfBinomial = new JLabel(" (");
txtFirst = new JTextField(4);
// instantiate JLabel object for Degrees Celesius
firstVar = new JTextField(4);
plusSign = new JLabel(" + ");
txtSecond = new JTextField(4);
secondVar = new JTextField(4);
endOfBinomial = new JLabel(")");
forExponent = new JLabel("^");
forExponent.setFont(new Font("Times New Roman", Font.BOLD, 9));
exp = new JTextField(2);
compute = new Button("Compute!");
compute.addActionListener(this);
lblExpanded = new JLabel("Your expanded binomial is: ");
// JLabel to display the equivalent degrees Celsius
outputExpanded = new JLabel("");
c.add(welcome);
c.add(directions);
c.add(example);
c.add(instructions);
c.add(startOfBinomial);
//CALL the addActionListener() method on the JTextField object
// for the degrees Fahrenheit
txtFirst.addActionListener(this);
// Add the textbox the celsius label and output label
c.add(txtFirst);
c.add(firstVar);
c.add(plusSign);
c.add(txtSecond);
c.add(secondVar);
c.add(endOfBinomial);
c.add(forExponent);
c.add(exp);
c.add(compute);
c.add(lblExpanded);
c.add(outputExpanded);
// timer = new Timer(1, this);
// timer.start();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
}
public String expand()
{
String x = "callingComputing";
return x;
}
}
yourTextField.getText() returns a String you can use as you would any other String, store it in an array, teach it to sing, fly and enjoy life.
Conversely, you can use yourTextField.setText() to display stuff in your JLabel, textfield etc.
JTextField extends JTextComponent, which has API to deal text manipualtion.
As suggested by other answers use setText to replace the current text with new text.
Also read the official tutorial to understand How to Use Text Fields
JTextField txtName = new JTextField();
JButton btn = new JButton();
in the action performed method add this
String name = txtname.getText();
this statement returns the text that is entered in the text field the second before you click the button
You create a class where you'll store the data, and create an object of that in the Frame class, i.e. the class that'll provide the GUI to the data class, then in the action listener of the submit button of the frame assign the getText() returned string to the object's field
for eg: you want to take input name and age from the text field,
create a Person class
public class Person{
public String name;
public int age;
}
now create a GUI class
public PersonFrame extends JFrame{
public person;
public PersonFrame(){
person = new Person();
JTextField txtName = new JTextField();
JButton btn = new JButton();
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
person.name = txtName.getText();
person.age = Integer.parseInt(txtAge.getText()); //as the textfield returns a String always
}
});
}
}
and avoid using
if (event.getSource() == compute)
{
outputExpanded.setText(expand());
}
If you have 100 button it'll be foolish to write nested if-else statements to check which button generated the event!!
remember that swing is designed for providing the user interface and you need an object of a class for storing the data!
for java tutorial visit here