Add to JList and select element? - java

I need some help to be able to add element to a JList and how to select element whith event.
This is my JList:
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
This is part of my actionlistener that handle different buttons. It's here I want to use model.add("Name"); bot I get a red underline in Eclipse!?
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number);
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement(name);
}
}
}
Then I would preciate some help how I should select the element inside the JList? Should I use implements ActionListener to the class or a FrameHandler object? Thanks!
EDIT: My main problem that I can't solve is that the JList is inside the construcor and when I use model.add("name"); inside the constructor it works, but it's not working when I want to add something outside the constructor? I have read the tutorial several times, but can't find any help for this.
EDIT 2: The completet code. Probably some out of scope problem?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI4EX extends JFrame implements ActionListener{
private JButton buttonNewCustomer, buttonTerminate, buttonAddNewName, buttonAddNewSavingsAccount, buttonAddNewCreditAccount;
private JLabel textLabelName, textLabelPersonalNumber, textLabelNewName;
private JTextField textInputName, textInputPersonalNumber, textInputNewName;
private JPanel panelNewCustomer, panelQuit, panelNewAccount, panelChangeName, panelSelectCustomer;
private boolean statusButtonNewCustomer = true;
private boolean statusButton2 = true;
private boolean statusButtonAddNewName = true;
private String title = "Bank ";
// Create a customHandler object
CustomHandler customHandler = new CustomHandler();
// Main method to start program
public static void main(String[] args){
GUI4EX frame = new GUI4EX();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
// Cunstructor
public GUI4EX(){
// Create window
setTitle(title);
setSize(450,500);
setLocation(400,100);
setResizable(false);
// Set layout to boxlayout
Container container = getContentPane( );
setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
// Create jpanels
panelNewCustomer = new JPanel();
panelQuit = new JPanel();
panelNewAccount = new JPanel();
panelChangeName = new JPanel();
panelSelectCustomer = new JPanel();
// Create and add components - buttons
buttonNewCustomer = new JButton("OK");
buttonTerminate = new JButton("Avsluta");
buttonAddNewName = new JButton("OK");
buttonAddNewSavingsAccount = new JButton("Sparkonto");
buttonAddNewCreditAccount = new JButton("Kreditkonto");
// Create and add components - labels
textLabelName = new JLabel("Namn");
textLabelPersonalNumber = new JLabel("Personnummer");
textLabelNewName = new JLabel("Nytt namn");
//add(textLabel1);
// Create and add components - textfields
textInputName = new JTextField("");
textInputPersonalNumber = new JTextField("");
textInputName.setColumns(10);
textInputPersonalNumber.setColumns(10);
textInputNewName = new JTextField();
textInputNewName.setColumns(20);
// Add components to panel new customer
panelNewCustomer.add(textLabelName);
panelNewCustomer.add(textInputName);
panelNewCustomer.add(textLabelPersonalNumber);
panelNewCustomer.add(textInputPersonalNumber);
panelNewCustomer.add(buttonNewCustomer);
// Add components to panel to select customer
panelSelectCustomer.add(listScroller);
// Add components to panel new name
panelChangeName.add(textLabelNewName);
panelChangeName.add(textInputNewName);
panelChangeName.add(buttonAddNewName);
// Add components to panel new accounts
panelNewAccount.add(buttonAddNewSavingsAccount);
panelNewAccount.add(buttonAddNewCreditAccount);
// Add components to panel quit
panelQuit.add(buttonTerminate);
// Set borders to jpanels
panelNewCustomer.setBorder(BorderFactory.createTitledBorder("Skapa ny kund"));
panelChangeName.setBorder(BorderFactory.createTitledBorder("Ändra namn"));
panelNewAccount.setBorder(BorderFactory.createTitledBorder("Skapa nytt konto"));
panelQuit.setBorder(BorderFactory.createTitledBorder("Avsluta programmet"));
panelSelectCustomer.setBorder(BorderFactory.createTitledBorder("Välj kund"));
// Add panels to window
add(panelNewCustomer);
add(panelSelectCustomer);
add(panelChangeName);
add(panelNewAccount);
add(panelQuit);
// Listener
// FrameHandler handler = new FrameHandler();
// Add listener to components
//button1.addActionListener(handler);
buttonNewCustomer.addActionListener(this);
buttonAddNewName.addActionListener(this);
buttonAddNewSavingsAccount.addActionListener(this);
buttonAddNewCreditAccount.addActionListener(this);
buttonTerminate.addActionListener(this);
}
//private class FrameHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number); // Check if customer exist
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement("name");
}
}
// Change name
if(event.getSource() == buttonAddNewName && statusButtonAddNewName)
{
String newName = textInputNewName.getText();
customHandler.changeName(newName); // call method to change name
setTitle(title + "Kund: " + newName);
}
// Create new savings account
if(event.getSource() == buttonAddNewSavingsAccount)
{
customHandler.CreateNewSavingsAccount();
}
// Create new credit account
if(event.getSource() == buttonAddNewCreditAccount)
{
customHandler.CreateNewCreditAccount();
}
// Terminate program
if(event.getSource()==buttonTerminate && statusButton2)
{
System.exit(3);
}
}
//}
}

You are lucky I am in a good mood. Here a very basic example, matching the code you provided. Type something in the textfield, hit the enter button and watch the list get populated.
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddToJListDemo {
private static JFrame createGUI(){
JFrame frame = new JFrame( );
final DefaultListModel model = new DefaultListModel();
JList list = new JList( model );
final JTextField input = new JTextField( 10 );
input.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent aActionEvent ) {
String text = input.getText();
if ( text.length() > 0 ) {
model.addElement( text );
input.setText( "" );
}
}
} );
frame.add( list, BorderLayout.CENTER );
frame.add( input, BorderLayout.SOUTH );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
return frame;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
public void run() {
JFrame frame = createGUI();
frame.setSize( 200,200 );
frame.setVisible( true );
}
} );
}
}
Edit
Based on your full code, you must make the list a field in your GUI4EX class, similar to for example the buttonNewCustomer field
public class GUI4EX extends JFrame implements ActionListener{
//... all other field
DefaultListModel model;
//constructor
public GUI4EX(){
//all other code
//DefaultListModel model = new DefaultListModel(); instantiate the field instead
model = new DefaultListModel();
JList list = new JList(model);
//rest of your code
}
}
This will make sure you can access the model in the actionPerformed method. But if you cannot figure out something this basic, you should not be creating GUIs but reading up on basic Java syntax and OO principles

Related

Editable JComboBox gives error: <identifier> expected and illegal start of type

I am trying to create and Editable JComboBox to allow the user to type the name of the song to purchase. However when I set tunes.setEditable(true); I get an error... any help will be appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
Thank you!
Actually, Java requires that you setup JComponents in the constructor. In order for your code to work, you need to call on setEditable(true) in the constructor, which means that you just need to move tunes.setEditable(true); to the constructor.
Tip: always allocate memory for JComponents in the constructor (you want to draw the components as soon as you create the Jframe). You can have a reference to the JComboBox at the class level.
Here is another version of your code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes;
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes2 frame = new JTunes2();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
You added the tunes.setEditable(true) at the class level, instead of at the method level. No statements allowed at the class level!
Here's a fixed version: I renamed JTunes2 to JTunes to fix the compilation errors, and moved the setEditable to the constructor. Also I fixed the indentation - this makes it harder to make this mistake:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}

How can I pass an ArrayList between two separate JTabbedPanes

I have a program utilizing JTabbedPane. On one pane I have a button that updates an arrayList of objects based on input from the same pane.
What I would like to happen is have the second pane update itself with the object information based on the arrayList in the first pane.
However, I am not sure how to pass the list between the panes. Is there some way to push the array to pane #2 when the update button on the first pane is pressed?
Here is the main file. Instantiating the two tabs
public class Assignment6 extends JApplet
{
private int APPLET_WIDTH = 650, APPLET_HEIGHT = 350;
private JTabbedPane tPane;
private StorePanel storePanel;
private PurchasePanel purchasePanel;
private ArrayList computerList;
public void init()
{
computerList = new ArrayList();
storePanel = new StorePanel(computerList, purchasePanel);
purchasePanel = new PurchasePanel(computerList);
tPane = new JTabbedPane();
tPane.addTab("Store Inventory", storePanel);
tPane.addTab("Customer Purchase", purchasePanel);
getContentPane().add(tPane);
setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
}
}
The first panel instantiates a button listener that applies all of the logic to the array list "compList"
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//Add Computer to list
Computer comp = new Computer();
comp.setBrandName(brandField.getText());
comp.setPrice(Double.parseDouble(priceField.getText()));
comp.setMemory(Integer.parseInt(memoryField.getText()));
comp.setCPU(typeField.getText(), Integer.parseInt(speedField.getText()));
compList.add(comp);
}
stringField.setText(listString);
alertLabel.setText("Computer Added");
}
}
Here is the other pane. The for loop at the end is what I need to push the arrayList to. After it receives the list, it populates a box with a checkbox for each object in the list
public PurchasePanel(ArrayList compList)
{
west = new JPanel();
east = new JPanel();
totalField = new JTextField();
this.compList = compList;
setLayout(new GridLayout(0,2));
add(west);
add(east);
east.setLayout(new BorderLayout());
east.add(currentTotalLabel, BorderLayout.NORTH);
east.add(totalField, BorderLayout.CENTER);
west.setLayout( new BoxLayout(west, BoxLayout.Y_AXIS));
for(Object c : compList){
System.out.println("Made it");
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String str = ("BrandName:" + (((Computer) c).getBrandName() +"CPU:" + (((Computer) c).getCPU() +"Memory:" + ((Computer) c).getMemory() + "M" +"Price:" + fmt.format(((Computer) c).getPrice()))));
JCheckBox chk = new JCheckBox(str);
west.add(chk);
}
}
}
You can use the same listener used to update the first ArrayList, to update the second pane. Something like:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Update the first ArrayList
// Update the second pane
}

Change JTextArea texts from JButton's actionPerformed which is in another class

I have a fully functional console-based database which I need to add GUIs to. I have created a tab page (currently only one tab) with a button "Display All Student" which when triggered will display a list of students inside a JTextArea which of course is in its own class and not inside the button's action listener class. Problem is, the JTextArea is not recognised inside button's action listener. If I add parameter into the action listener, more errors arise. Help?
I have searched Stack Overflow for similar problems but when I tried it in my code, doesn't really do the trick? Or maybe I just need a nudge in the head. Anyways.
Here is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
Your code isn't working for the same reason this wouldn't work:
int j = i+5;
int i = 4;
You have to declare variables before using them in Java.
Secondly, in order to use a variable (local or instance) from inside an inner class - which is what your ActionListener is - you need to make it final.
So, the below code will compile and run:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);

Trouble with basic GUI

First, I would like to say I have searched these forums, as well as others for an answer to my question. I am very new to Java, and programing in general. After working on this for several hours, I would like to ask for some help.
I am trying to open up a window (that will have some graphics later), that has a menu bar. The options are 3 drop down menus that perform a task when selected. The file menu lets me save, load, and exit the program. For now the rest just print to the screen to let me know that much is working. Right now, I want to set it up so when I click the "Create Seller" option, it will open up a new dialog box with 3 fields. I would like to enter a string in one, and two doubles in the other two. I will then store those as variables and send them to another function. I have been stuck on this part for way too long. Keep in mind that, while this has probably been answered before, I think I am just not competent enough with Java yet to understand the answer. Try to dumb it down for me if that is not too much to ask. THANKS!
here is the class I am working on. Feel free to ask for less or more if you need.
package seller;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import datastore.Meteorite;
import datastore.continents;
import datastore.customers;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class BaseFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JFileChooser myChooser = new JFileChooser(".");
JMenuItem menuItemSave;
JMenuItem menuItemLoad;
JMenuItem menuItemExit;
JMenuItem menuItemCreateSeller;
JMenuItem menuItemUpdateSeller;
JMenuItem menuItemRemoveSeller;
JMenuItem menuItemCreateMeteorite;
JMenuItem menuItemUpdateMeteorite;
JMenuItem menuItemRemoveMeteorite;
JMenuItem menuItemCreateOneLine;
continents worldMap = new continents();
boolean[][] mapArray = null;
int selection = 1;
String shopName = null;
Map myMap= new Map();
Scanner myScanner = new Scanner(System.in);
Menu myMenu = new Menu();
seller seller= new seller();
Meteorites myMeteorite = new Meteorites();
customers sellers= new customers(0,0,"test");
customers buyers= new customers(0, 0, "test");
ArrayList <Meteorite> myMeteorites = new ArrayList<Meteorite>();
ArrayList <customers> mySellers= new ArrayList<customers>();
ArrayList <customers> myBuyers= new ArrayList<customers>();
customers people= new customers(0,0,"test");
public void makeGui()
{
this.setTitle("Phase 3");
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
//Load and Save used from class example
JMenu fileMenu = new JMenu("File");
mb.add(fileMenu);
menuItemSave = new JMenuItem("Save");
menuItemSave.addActionListener(this);
menuItemLoad = new JMenuItem("Load");
menuItemLoad.addActionListener(this);
menuItemExit = new JMenuItem("Exit");
menuItemExit.addActionListener(this);
fileMenu.add(menuItemSave);
fileMenu.add(menuItemLoad);
fileMenu.add(menuItemExit);
//seller menu
JMenu sellerMenu = new JMenu("Seller");
mb.add(sellerMenu);
menuItemCreateSeller = new JMenuItem("Create Seller");
menuItemCreateSeller.addActionListener(this);
menuItemUpdateSeller = new JMenuItem("Update Seller");
menuItemUpdateSeller.addActionListener(this);
menuItemRemoveSeller = new JMenuItem("Remove Seller");
menuItemRemoveSeller.addActionListener(this);
sellerMenu.add(menuItemCreateSeller);
sellerMenu.add(menuItemUpdateSeller);
sellerMenu.add(menuItemRemoveSeller);
//handle meteorite menu
JMenu handleMeteoriteMenu = new JMenu("Handle Meteorite");
mb.add(handleMeteoriteMenu);
menuItemCreateMeteorite = new JMenuItem("Create Meteorite");
menuItemCreateMeteorite.addActionListener(this);
menuItemUpdateMeteorite = new JMenuItem("Update Meteorite");
menuItemUpdateMeteorite.addActionListener(this);
menuItemRemoveMeteorite = new JMenuItem("Remove Meteorite");
menuItemRemoveMeteorite.addActionListener(this);
menuItemCreateOneLine = new JMenuItem("Create Meteorite(1 line)");
menuItemCreateOneLine.addActionListener(this);
handleMeteoriteMenu.add(menuItemCreateMeteorite);
handleMeteoriteMenu.add(menuItemUpdateMeteorite);
handleMeteoriteMenu.add(menuItemRemoveMeteorite);
handleMeteoriteMenu.add(menuItemCreateOneLine);
JPanel tPanel = new JPanel();
this.add(tPanel);
this.pack();
this.setSize(new Dimension(640,480));
this.setVisible(true);
}
String myName;
double myLong;
double myLat;
#Override
public void actionPerformed(ActionEvent e)
{
Object source=null;
source=e.getSource();
if (source == menuItemLoad)
{
mapArray = worldMap.createMap();
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = myChooser.showOpenDialog(this);
//if user clicked Cancel button, return
if (result == JFileChooser.CANCEL_OPTION)
System.exit(1);
File myFile = myChooser.getSelectedFile(); //get file
//display error if invalid
if ( ( myFile == null) || (myFile.getName().equals("")))
{
JOptionPane.showMessageDialog(this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
myMeteorites= myMeteorite.loadMeteorite(myMeteorites, myFile);
sellers.loadSeller(mySellers);
buyers.loadBuyer(myBuyers);
}
if (source == menuItemSave)
{
mapArray = worldMap.createMap();
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = myChooser.showOpenDialog(this);
//if user clicked Cancel button, return
if (result == JFileChooser.CANCEL_OPTION)
System.exit(1);
File myFile = myChooser.getSelectedFile(); //get file
//display error if invalid
if ( ( myFile == null) || (myFile.getName().equals("")))
{
JOptionPane.showMessageDialog(this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
myMeteorites= myMeteorite.saveMeteorite(myMeteorites, myFile);
sellers.saveSeller(mySellers);
buyers.saveBuyer(myBuyers);
}
if (source == menuItemExit)
{
System.exit(1); //exit system
}
if (source == menuItemCreateSeller)
{
JFrame myFrame = new JFrame("Create a Seller");
JPanel myPanel = new JPanel();
JLabel myLabel1 = new JLabel();
JLabel myLabel2 = new JLabel();
JLabel myLabel3 = new JLabel();
final JTextField myText1 = new JTextField(30);
final JTextField myText2 = new JTextField(30);
final JTextField myText3 = new JTextField(30);
setDefaultCloseOperation(EXIT_ON_CLOSE);
myLabel1.setText("Enter Name");
myLabel2.setText("Enter Longitude");
myLabel3.setText("Enter Latitude");
myPanel.add(myLabel1);
myPanel.add(myText1);
myPanel.add(myLabel2);
myPanel.add(myText2);
myPanel.add(myLabel3);
myPanel.add(myText3);
myFrame.add(myPanel);
myFrame.setSize(350,200);
myFrame.setVisible(true);
myText1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
myName = myText1.getText();
}
});
myName = myText1.getText();
//myLong = Double.parseDouble(myText2.getText());
//myLat = Double.parseDouble(myText3.getText());
System.out.println(myName);
//mySellers=people.createCust(mySellers, myLong, myLat, myName);
//mySellers=people.saveSeller(mySellers);
}
if (source == menuItemRemoveSeller)
{
System.out.println("remove seller");
}
if (source == menuItemUpdateSeller)
{
System.out.println("update seller");
}
if (source == menuItemCreateMeteorite)
{
System.out.println("create meteorite");
}
if (source == menuItemUpdateMeteorite)
{
System.out.println("updateMeteorite");
}
if (source == menuItemRemoveMeteorite)
{
System.out.println("remove meteorite");
}
if (source == menuItemCreateOneLine)
{
System.out.println("create one line");
}
}
}
See this example for what I am talking about. Though I'd advise against using multiple frames, this will work for what yo are trying to do. As #MadProgrammer suggested, look into creating JDialogs
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BaseFrame extends JFrame {
private String name;
private double value1;
private double value2;
private final JMenuBar jMenuBar = new JMenuBar();
private final JMenu jmOpen = new JMenu("Open");
JMenuItem menuItemCreateSeller = new JMenuItem("Create Seller");
InnerFrame innerFrame = new InnerFrame();
public BaseFrame() {
innerFrame.setResizable(false);
jmOpen.add(menuItemCreateSeller);
jMenuBar.add(jmOpen);
setJMenuBar(jMenuBar);
menuItemCreateSeller.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
innerFrame.setVisible(true);
}
});
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
Frame frame = new BaseFrame();
}
});
}
private class InnerFrame extends JFrame {
JPanel myPanel = new JPanel();
JLabel myLabel1 = new JLabel("Enter Name");
JLabel myLabel2 = new JLabel("Enter Longitude");
JLabel myLabel3 = new JLabel("Enter Latitude");
JLabel jlblStatus = new JLabel(" ");
JTextField myText1 = new JTextField(10);
JTextField myText2 = new JTextField(10);
JTextField myText3 = new JTextField(10);
JButton jbtPrint = new JButton("Print");
public InnerFrame() {
myPanel.add(myLabel1);
myPanel.add(myText1);
myPanel.add(myLabel2);
myPanel.add(myText2);
myPanel.add(myLabel3);
myPanel.add(myText3);
JPanel p1 = new JPanel(new GridLayout(1,2));
p1.add(jlblStatus);
p1.add(jbtPrint);
jlblStatus.setHorizontalAlignment(SwingConstants.LEFT);
jlblStatus.setForeground(Color.RED);
jbtPrint.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
name = myText1.getText();
value1 = Double.parseDouble(myText2.getText());
value2 = Double.parseDouble(myText3.getText());
System.out.println(name);
double total = value1 + value2;
System.out.println(total);
setVisible(false);
} catch (NumberFormatException ex) {
jlblStatus.setText("Invalid Input");
}
}
});
add(myPanel, BorderLayout.CENTER);
add(p1, BorderLayout.SOUTH);
setSize(180, 220);
setLocationRelativeTo(null);
setVisible(false);
}
}
}
You've gotten good advice in comments, and the other answer that has been posted looks reasonable at a glance. I'm going to throw in an explanation that you may or may not need; if you do need it, it would be the sort of thing it would be hard to explain that you need, because it is a concept that you may not have assimilated yet.
UI programming is "event-driven"; that means that, instead of having control in your code as you do for a non-interactive program, the control is passed to another system or part of the system, and when certain events happen, that other part calls your code. The 'other part' in this case is the Swing runtime. So your code is all about setting up the frames, panels, layouts, text fields, drop-downs, etc., AND setting listeners to those things that might cause events, and waiting for events to happen.
If your confusion is rooted in a lack of understanding of this, then the answer to your question might be that the listener for the button on the dialog is going to read the values from the drop-downs and/or text fields -- presumably the user has chosen and/or entered values as he/she was supposed to and then clicked the button. So the action routine that fires when the button (or the enter key) is clicked (pressed) goes and gets those values as they are at that time and puts them into variables (or writes them to a database or instantiates another object with them or whatever it is supposed to do.
This routine also might do validation -- if, for instance, one of the text fields holds a value that is required and the user didn't fill it out, then this listener routine could detect that and, instead of allowing the program to continue, could popup a message dialog for the user telling him/her what is wrong.
Again, I don't know that this is any part of your problem, but I thought it might be. It is a concept that inexperienced UI programmers sometimes have trouble with, and it is so basic to UI programming that a lot of the tutorials just assume you already know it.

Java GUI Variables Problems

I seem to have set up something wrong in the action listener for the Create Button handler. When I tried to get the value of the text field nameTF I get a null pointer error. I tried to imitate your code for the calculator, and the Exit Button Handler works well. I know that pressing the Create button invokes the handler but the statement
inName = nameTF.getText();
gives the error message.
The complete text of the listener is
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
and the whole program is below. Any help/explanation/suggestion would be very welcome.
import javax.swing.*; // import statement for the GUI components
import java.awt.*; //import statement for container class
import java.awt.event.*;
public class DogGUI //creation of DogGUI clas
{
private JLabel nameL, typeL, ageL, outtputL;
private JTextField nameTF, typeTF, ageTF;
private JButton createB, exitB;
CreateButtonHandler cbHandler;
ExitButtonHandler ebHandler;
public void driver () //creates everything
{
//create the window
JFrame DogInfo = new JFrame ("Dog GUI");
DogInfo.setSize(400,300); //set the pixels for GUI
DogInfo.setVisible(true); // set visibility to true
DogInfo.setDefaultCloseOperation(DogInfo.EXIT_ON_CLOSE); // when closed JFrame will disappear
//layout
Container DogFields = DogInfo.getContentPane();
DogFields.setLayout(new GridLayout(5,2));
// setting labels for GUI
nameL = new JLabel ("Enter name of Dog: ",
SwingConstants.RIGHT);
typeL = new JLabel ("Enter the type of the Dog: ",
SwingConstants.RIGHT);
ageL = new JLabel ("Enter the age of the Dog: ",
SwingConstants.RIGHT);
outtputL = new JLabel ("Dog Information: ",
SwingConstants.RIGHT);
//Buttons
JButton createB, exitB; //creating button for creation of Dog and button to exit
createB = new JButton("Create Dog");
exitB = new JButton("Exit");
//text fields
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
typeTF = new JTextField(15);
ageTF = new JTextField(5);
outtputTF = new JTextField(25);
outtputTF.setEditable(false); //this TF is to display this output
//Lables and Textfields
DogInfo.add(nameL);
DogInfo.add(nameTF);
DogInfo.add(typeL);
DogInfo.add(typeTF);
DogInfo.add(ageL);
DogInfo.add(ageTF);
DogInfo.add(outtputL);
DogInfo.add(outtputTF);
//Buttons
DogInfo.add(createB);
DogInfo.add(exitB);
//Instantiate Listeners
cbHandler = new CreateButtonHandler();
ebHandler = new ExitButtonHandler();
//Register Listeners
createB.addActionListener(cbHandler);
exitB.addActionListener(ebHandler);
DogInfo.setVisible(true);
}
//run the program from main, instantiate class, invoke driver() method
public static void main(String[] args)
{
DogGUI d = new DogGUI();
d.driver();
}
// class to actually handle Dog creation
private class CreateButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String inName, inType; //local variables
int inAge;
Dog arf;
inName = nameTF.getText();
inType = typeTF.getText();
inAge = Integer.parseInt( ageTF.getText() );
//System.out.println("Inside CreateButtonHandler");
System.out.println(inName);
arf = new Dog(inName, inType, inAge);
System.out.println(arf.toString () );
}
}
private class ExitButtonHandler
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("inside exit button");
System.exit(0);
} // end method actionPerformed
}
}
You have a local variable in the driver() method called nameTF that is hiding that field (same for some other variables).
JTextField nameTF, typeTF, ageTF, outtputTF;
nameTF = new JTextField(10);
Remove the declaration of those fields since they are already declared as instance fields.
private JTextField nameTF, typeTF, ageTF;
(probably not outtputTF, depending on what you want to do)

Categories

Resources