I have three JTextFields, when the buy button is pressed the associated listener should retrieve the text from the text fields and use it to update the table.
The issue is that when I press the buy button it tries to use the data in the JTextFields in David's tab as opposed to the one I'm currently on. If I made another tab named "Jack" it would then try to be using jacks. The code to create the text boxes is as follows:
JLabel label2 = new JLabel("Name Of Share:");
tabPanel.add(label2);
textFieldName = new JTextField("", 15);
textFieldName.setColumns(10);
textFieldName.setToolTipText("Enter Number of shares here");
tabPanel.add(textFieldName);
The listener for the buy button:
int quantity = 0;
if (e.getActionCommand().equals("Buy")) {
String name = view.getTextFieldName().getText();
String ticker = view.getTextFieldTicker().getText().toUpperCase();
try{
quantity = Integer.parseInt(view.getTextFieldNumber().getText());
}catch(NumberFormatException er){
}
view.buy(ticker, name, quantity);
}
Everything works fine if I only have one tab but once I introduce more that's when the issues start.
Can anyone suggest a way to fix this so I can get data from the text boxes of only the tab I am on?
I should have mentioned view is of type MainGUI a Class I have created, which is used for building the GUI which has the fields:
public class MainGUI extends JFrame implements Observer {
private JTabbedPane tabbedPane;
private JTable table;
private JTextField textFieldTicker;
private JTextField textFieldName;
private JTextField textFieldNumber;
private DefaultTableModel model;
private PortfolioManager pm;
private JLabel tValue;
to create a Tab the code used is:
JPanel topPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
JSplitPane splitPanelbtm = new JSplitPane(JSplitPane.VERTICAL_SPLIT, labelPanel, buttonPanel);
JSplitPane splitPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, splitPanelbtm){
private final int location = 500;
{setDividerLocation(location);}
#Override
public int getDividerLocation(){
return location;
}
#Override
public int getLastDividerLocation(){
return location;
}
};
splitPanel.setEnabled( false );
splitPanel.setDividerSize(0);
splitPanelbtm.setEnabled( false );
splitPanelbtm.setDividerSize(0);
splitPanelbtm.setBorder(null);
splitPanel.setBorder(null);
tabbedPane.add(tabName, splitPanel);
tabbedPane.setName(tabName);
this.add(tabbedPane);
this.setVisible(true);
createLabelsButtons(topPanel);
createTable(topPanel);
tValue = new JLabel("Total Value for " + tabbedPane.getName() + " is: $ ");
labelPanel.add(tValue);
createTabButtons(buttonPanel);
Related
I have a class that has 4 private attributes, and through a JComboBox selection, I want to modify them through calling a procedure. However, it seems like even though the JComboBox appears with the selection, the attributes that are shown don't change.
public class PanneauVehicule extends JPanel {
private String[] vehicules;
private int majCarburant;
private int majPassager;
public class PanneauVehicule extends JPanel {
//Main constructor
public PanneauVehicule(){
//Creates a JPanel
super();
//Sets layout as BorderLayout
setLayout(new BorderLayout());
initListeVehicule();
initLabels();
}
public void initListeVehicule(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
//Keep in mind the comboBox does appear with the right selections
add(vehiculesList,BorderLayout.NORTH);
//Here's where it doesnt work.
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
majInfo(2,4);
}
});
}
public void majInfo(int test1, int test2){
this.majCarburant = test2;
this.majPassager = test1;
}
public void initLabels(){
JPanel panneauBas = new JPanel();
panneauBas.setLayout(new GridLayout(2,1,5,5));
JLabel labelCarburant = new JLabel();
labelCarburant.setText("Type de caburant: " + this.majCarburant);
JLabel labelPassagers = new JLabel();
labelPassagers.setText("Nb de passagers: " + this.majPassager);
panneauBas.add(labelPassagers);
panneauBas.add(labelCarburant);
add(panneauBas, BorderLayout.SOUTH);
panneauBas.setBackground(Color.WHITE);
}
After that, I use another procedure that will make majCarburant and majPassager appear on screen. However their values are shown as default (0). I can make their values change manually without using an ActionListener, but the task at hand requires me to use one.
I've been trying ways to just simply change the values through actionListener directly,
You don't invoke an ActionListener directly. Once an ActionListener has been added to the combo box, you can invoke:
setSelectedItem(...) or
setSelectedIndex(...)
on the combo box and the combo box will invoke the ActionListener.
I found the solution after a few more hours of meddling. I just integrated the procedure that creates labels into initListeVehicule, and from there the ActionListener can access the labels to modify their texts.
public void initListeVehiculeInfos(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
add(vehiculesList,BorderLayout.NORTH);
JPanel panneauBas = panelGenerator();
//these setTexts serve as default values before doing your first selection
final JLabel carb = labelGenerator();
carb.setText("Carburant: Kérosène");
final JLabel passager = labelGenerator();
passager.setText("Nb Passager: 110");
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
InterfaceVehicules info = FabriqueVehicule.obtenirVehicule(vehiculesList.getSelectedIndex());
carb.setText("Carburant: " + info.tabNomTypeCarburant[info.getTypeCarburant()] );
passager.setText("Nb Passagers: " + info.getNbPassagersMax());
}
});
panneauBas.add(carb);
panneauBas.add(passager);
add(panneauBas, BorderLayout.SOUTH);
}
I have tried everything possible to fix this error. Every time I compile the program, the error
KiloConverter.java:25: error: cannot find symbol
How to resolve this error?
import javax.swing.*; // Needed for swing classes
public class KiloConverter extends JFrame
{
private JPanel panel;
private JLabel messageLabel;
private JTextField kiloTextField;
private JButton calcButton;
private final int WINDOW_WIDTH = 310;
private final int WINDOW_HEIGHT = 100;
//constructor
public KiloConverter()
{
setTitle("Kilometer Converter");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//bulid the panel and add it to the frame
buildPanel();
//Add the panel to the frame's content page
add(panel);
setVisible(true);
}
//the bulid panel method adds a label, a text field,
//and a button to a panel
private void bulidPanel()
{
//Create a label to display instructions.
messageLabel = new JLabel("Enter a distance " + "in kilometers");
//Create a text field 10 characters wide.
kiloTextField = new JTextField(10);
//create a button with the caption CALCULATE
calcButton = new JButton("Calculate");
//create a JPanel object and let the panel field reference it
panel = new JPanel();
//Add the label, text fieldm and button components to the panel
panel.add(messageLabel);
panel.add(kiloTextField);
panel.add(calcButton);
}
public static void main (String[] args)
{
new KiloConverter();
}
}
The source code seen, incorrectly spells 'build' as 'bulid' in two comments and one method name. Correcting the spelling in the method name should fix the problem, but change all three instances.
I know I don't have a frame but everything shows except my JPasswordField (password bar) and my JTextField (username bar) I'm just trying to add a "username" and "password" bar at the bottom of the page but the bars won't show.
Thanks for the help although it seems as everything here receives negatives. lol.
public class test extends JFrame {
private JLabel jl;
private JLabel paypalLogo;
private JButton money1;
private JButton money2;
private JButton money3;
private JButton money4;
private JButton money5;
private JButton money6;
private JButton custom;
private JTextField user;
private JButton login;
private JPasswordField pass;
public test(){
super("PayPal Money Generator");
setLayout(new FlowLayout());
this.setLayout(null);
Icon logo1 = new ImageIcon(getClass().getResource("res/paypal.png"));
paypalLogo = new JLabel(logo1);
paypalLogo.setBounds(50,-50,200,200);
add(paypalLogo);
money1 = new JButton("$5");
money1.setBounds(85,100,35,35);
add(money1);
money2 = new JButton("$10");
money2.setBounds(200,100,35,35);
add(money2);
money3 = new JButton("$25");
money3.setBounds(67,200,50,35);
add(money3);
money4 = new JButton("$50");
money4.setBounds(200,200,50,35);
add(money4);
money5 = new JButton("$200");
money5.setBounds(50,300,70,40);
add(money5);
money6 = new JButton("$500");
money6.setBounds(200,300,70,40);
add(money6);
user = new JTextField(15);
add(user);
pass = new JPasswordField(15);
add(pass);
login = new JButton("Login");
add(login);
/*how to make logo in button test
Icon b = new ImageIcon(getClass().getResource("res/paypal.png"));
custom = new JButton("", b);
custom.setBounds(10,10,100,100);
add(custom);
*/
HandlerClass handler = new HandlerClass();
money1.addActionListener(handler);
money2.addActionListener(handler);
money3.addActionListener(handler);
money4.addActionListener(handler);
money5.addActionListener(handler);
money6.addActionListener(handler);
}
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(user.getText().trim().length() == 0 || pass.getText().length() == 0){
JOptionPane.showMessageDialog(null, "Fill");
}else{
if(user.getText().equals("Kleo") || user.getText().equals("Kleo")){
JOptionPane.showMessageDialog(null, "Welcome");
}else{
JOptionPane.showMessageDialog(null, "Denied");
}
}
}
}
private class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent e){
try {
final ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("/res/paypal.png")));
JOptionPane.showOptionDialog(
null,
e.getActionCommand() + ".00 USD has successfully been added to your account!",
"",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE,
icon,
new Object[]{"OK"},
"");
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
When you use a null layout, you the programmer are completely responsible for setting all the locations and sizes of components added to the container. You don't set either of these for your JTextField or JPasswordField. The quick (and wrong) solution is to set their bounds. The better solution is to use layout managers.
The use of a null layout is the main cause of your problem...
this.setLayout(null);
//...
user = new JTextField(15);
add(user);
pass = new JPasswordField(15);
add(pass);
login = new JButton("Login");
add(login);
Basically when a component is created, it's default size and position are 0x0, meaning that, based on the above code, you components aren't visible because they have no size.
Swing was designed to work with layout managers and there are many good reasons to use them. You don't control the rendering process by which content is rendered to the screen, this will effect things like the font metrics, which will change the size that components needs to be and effect the placement of components around each other...
Short answer, use appropriate layout managers
See Laying Out Components Within a Container for more details
You will be hard pushed to find an experienced Swing developer worth their salt who would advocate the use of null layouts when dealing with forms of this nature.
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
I am hoping someone can spoon feed me this solution. It is part of my major lab for the class, and it really isn't giving me too much since I just don understand how to make a GUI with tabs. I can make a regular program with some sort of GUI, but I've been searching and reading and can't put 2 and 2 because of the whole class part and declaring the private variables. So what I am asking is if someone can make me a main GUI with 5 tabs and put my code into 1 tab so I can learn and put the rest of my codes into the other 4 tabs. So I hope you don't think I want you to give me code when I have the code, I just don't really get the tabs, and we haven't gone over it in class. Here is the code with its own gui, I hope what I type makes sense. I learn code by seeing, and this will help me a bunch.
package landscape;
import javax.swing.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Landscape extends JFrame {
private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JLabel lengthLabel;
private JTextField widthField;
private JLabel widthLabel;
private JTextField depthField;
private JLabel depthLabel;
private JTextField volumeField;
private JLabel volumeLabel;
private JRadioButton builtIn;
private JRadioButton above;
private JTabbedPane panel;
public Landscape()
{
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("Pool", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
//tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
mainFrame.setSize(265,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
JPanel panel = new JPanel();//FlowLayout is default
//Pool
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
panel.add(lengthLabel);
panel.add(lengthField);
panel.add(widthLabel);
panel.add(widthField);
panel.add(depthLabel);
panel.add(depthField);
panel.add(volumeLabel);
panel.add(volumeField);
panel.add(calculateButton);
panel.add(exitButton);
//creating components
calculateButton = new JButton ("Calculate");
exitButton = new JButton ("Exit");
lengthField = new JTextField (5);
lengthLabel = new JLabel ("Enter the length of your pool: ");
widthField = new JTextField (5);
widthLabel = new JLabel ("Enter the width of your pool: ");
depthField = new JTextField (5);
depthLabel = new JLabel ("Enter the depth of your pool: ");
volumeField = new JTextField (5);
volumeLabel = new JLabel ("Volume of the pool: ");
//radio button
ButtonGroup buttonGroup = new ButtonGroup();
builtIn = new JRadioButton ("Built in");
buttonGroup.add(builtIn);
above = new JRadioButton ("Above");
buttonGroup.add(above);
exitButton.setMnemonic('x');
calculateButton.setMnemonic('C');
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
// create the handlers
calculateButtonHandler chandler = new calculateButtonHandler(); //instantiate new object
calculateButton.addActionListener(chandler); // add event listener
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
depthField.addFocusListener(fhandler);
}
class calculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(", ###.##");
double width;
double length;
double depth;
double volume;
double volume2;
double height;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = "0";
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
instring = depthField.getText();
if (instring.equals(""))
{
instring = "0";
depthField.setText("0");
}
depth = Double.parseDouble(instring);
volume = width * length * depth;
volumeField.setText(num.format(volume));
volume2 = width * length * depth;
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if(e.getSource() == lengthField || e.getSource() == widthField || e.getSource() == depthField)
{
volumeField.setText("");
}
else if (e.getSource() == volumeField)
{
volumeField.setNextFocusableComponent(calculateButton);
calculateButton.grabFocus();
}
}
public void focusLost1(FocusEvent e)
{
if(e.getSource() == widthField)
{
widthField.setNextFocusableComponent(calculateButton);
}
}
public void focusLost(FocusEvent e)
{
if(e.getSource() == depthField)
{
depthField.setNextFocusableComponent(calculateButton);
}
}
}
public static void main(String args[])
{
Landscape app = new Landscape();
}
}
Instead of getting the content pane and adding to it, just create a new JPanel and add your stuff to that. Then, add the panel to a new JTabbedPane with whatever title you want, and set the content pane of the JFrame to be the tabbed pane.
Here is a simple example of what you would do:
JPanel panel=new JPanel();//FlowLayout is default
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
//...you get the picture; add all the stuff you already do, just use panel instead of c
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("title", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
You can leave the rest of your code how it is and it should work fine.
The tutorial and its demo are pretty straight forward examples.