Actionlistener not functioning properly - java

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.

Related

How to know which reference is static in Java

I am currently working on GUI of simple food ordering system. I created a button that whenever user clicks it it will go to another frame, however I am facing problem when I want to close the first frame (setVisible(false)).
This is my first frame
public class MainFrame extends JFrame {
private Manager manager = new Manager();
private JPanel titlepane;
private JLabel title;
MainFrame(String name){
setTitle(name);
}
public void content() {
Font titlefont = new Font("Times New Roman", Font.PLAIN, 22);
setLayout(new BorderLayout());
titlepane = new JPanel();
title = new JLabel("Welcome to POS!");
title.setFont(titlefont);
titlepane.add(title);
manager.LoginGUI();
add(titlepane,BorderLayout.NORTH);
add(manager,BorderLayout.CENTER);
}
public void runGUI() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
content();
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
});
}
This is another class where the button is
public class Manager extends JPanel implements ActionListener {
private ArrayList<AccountInfo> manager = new ArrayList<AccountInfo>();
private GridBagConstraints gbc = new GridBagConstraints();
private JLabel id;
private JLabel pw;
private JTextField idfill;
private JTextField pwfill;
private JButton login;
private int isManager = 0;
private String idinput, pwinput;
private int temp = -1;
Manager() {
this.manager.add(new AccountInfo("admin", "1234"));
}
public void addManager(AccountInfo newManager) {
this.manager.add(newManager);
}
public void LoginGUI() {
Font standard = new Font("Times New Roman", Font.PLAIN, 18);
setLayout(new GridBagLayout());
id = new JLabel("ID");
id.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 0;
gbc.ipadx = 10;
gbc.ipady = 10;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(id, gbc);
idfill = new JTextField(10);
idfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(idfill, gbc);
pw = new JLabel("Password");
pw.setFont(standard);
// Alignment
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pw, gbc);
pwfill = new JTextField(10);
pwfill.setFont(standard);
// Alignment
gbc.gridx = 1;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(pwfill, gbc);
login = new JButton("Login");
login.setFont(standard);
login.addActionListener(this);
// Alignment
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
add(login, gbc);
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
MainFrame.setVisible(false); // This is the problem
}
}
private void verify() {
idinput = idfill.getText().trim();
pwinput = pwfill.getText();
for (int i = 0; i < manager.size(); i++) {
if (idinput.equals(manager.get(i).id)) {
temp = i;
}
}
if(temp == -1) {
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
} else if(pwinput.equals(manager.get(temp).password)) {
isManager = 1;
} else
JOptionPane.showMessageDialog(null, "Id or password incorrect, try again");
}
}
(The codes are a bit lengthy as I am not confident that the other part was correct. All I know this has nothing to do with MenuFrame)
I get this error:
Cannot make a static reference to the non-static method setVisible(boolean) from the type Window
It might be my fault where it is not obvious enough for me to know which part of Manager or MainFrame is static. I also came across other posts regarding the same issue but none relates with mine. (Other post was having obvious static method)
Also tried the create an MainFrame object in Manager but it made it worse, please help, thank you!
You indeed need to keep the MainFrame object somewhere accessible, keep a reference to it. For this MVC, Model-View-Controller, is a nice paradigm.
Use MVC
I personally have my main method for swing in a Controller class (so the controller is the application class). It creates the main frame (View) and the controller is passed.
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
controller.setMainFrameVisible(false);
}
}
Controller:
private MainFrame mainFrame;
public setMainFrameVisible(boolean visible) {
MainFrame.setVisible(visible);
}
Pass the MainFrame instance.
However you may also pass the MainFrame:
private final MainFrame mainFrame;
Manager(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void actionPerformed(ActionEvent e) {
verify();
if(isManager == 1) {
MenuFrame menu = new MenuFrame("Menu");
menu.runGUI();
mainFrame.setVisible(false);
}
}
If the panel is inside the MainFrame
((JFrame) getTopLevelAncestor()).setVisible(false);
Tip:
Should the application exit (EXIT_ON_CLOSE), change the default close operation.
MainFrame(String name){
setTitle(name);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}

Can not set text for JTextField from another class

I have ran into yet another issue. I am trying to set the text of a JTextField from another java class, and it does not seem to work.
I have tried the following:
calling the setter from inside the GUI class to .setText with a String. WORKS!
Setting the JTextField to some text so it isnt NULL -failed
Calling another method inside the GUI class, pass the string, then call the setter for the JTextField to set its text to the string. -failed (Just an idea i wanted to play with)
I did insure that the string is passed into the setter method by using a println. WORKED.
From googling around I believe that i have not set the reference to the main GUI?
Here is the GUI Class:
package book;
import book.BookIO;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
*
*
*/
public class UserInterface implements ActionListener {
//Containers
JFrame frame = new JFrame("Ye old Book stoppe");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
//Buttons
JButton processItem = new JButton("Process Item #1");
JButton confirmItem = new JButton("Confirm Item #1");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//TextFields
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField("");
JTextField total = new JTextField();
//Labels
JLabel num = new JLabel("Enter Number of Items in this Order:");
JLabel bookID = new JLabel("Enter Book ID for Item #1:");
JLabel quantityItem = new JLabel("Enter Quantity for Item #1:");
JLabel itemInfo = new JLabel("Item #1:");
JLabel subtotal = new JLabel("Order subtotal for 0 Items(s):");
public void startUI() {
UserInterface gui = new UserInterface();
gui.bookingUI();
}
public void bookingUI() {
//sets windows, and pane in the UI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);
//adding the labels to the panel
c.insets = new Insets(5, 0, 0, 0);
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo, c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal, c);
toppane.setBackground(Color.GREEN);
frame.add(toppane);
//add textfield to panel
c.ipadx = 400;
c.insets = new Insets(5, 10, 0, 0);
c.gridx = 3;
c.gridy = 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(quantity, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(total, c);
//----------------------------------------------------------BUTTOM PANE-------------------------
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.insets = new Insets(5, 5, 5, 5);
b.ipadx = 10;
b.ipady = 10;
b.gridx = 1;
b.gridy = 0;
bottomPane.add(processItem, b);
processItem.addActionListener(this);
b.gridx = 2;
b.gridy = 0;
bottomPane.add(confirmItem, b);
confirmItem.setEnabled(false);
confirmItem.addActionListener(this);
b.gridx = 3;
b.gridy = 0;
bottomPane.add(viewOrder, b);
viewOrder.setEnabled(true);
viewOrder.addActionListener(this);
b.gridx = 4;
b.gridy = 0;
bottomPane.add(finishOrder, b);
finishOrder.setEnabled(true);
finishOrder.addActionListener(this);
b.gridx = 5;
b.gridy = 0;
bottomPane.add(newOrder, b);
newOrder.addActionListener(this);
b.gridx = 6;
b.gridy = 0;
bottomPane.add(exit, b);
exit.addActionListener(this);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.setSize(810, 310);
frame.setVisible(true);
}
//action listener for the buttons
public void actionPerformed(ActionEvent e) {
if (e.getSource() == processItem) {
confirmItem.setEnabled(true);
processItem.setEnabled(false);
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
} else if (e.getSource() == confirmItem) {
processItem.setEnabled(true);
confirmItem.setEnabled(false);
} else if (e.getSource() == viewOrder) {
} else if (e.getSource() == finishOrder) {
} else if (e.getSource() == newOrder) {
} else if (e.getSource() == exit) {
System.exit(0);
}
}
//Creating getters and setters to change the text for the buttons and labels, as well as getting text from the textfields.
public void setProcessItemBtn(int num) {
processItem.setText("Process Item #" + num);
processItem.validate();
processItem.repaint();
}
public void setConfirmItemBtn(int num) {
confirmItem.setText("Confirm Item #" + num);
confirmItem.validate();
confirmItem.repaint();
}
public void setViewOrderBtn(String title) {
viewOrder.validate();
viewOrder.repaint();
}
public void setInfo(String title) {
System.out.println(title);
info.setText(title);
info.validate();
info.repaint();
}
public String getAmount() {
String str = amount.getText();
return str;
}
}
Here is the class with the method call to the setter:
package book;
import book.UserInterface;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.StringTokenizer;
/**
*
*
*/
public class BookIO {
public void readFile(String bookID) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
}
Your error is that you are instantiating a new UserInterface object which is wrong:
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
Your readFile() from BookIO should be like this:
public static void readFile(String bookID, UserInterface userInterface) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
userInterface.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
In your UserInterface class, where you have this:
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
Change the lines to this:
//pass the already created userInterface object.
BookIO.readFile(id.getText(), this);
Note: I have tested this and it worked. Tell me if it doesn't work for you.
You always make a new UserInterface instance
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
That sounds incorrect. Normally you would only have one such unstance (the visible one), and update that one.
Small side-note
if( Objects.equals(tokens[0], bookID)) == true )
can be simplified to
if( Objects.equals(tokens[0], bookID)) )

Proper JFrame components for viewing data entered, and viewing layout correctly on load

As of right now I have all my labels and input fields stacked up the center of the JFrame.
When I run the program the program, the label Business Name appears top center and nothing else appears till I resize the window...
Can anyone tell me why it does this and how to fix it?
Also I would like to add a area to the left side of the JFrame that will display the contact when you click save, what type of component would I use to do this?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;
import javax.swing.*;
public class Driver extends JFrame {
private JFrame f;
private JPanel p;
private JTextField fieldBN;
private JTextField fieldFN;
private JTextField fieldLN;
private JTextField fieldP;
private JTextField fieldE;
private JTextField fieldA;
private JTextField aLine2;
private JTextField fieldW;
private JLabel labelBN;
private JLabel labelFN;
private JLabel labelLN;
private JLabel labelP;
private JLabel labelE;
private JLabel labelA;
private JLabel labelW;
private JButton buttonS;
// Constructor:
public Driver() {
gui();
}
public void gui() {
f = new JFrame("Contact Book");
f.setVisible(true);
f.setSize(900,800); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10, 10, 10, 10);
p = new JPanel(new GridBagLayout());
f.getContentPane().add(p, BorderLayout.NORTH);
c.gridx = 100;
c.gridy = 0;
labelBN = new JLabel ("Business Name");
p.add(labelBN, c);
c.gridx = 110;
c.gridy = 0;
fieldBN = new JTextField(10);
p.add(fieldBN, c);
c.gridx = 100;
c.gridy = 10;
labelFN= new JLabel ("First Name");
p.add(labelFN, c);
c.gridx = 110;
c.gridy = 10;
fieldFN = new JTextField (10);
p.add(fieldFN, c);
c.gridx = 100;
c.gridy = 20;
labelLN= new JLabel ("Last Name");
p.add(labelLN, c);
c.gridx = 110;
c.gridy = 20;
fieldLN = new JTextField (10);
p.add(fieldLN, c);
c.gridx = 100;
c.gridy = 30;
labelP = new JLabel ("Phone Number");
p.add(labelP, c);
c.gridx = 110;
c.gridy = 30;
fieldP = new JTextField (10);
p.add(fieldP, c);
c.gridx = 100;
c.gridy = 40;
labelE = new JLabel ("Email");
p.add(labelE, c);
c.gridx = 110;
c.gridy = 40;
fieldE = new JTextField (10);
p.add(fieldE, c);
c.gridx = 100;
c.gridy = 50;
labelA = new JLabel ("Address");
p.add(labelA, c);
c.gridx = 110;
c.gridy = 50;
fieldA = new JTextField (10);
p.add(fieldA, c);
c.gridx = 110;
c.gridy = 60;
aLine2 = new JTextField (10);
p.add(aLine2, c);
c.gridx = 100;
c.gridy = 70;
labelW = new JLabel ("Website");
p.add(labelW, c);
c.gridx = 110;
c.gridy = 70;
fieldW = new JTextField (10);
p.add(fieldW, c);
c.gridx = 110;
c.gridy = 80;
buttonS = new JButton("Save");
p.add(buttonS, c);
// Window Listeners
addWindowListener(new WindowAdapter() {
}
);
} // End Gui
public static void main(String[] args) {
new Driver();
} // End main Method
} // End class Driver
The probable cause is right here...
public void gui() {
f = new JFrame("Contact Book");
f.setVisible(true);
f.setSize(900,800); // default size is 0,0
You're calling setVisible to early.
The simple solution is to call setVisible once you've set the frame up the way you want...
public void gui() {
f = new JFrame("Contact Book");
// Add everything to the frame...
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
}
Also, extending from JFrame and then creating an instance of JFrame is very confusing. Generally, you shouldn't need to extend from JFrame, just keep creating an instance as you need.
You should also take a look at Initial Threads
For example...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
}
});
} // End main Method

setLocation of Label

I have all of the labels working correctly but the userLabel[3] is not positioning properly
No matter what I do, the label "Color:" always shows up on the frame with a x-coordinate of 0 and a y-coordinate that is half way down the frame.
JLabel[] userLabel = new JLabel[4];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
userLabel[p].setSize(100,50);
frameSetUp.add(userLabel[p]);
}
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[0].setLocation(10,35);
userLabel[1].setLocation(10,85);
userLabel[2].setLocation(10,135);
userLabel[3].setLocation(0,0); //no matter what coordinates I change this too, it wont reposition
Image:
[IMG]http://i41.tinypic.com/23jfo9l.png[/IMG]
http://i41.tinypic.com/23jfo9l.png
Don't use setLocation, setBounds, null layouts or absolute positioning.
Instead use the layout managers including perhaps nested JPanels, each using its own layout manager to achieve pleasing easy to maintain GUI's.
For more help, show a picture of what you're trying to achieve, what you actually are achieving, and post a minimal working example, code that is small, that compiles and runs, and shows us your problem.
e.g.,
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which will display like so:
The beauty of this code, is if you wish to add another field, say a line thickness field, and want to add it so that it is second to last, then the only change needed to the code would be to change this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
to this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Line Thickness:", "Color:" };
Which results in:
No need to have to calculate how to change the Color label or JTextField's locations as the layout manager does all the hard work for you.
Finally got the answer try increasing the size of the JLabel array by 1 and run it will work fine
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Labelss{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(50, 50, 700, 550);
JLabel[] userLabel = new JLabel[6];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
}
userLabel[0].setBounds(10,35,100,50);
userLabel[1].setBounds(10,85,100,50);
userLabel[2].setBounds(10,135,100,50);
userLabel[3].setBounds(10,185,100,50);
userLabel[4].setBounds(10,235,100,50);
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[4].setText("Stack overflow:");
for(int p = 0; p < userLabel.length; p++){
frame.add(userLabel[p]);
}
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

ActionListener implementation in Java

Could you please help me use the ActionListener correclty in my code? The code compiles and the GUI is displayed correctly, but no button works!! If you want to test the code, note that you need to put the image in the same folder as the project file created and change the line "ImageIcon myImageIcon = new ImageIcon("rodeo.jpg");" according to the name of your photo.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageApplication extends JFrame implements ActionListener
{
public Image myImage;
public JLabel myImageLabel;
public ImageIcon myImageIcon;
public JFrame frame;
public JTextField txtWidth, txtHeight;
public int origWidth, origHeight;
public static void main(String[] args)
{
int origWidth, origHeight;
ImageApplication ia = new ImageApplication();
ia.setVisible(true);
JFrame frame = new JFrame();
ImageIcon myImageIcon = new ImageIcon("rodeo.jpg");
JLabel myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
Image myImage = myImageIcon.getImage();
origWidth = myImageIcon.getIconWidth();
origHeight = myImageIcon.getIconHeight();
JMenuBar myMenuBar = new JMenuBar();
JMenu myMenu = new JMenu("Options");
JMenuItem myMenuItem1 = new JMenuItem("Double");
JMenuItem myMenuItem2 = new JMenuItem("Reset");
myMenu.add(myMenuItem1);
myMenu.add(myMenuItem2);
myMenuBar.add(myMenu);
ia.setJMenuBar(myMenuBar);
JButton bAL = new JButton("Align Left");
JButton bAC = new JButton("Align Center");
JButton bAR = new JButton("Align Right");
JButton bResize = new JButton ("Resize");
bAL.setFocusPainted(false);
bAC.setFocusPainted(false);
bAR.setFocusPainted(false);
bResize.setFocusPainted(false);
JLabel lWidth = new JLabel("Width:");
JLabel lHeight = new JLabel("Height:");
JTextField txtWidth = new JTextField(Integer.toString(origWidth));
JTextField txtHeight = new JTextField(Integer.toString(origHeight));
JPanel GRID = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1f;
c.weighty = 0f;
c.gridx = 0;
c.gridy = 0;
GRID.add(bAL, c);
c.gridx++;
GRID.add(bAC, c);
c.gridx++;
GRID.add(bAR, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
GRID.add(myImageLabel, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
GRID.add(lWidth, c);
c.gridx++;
c.gridwidth = 2;
GRID.add(txtWidth, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 3;
GRID.add(lHeight, c);
c.gridx++;
c.gridwidth = 2;
GRID.add(txtHeight, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 4;
GRID.add(bResize, c);
ia.add(GRID, BorderLayout.CENTER);
ia.setSize(origWidth + 150, origHeight + 150);
myMenuItem1.addActionListener(ia);
myMenuItem1.setActionCommand("double");
myMenuItem2.addActionListener(ia);
myMenuItem2.setActionCommand("reset");
bAL.addActionListener(ia);
bAL.setActionCommand("left");
bAC.addActionListener(ia);
bAC.setActionCommand("center");
bAR.addActionListener(ia);
bAR.setActionCommand("right");
bResize.addActionListener(ia);
bResize.setActionCommand("resize");
}
private void ResizeImage(int Width, int Height)
{
myImage = myImage.getScaledInstance(Width, Height, Image.SCALE_SMOOTH);
myImageIcon.setImage(myImage);
myImageLabel.setIcon(myImageIcon);
txtWidth.setText(Integer.toString(Width));
txtHeight.setText(Integer.toString(Height));
setSize(Width + 150, Height + 150);
}
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command == "left") myImageLabel.setHorizontalAlignment(JLabel.LEFT);
else if(command == "center") myImageLabel.setHorizontalAlignment(JLabel.CENTER);
else if(command == "right") myImageLabel.setHorizontalAlignment(JLabel.RIGHT);
else if(command == "resize") ResizeImage(Integer.parseInt(txtWidth.getText()),
Integer.parseInt(txtHeight.getText()));
else if(command == "double") ResizeImage(myImageIcon.getIconWidth() * 2,
myImageIcon.getIconHeight() * 2);
else if(command == "reset") ResizeImage(origWidth, origHeight);
}
}
Use String#equals to compare String content. You are using the == operator which compares Object references.
However, as the buttons have differing functionality, better for each to have an individual ActionListener. This can be done using an anonymous ActionListener instance.
Side issue: The class member variable myImageLabel is not being assigned. Rather another variable
with the same name is initialized in the static main method. You need to move all the components instantiated in the main method into an instance method and also remove the JLabel local class declaration.
After moving code:
JLabel myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
should be
myImageLabel = new JLabel(myImageIcon, JLabel.CENTER);
Try this method:
What it does: it adds to the button itself, when clicked an method to be performed:
buttonName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//do what ever
}
});
//set bunds for the button itself, if not done otherwise, but for your layout.
These instance variables:
public JTextField txtWidth, txtHeight;
are never initialized but are referred to in your listener code. You have local variables of the same name that you're instantiating. Change this:
JTextField txtWidth = new JTextField(Integer.toString(origWidth));
JTextField txtHeight = new JTextField(Integer.toString(origHeight));
to this:
txtWidth = new JTextField(Integer.toString(origWidth));
txtHeight = new JTextField(Integer.toString(origHeight));
and similarly for your other instance variables.
Use the following code to get Image
ImageIcon myImageIcon = new ImageIcon("rodeo.jpg").getImage();

Categories

Resources