getText wont work on a JTextField for some reason - java

Here is my code
Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
import CourseProject.General.exitApp;
public class Options extends JPanel{
private JLabel changeLabel;
private JTextField changeName;
private JButton setName;
private JButton exitButton;
public Options(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
c.insets = new Insets(10, 10, 10, 10);
changeLabel = new JLabel("Change Company Name:");
changeName = new JTextField(10);
setName = new JButton("Set New Name");
exitButton = new JButton("Exit");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
add(changeLabel, c);
c.gridx = 0;
c.gridy = 1;
add(changeName, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
add(setName, c);
setName.addActionListener(new setNameAction());
c.gridx = 1;
c.gridy = 2;
add(exitButton, c);
exitButton.addActionListener(new exitApp());
exitButton.setSize(40,40);
}
static class setNameAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str = "";
str = changeName.getText();
}
}
static class exitApp implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
I'm specifically having a problem with this part of the code
static class setNameAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str = "";
str = changeName.getText();
}
}
Its asking to me set changeName to a static variable. This wouldnt make sense because I'm trying to capture user input.

You inner class is declared static...
static class setNameAction ...
Remove the static reference from the class declaration if you want to be able to reference the instance fields of the outer class...
Otherwise you will be required to pass an instance of Options or JTextField to the setNameAction class.
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Related

Trouble assigning listener to class

My problem consists in inexplicable inability listen to one of my classes.
The software is a java swing-based desktop application, where the JFrame's child class called MainFrame is listening to multiple dialogs. All the dialog windows are children of my PDialog class, which carries the listener-related variables and functions. This is what PDialog class looks like:
public class PDialog extends JDialog {
private MainFrameChildrenListener listener;
// Function that assigns its parameter to local listener value "listener setter"
public void addMainFrameChildrenListener(MainFrameChildrenListener listener) {
this.listener = listener;
}
public void removeMainFrameChildrenListener() {
this.listener = null;
}
public void firePDialogEvent(MainFrameChildrenEventObject event) {
this.listener.dialogEventOccured(event);
}
// This method was useful when I tried to debug with System.out.println() method
public String retrieveListenerInformation(){
if(listener == null){
return "No listener loaded";
}
return this.listener.toString();
}
}
So I have created 3 dialogs that I listen to successfully using functions they inherited as PDialog's children classes. The MainFrame class implements MainFrameChildrenListener listener object and it is passed as listener to the dialogs in its constructor:
public class MainFrame extends JFrame implements MainFrameChildrenListener {
private PDialogCustomer dialogCustomer = new PDialogCustomer();
private PDialogOrder dialogOrder = new PDialogOrder();
private PDialogProduct dialogProduct = new PDialogProduct();
private PDialogMaterial dialogMaterial = new PDialogMaterial();
public MainFrame(){
dialogMaterial.addMainFrameChildrenListener(this);
dialogCustomer.addMainFrameChildrenListener(this);
dialogOrder.addMainFrameChildrenListener(this);
dialogProduct.addMainFrameChildrenListener(this);
System.out.println("Material dialog: " + dialogMaterial.retrieveListenerInformation());
System.out.println("Customer dialog: " + dialogCustomer.retrieveListenerInformation());
System.out.println("Order dialog: " + dialogOrder.retrieveListenerInformation());
System.out.println("Product dialog: " + dialogProduct.retrieveListenerInformation());
}
Surprisingly after the launch of the application the console outputs the PDialog.retrieveListenerInformation() instruction and this is what it looks like:
Material dialog: No listener loaded
Customer dialog: view.MainFrame[-deleted the .toString() rubbish to keep things short-]
Order dialog: view.MainFrame[-deleted the .toString() rubbish to keep things short-]
Product dialog: view.MainFrame[-deleted the .toString() rubbish to keep things short-]
And if I try to fire the listener event I get null pointer exception for the PDialog.firePDialogEvent() method.
I have tried to pass the listener to the PDialogMaterial class through its constructor, I even tried to create new method only within PDialogMaterial class to pass the listener and with no luck. The only way I was able to make things work was create new MainFrameChildrenListener variable which was declared public (eek!) and accessed it directly (eeeeek!) from MainFrame constructor like so:
public class PDialogMaterial extends PDialog{
public MainFrameChildrenListener testListener;
}
public class MainFrame extends JFrame implements MainFrameChildrenListener{
public MainFrame(){
dialogMaterial.testListener = this;
dialogCustomer.addMainFrameChildrenListener(this);
dialogOrder.addMainFrameChildrenListener(this);
dialogProduct.addMainFrameChildrenListener(this);
}
}
Is there any explanation as to why 3 out of 4 classes that all inherited identical listener-handling methods behave differently than the fourth class? What could I be missing?
Comment followup:
The complete code for PDialogMaterial (not working):
package view.dialogs;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import view.listeners.MainFrameChildrenEventObject;
import view.listeners.MainFrameChildrenListener;
import view.utils.DoubleFormatCheck;
public class PDialogMaterial extends PDialog {
private static final long serialVersionUID = 6190469565649183032L;
// private PMaterialFabricObject fabricObject;
public static final int FABRIC_MASK = 0;
public static final int STRAP_MASK = 1;
public static final int PARTS_MASK = 2;
public static final int THREAD_MASK = 3;
private String[] fabricMaterialList = { "Cotton", "Brocate", "Satin", "Synthetic" };
private String[] fabricColorsList = { "Red", "Green", "Blue", "Purple", "Gray", "Yellow", "Black", "Khakhi",
"Carcaline" };
private MainFrameChildrenListener listener;
private GridBagConstraints gc = new GridBagConstraints();
private Dimension size = new Dimension(300, 300);
private DoubleFormatCheck dfc = new DoubleFormatCheck();
private JTextField nameField = new JTextField(8);
private JTextField priceField = new JTextField(6);
private JTextField widthField = new JTextField(6);
private JTextField vendorField = new JTextField(8);
private JButton okButton = new JButton("Ok");
private JButton cancelButton = new JButton("Cancel");
private DefaultComboBoxModel<String> fabricMaterialComboBoxModel = new DefaultComboBoxModel<String>(
fabricMaterialList);
private DefaultComboBoxModel<String> materialColorComboBoxModel = new DefaultComboBoxModel<String>(
fabricColorsList);
private JComboBox<String> fabricMaterialComboBox = new JComboBox<String>(fabricMaterialComboBoxModel);
private JComboBox<String> fabricColorComboBox = new JComboBox<String>(materialColorComboBoxModel);
public PDialogMaterial(){
}
public void addMainFrameChildrenListener(MainFrameChildrenListener listener) {
this.listener = listener;
}
public void removeMainFrameChildrenListener() {
this.listener = null;
}
public void firePDialogMaterialEventOccured(MainFrameChildrenEventObject event) {
this.listener.dialogEventOccured(event);
}
public ImageIcon getPicture(String path) {
URL link = this.getClass().getResource(path);
ImageIcon icon = new ImageIcon(link);
return icon;
}
public void setFabricMask() {
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 1;
gc.gridheight = 1;
gc.weightx = 1;
gc.weighty = 1;
gc.anchor = GridBagConstraints.CENTER;
// First line - picture
gc.gridwidth = 2;
this.add(new JLabel(getPicture("/images/material_32pos.gif")), gc);
gc.gridwidth = 1;
// Second line - name
gc.gridy++;
this.add(new JLabel("Name: "), gc);
gc.gridx++;
this.add(nameField, gc);
// Third line - material
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Material: "), gc);
gc.gridx++;
this.add(fabricMaterialComboBox, gc);
// Fourth line - vendor name
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Vendor: "), gc);
gc.gridx++;
this.add(vendorField, gc);
// Fifth line - predominating color
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Predominaing color: "), gc);
gc.gridx++;
this.add(fabricColorComboBox, gc);
// Sixth line - price
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Price per square meter: "), gc);
gc.gridx++;
this.add(priceField, gc);
// Seventh line - control buttons
gc.gridx--;
gc.gridy++;
this.add(okButton, gc);
gc.gridx++;
this.add(cancelButton, gc);
}
public void setStrapMask() {
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 1;
gc.gridheight = 1;
gc.weightx = 1;
gc.weighty = 1;
gc.anchor = GridBagConstraints.CENTER;
// First line - picture
gc.gridwidth = 2;
this.add(new JLabel(getPicture("/images/material_32pos.gif")), gc);
gc.gridwidth = 1;
// Second line - name
gc.gridy++;
this.add(new JLabel("Name: "), gc);
gc.gridx++;
this.add(nameField, gc);
// Third line - strap width
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Width: "), gc);
gc.gridx++;
this.add(widthField, gc);
// Fourth line - predominating color
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Predominaing color: "), gc);
gc.gridx++;
this.add(fabricColorComboBox, gc);
// Fifth line - strap price
gc.gridx--;
gc.gridy++;
this.add(new JLabel("Price per meter: "), gc);
gc.gridx++;
this.add(priceField, gc);
// Sixth line - control buttons
gc.gridx--;
gc.gridy++;
this.add(okButton, gc);
gc.gridx++;
this.add(cancelButton, gc);
}
public void constructPDialogMaterial(int maskType){
this.setLayout(new GridBagLayout());
this.setLocationRelativeTo(this.getParent());
this.setDefaultCloseOperation(PDialog.DISPOSE_ON_CLOSE);
this.setSize(size);
this.setResizable(false);
this.setVisible(false);
this.setIconImage(getPicture("/images/material_32pos.gif").getImage());
this.nameField.setBackground(this.getBackground());
this.vendorField.setBackground(this.getBackground());
this.priceField.setBackground(this.getBackground());
switch (maskType) {
case PDialogMaterial.FABRIC_MASK:
this.setTitle("Fabric material");
setFabricMask();
break;
case PDialogMaterial.STRAP_MASK:
this.setTitle("Straps");
setStrapMask();
break;
// TODO
default:
System.out.println("Oh noes! Something happend!");
}
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String priceString = dfc.removeWhitespacesAndSwapCommas(priceField.getText());
if(dfc.testDoubleFormat(priceString)){
Double price = Double.valueOf(priceString);
MainFrameChildrenEventObject eventObject = new MainFrameChildrenEventObject(okButton, vendorField.getText(), nameField.getText(),
(String)materialColorComboBoxModel.getSelectedItem(), (String)materialColorComboBoxModel.getSelectedItem(),
price, PDialog.MATERIAL_EVENT_FABRIC);
firePDialogEvent(eventObject);
dispose();
}
else{
JOptionPane.showMessageDialog(PDialogMaterial.this, "Wrong price format", "Format error",
JOptionPane.WARNING_MESSAGE);
}
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
}
The complete code for PDialogCustomer (working example):
package view.dialogs;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import view.listeners.MainFrameChildrenEventObject;
public class PDialogCustomer extends PDialog {
private static final long serialVersionUID = 8431597688560531951L;
private GridBagConstraints gc = new GridBagConstraints();
private URL imageLink;
private URL iconLink;
// New customer GUI setup
JLabel nameLabel = new JLabel("Customer name: ");
JLabel addressLabel = new JLabel("Customer address: ");
JLabel dogLabel = new JLabel("Dog name: ");
JTextField nameField = new JTextField(8);
JTextField streetField = new JTextField(8);
JTextField cityField = new JTextField(8);
JTextField countryField = new JTextField(8);
JTextField dogField = new JTextField(8);
JButton okBttn = new JButton("Ok");
JButton cancelBttn = new JButton("Cancel");
// ________________________________________________________
public PDialogCustomer() {
String imagePath = "/images/customer_32pos.gif";
String iconPath = "/images/customer_16pos.gif";
this.iconLink = getClass().getResource(iconPath);
this.setIconImage(new ImageIcon(iconLink).getImage());
this.imageLink = getClass().getResource(imagePath);
this.setTitle("New customer");
nameField.setBorder(BorderFactory.createEtchedBorder());
nameField.setBackground(this.getBackground());
streetField.setBorder(BorderFactory.createTitledBorder("Street"));
streetField.setBackground(this.getBackground());
cityField.setBorder(BorderFactory.createTitledBorder("City"));
cityField.setBackground(this.getBackground());
countryField.setBorder(BorderFactory.createTitledBorder("Country"));
countryField.setBackground(this.getBackground());
dogField.setBorder(BorderFactory.createTitledBorder("Dogs name"));
dogField.setBackground(this.getBackground());
gc.weightx = 1;
gc.weighty = 1;
gc.gridheight = 1;
gc.gridwidth = 2;
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.CENTER;
add(new JLabel(new ImageIcon(imageLink)));
gc.gridwidth = 1;
gc.gridy++;
add(nameLabel, gc);
gc.gridx++;
add(nameField, gc);
gc.gridy++;
gc.gridx--;
add(addressLabel, gc);
gc.gridx++;
add(streetField, gc);
gc.gridy++;
add(cityField, gc);
gc.gridy++;
add(countryField, gc);
gc.gridy++;
gc.gridx--;
add(dogLabel, gc);
gc.gridx++;
add(dogField, gc);
gc.gridy++;
gc.gridx--;
add(okBttn, gc);
gc.gridx++;
add(cancelBttn, gc);
okBttn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String address = streetField.getText() + ", " + cityField.getText() + ", " + countryField.getText();
firePDialogEvent(new MainFrameChildrenEventObject(okBttn, nameField.getText(), address,
dogField.getText(), PDialog.CUSTOMER_EVENT));
dispose();
}
});
cancelBttn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
}
The problem in the offending class is that it redeclares a
private MainFrameChildrenListener listener;
field. So you have two private fields, one in the superclass, and one in the subclass, with the same name. The one in the subclass overrides the one in the superclass when you are in methods of that subclass, but is not visible for methods defined in the superclass. Remove the listener field in the subclass, and it should work.
As Markus already said, in your not-working listener you are hiding the listener-field and redeclare the setter.
To illustrate this problem, I built up a small example:
import java.util.Arrays;
public class HiddenField {
static abstract class Base {
String field = "BASE";
// sets the base's field
void setField(String set) {
this.field = set;
}
// ensures not to be overridden and returns the base's field.
final String getField() {
return this.field;
}
// access the field by getter (ensured to be base) and field 'field'
#Override
public String toString() {
return this.getClass().getSimpleName() + ": get()->" + getField() + " vs. field->" + field;
}
}
static class ProperExtension extends Base {
/* no need to override the base's field */
}
static class HidingExtension extends Base {
// this field isn't related to the one in Base, but has the same name!
String field = "HIDING";
// the setter is overridden (exact copy!) but because of the same-named
// field in this extending class, it sets this class's field and not the
// one in the base-class!
#Override
void setField(String set) {
this.field = set;
}
// copied the toString from above - here it is accessing the
// base-class's field via getter and this class's field directly.
#Override
public String toString() {
return this.getClass().getSimpleName() + ": get()->" + getField() + " vs. field->" + field;
}
}
public static void main(String[] args) {
// build both types of extending classes and invoke their setters
Arrays.asList(new ProperExtension(), new HidingExtension()).forEach(obj -> {
System.out.println("before ~> " + obj);
obj.setField("SET");
System.out.println("after ~> " + obj + "\n");
});
}
}

JButton listener not firing

I seperated my codes into MVC model and now my confirm button action listener is not printing the username and password even though I added a Actionlistener for it. please help thanks.
Codes
LoginDialog.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class LoginDialog extends JDialog {
private JLabel nameLabel;
private JLabel passwordLabel;
private JTextField usernameTF;
private JPasswordField passwordTF;
private JButton confirmBtn;
private JButton cancelBtn;
private JPanel topPanel;
private JPanel buttonPanel;
private GridBagConstraints gbc;
public LoginDialog() {
this.setTitle("Authentication");
topPanel = new JPanel(new GridBagLayout());
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
nameLabel = new JLabel("Name : ");
passwordLabel = new JLabel("Password : ");
usernameTF = new JTextField();
passwordTF = new JPasswordField();
confirmBtn = new JButton("Confirm");
cancelBtn = new JButton("Cancel");
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
topPanel.add(nameLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
topPanel.add(usernameTF, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
topPanel.add(passwordLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
topPanel.add(passwordTF, gbc);
this.add(topPanel);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void showLoginDialog() {
LoginDialog ld = new LoginDialog();
ld.setSize(400, 150);
ld.setVisible(true);
ld.setLocationRelativeTo(null);
}
public String getUsername() {
return usernameTF.getText();
}
public String getPassword() {
return new String(passwordTF.getPassword());
}
public void confirmBtnListner(ActionListener listener) {
confirmBtn.addActionListener(listener);
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
private LoginDialog loginDialog;
public Controller(LoginDialog loginDialog) {
this.loginDialog = loginDialog;
loginDialog.showLoginDialog();
loginDialog.confirmBtnListner(new BtnListener());
}
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(loginDialog.getUsername());
System.out.println(loginDialog.getPassword());
}
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog();
new Controller(loginDialog);
}
}
You are having two instances of LoginDialog class.
One you are creating in your controller and the other one is in your LoginDialog#showLoginDialog() method.
Let's list them:
1st instance - In the controller class named `loginDialog`
2nd instance - In the `LoginDialog` class named `ld`
Here ld is an object created within loginDialog object. But they are two different JDialog objects. When you call
loginDialog.showLoginDialog()
another object ld is created from within the method. The JDialog refered is set to visible by:
ld.setVisible(true)
So now,
Object `ld` is visible
And Object `loginDialog` is NOT yet visible as you havent done `loginDialog.setVisible(true)` yet.
Now are adding the ActionListener to the button within loginDialog object, which is not yet visible. While there is no ActionListener added to the Button within ld object.
Final conclusion:
Object ld is visible, but button within it has NO ActionListener.
Object loginDialog is NOT yet visible. But the button within it has an ActionListener.
The button you are clicking is a part of ld object which has NO action listener associated to it.
The button which has an ActionListener associated to it is a part of loginDialog object which is NOT visible.
Wanna check if I am right?
Just add these lines in your controller constructor:
loginDialog.setVisible(true);
loginDialog.setSize(400, 150);
loginDialog.setLocationRelativeTo(null);
I won't give you the full solution as we don't spoonfeed here on stack overflow. So it's a challange for you to adjust your code accordingly. :)
The method showLoginDialog() creates a new instance of your dialog, which does not have the actionlistener.
fix: don't create a new instance - use the one you have.
public void showLoginDialog() {
setSize(400, 150);
setVisible(true);
setLocationRelativeTo(null);
}

I can't seem to get this inheritance to work

I have a tabbed application. One of the tabs you can enter the name of the company and it should change it to whatever you typed into the other tab. Here are both classes.
On this code its telling me to change About.setCompanyName(str); to static
The error that I am seeing is "Cannot make a static reference to the non-static method SetCompanyName(String) from the type About"
package CourseProject;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class Options extends JPanel{
private JLabel changeLabel;
private JTextField changeName;
private JButton setName;
private JButton exitButton;
public Options(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
c.insets = new Insets(10, 10, 10, 10);
changeLabel = new JLabel("Change Company Name:");
changeName = new JTextField("", 10);
setName = new JButton("Set New Name");
exitButton = new JButton("Exit");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
add(changeLabel, c);
c.gridx = 0;
c.gridy = 1;
add(changeName, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
add(setName, c);
setName.addActionListener(new setNameAction());
c.gridx = 1;
c.gridy = 2;
add(exitButton, c);
exitButton.addActionListener(new exitApp());
exitButton.setSize(40,40);
}
class setNameAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str;
str = changeName.getText();
About.SetCompanyName(str);
changeName.setText("");
}
}
class exitApp implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
}
And here is "About" which contains my setter. It asks me to make the method and variable static but I know this wont work because I am wanting to change it
package CourseProject;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JPanel{
private JLabel programInfoLabel;
private JLabel programInfo;
private JLabel programmerLabel;
private JLabel programmer;
private JLabel companyLabel;
JLabel company;
public String companyName = "enter a company name in options";
public About() {
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
c.insets = new Insets(10, 10, 10, 10);
programInfoLabel = new JLabel("Program Information:");
programInfo = new JLabel("This is the CIS355A course project application");
programmerLabel = new JLabel("Programmer:");
programmer = new JLabel("Kevin Rankin");
companyLabel = new JLabel("Company Name:");
company = new JLabel(companyName);
c.gridx = 0;
c.gridy = 0;
add(programInfoLabel, c);
c.gridx = 1;
c.gridy = 0;
add(programInfo, c);
c.gridx = 0;
c.gridy = 1;
add(programmerLabel, c);
c.gridx = 1;
c.gridy = 1;
add(programmer, c);
c.gridx = 0;
c.gridy = 2;
add(companyLabel, c);
c.gridx = 1;
c.gridy = 2;
add(company, c);
}
public void SetCompanyName(String str){
company.setText(str);
}
}
On this line
About.SetCompanyName(str);
You're calling SetCompanyName statically (by using the class name "About"). You should either make the method static (which is not the same as "final"; you seem to be confused about this) or create an instance of the About class first, like so:
About myAboutObject = new About();
myAboutObject.SetCompanyName(str);

Trying to use GridBagConstraints in a standalone frame class

The following code is going to end up being one of the panels for a tabbed panel. I've only used GridBagConstraints once and it was easier because I had a Pane. I would just use something like
mainFrame.getContentPane().add(panel, BorderLayout.NORTH);
What if I wanted to us the gridbaglayout for this code. I don't have a pane. How could I accomplish adding GridBagConstraints?
package Week4;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class OfficeAreaCalculator extends JPanel{
private JButton calculateButton;
private JTextField lengthField;
private JTextField widthField;
private JTextField areaField;
private JLabel lengthLabel;
private JLabel widthLabel;
private JLabel areaLabel;
public OfficeAreaCalculator(){
setBackground(Color.white);
lengthLabel = new JLabel("Enter the length of the office:");
widthLabel = new JLabel("Enter the width of the office:");
areaLabel = new JLabel("Office area:");
lengthField = new JTextField(5);
widthField = new JTextField(5);
areaField = new JTextField(5);
areaField.setEditable(false);
calculateButton = new JButton("Calculate");
add(lengthLabel);
add(lengthField);
add(widthLabel);
add(widthField);
add(areaLabel);
add(areaField);
add(calculateButton);
calculateButton.setMnemonic('C');
CalculateButtonHandler chandler = new CalculateButtonHandler();
calculateButton.addActionListener(chandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
areaField.addFocusListener(fhandler);
}
class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
try{
DecimalFormat num = new DecimalFormat(",###.##");
double width, length, area;
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);
area = length * width;
areaField.setText(num.format(area));
}
catch( Exception d){
lengthField.setText("Invalid");
widthField.setText("Invalid");
}
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if (e.getSource() == lengthField || e.getSource() == widthField)
{
areaField.setText("");
}
else if (e.getSource() == areaField)
{
calculateButton.requestFocus();
}
}
public void focusLost(FocusEvent e)
{
if (e.getSource() == widthField)
{
calculateButton.requestFocus();
}
}
}
}
I think I may have figured out the answer to my own question. Before I start messing with the grid coordinates I need to do it like this:
package Week6;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Index extends JPanel{
private JLabel searchLabel;
private JTextField searchField;
private JLabel charLabel;
private JTextField charField;
public Index(){
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.NORTH;
setBackground(Color.WHITE);
super.setLayout(gridbag);
searchLabel = new JLabel("Enter text to be searched:");
searchField = new JTextField("");
charLabel = new JLabel("Exter a character:");
charField = new JTextField("");
c.insets = new Insets(10, 10, 10, 10);
c.gridx = 0;
c.gridy = 0;
add(searchLabel, c);
c.gridx = 1;
c.gridy = 0;
add(searchField, c);
c.gridx = 0;
c.gridy = 1;
add(charLabel, c);
c.gridx = 1;
c.gridy = 1;
add(charField, c);
}
}

Actionlistener not functioning properly

I'm running into a problem, I believe with the actionlistener. The weird thing is that it works on some computers and not on others. All computers are running JE7.1. So, on some systems, it works flawlessly, the user enters text, presses enter and the text is appended to the JTextPane and updates the static userInput variable. On other computers though, text is appended, but the variable never seems to update.
For example:
user types in "Hello"
"Hello is appened to the JtextPane and the static variable userInput = "Hello"
Am I missing something very silly here? Thank you in advance.
package com.core;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.text.*;
public class GUI {
public static JFrame f;
private static JPanel topPanel = new JPanel();
private static JTextPane textArea = new JTextPane();
public static JTextField inputText = new JTextField();
private static String userInput = "";
private static Player player;
public static JPanel sidePanel = new JPanel();
public JFrame buildFrame(){
f = new JFrame("AMSA World");
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridBagLayout());
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String text = inputText.getText();
if(!text.equals("")){
appendToPane(text + "\n\n", Color.blue);
inputText.setText("");
if(text.startsWith("use ")){
ArrayList<Item> inventory = player.getInventory();
String key = text.substring(4);
boolean found = false;
for(Item i : inventory){
if(i.getName().equalsIgnoreCase(key)){
found = true;
i.use();
break;
}
}
if(!found){
appendToPane("Item does not exist in your iventory.\n\n", Color.black);
}
}
if(text.startsWith("inventory")){
ArrayList<Item> inventory = player.getInventory();
if(inventory.size() > 0){
for(Item i : inventory){
appendToPane(i.getName() +"\n", Color.darkGray);
}
}
else
appendToPane("Your iventory is empty.\n\n", Color.black);
appendToPane("#", Color.blue);
}
else{
userInput = text;
}
}
}
};
inputText.addActionListener(listener);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5,5,5,5);
c.weightx = 1.0;
c.gridwidth = 3;
c.weighty = 0.025;
c.gridx = 0;
c.gridy = 0;
f.add(topPanel, c);
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 1;
f.add(scrollPane, c);
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridwidth = 1;
c.gridx = 2;
c.gridy = 1;
f.add(sidePanel, c);
sidePanel.setVisible(false);
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0.025;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 2;
f.add(inputText, c);
f.setVisible(true);
return f;
}
public static JTextField getTextField(){
return inputText;
}
public static void toggleTextField(boolean value){
inputText.setEnabled(value);
}
public static String getUserInput(){
return userInput;
}
public static void setUserInput(String s){
userInput = s;
}
public static JPanel getTopPanel(){
return topPanel;
}
public static JPanel getSidePanel(){
return sidePanel;
}
public static void setPlayer(Player p){
player = p;
}
public static void appendToPane(String msg, Color c){
if(inputText.isEnabled()){
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
textArea.setCharacterAttributes(aset, false);
textArea.replaceSelection(msg);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
}
To (try) to answer your question, I'm guessing you are running into multi-thread issues. Swing events run in their own thread thread, the Event Dispatch Thread. If you are accessing the variable from another thread, you will run into occasional situations where the variables are not synchronized between threads.
In the bigger picture, taking shortcuts in writing Java code will generally end up costing you a lot of time and effort. Placing your entire UI in static variables with static methods is not a good idea. Take the time to instantiate an instance. Beyond that, I'm guessing you didn't start the UI using SwingUtilities.invokeLater(). Read the Swing Tutorial, which I linked above. Swing works well, but it is not simple.

Categories

Resources