JLabel constructor
Hello,
I created two labels called left and right as shown below.
left = new JLabel ( images[0] );
right = new JLabel ( images[0]);
It wont compile complaining, "cannot resolve symbol".
images is an array created in a separate method within the same code. I thought maybe it wanted me to declare it like this:
left = new JLabel ( Icon images[0] );
but that didn't work either. It gives the same error.
I'd appreciate some help and/or advice on this.
Daniel
Here is a sample that works. Use it to see what is missing in your code:
import javax.swing.*;
import java.awt.*;
class TestIcon {
public static void main (String[] argv) {
ImageIcon[] imagini = new ImageIcon [2];
imagini[0] = new ImageIcon ("oops.gif");
imagini[1] = new ImageIcon ("exclamation.gif");
JLabel l1 = new JLabel (imagini[0]);
JLabel l2 = new JLabel (imagini[0]);
JFrame frame = new JFrame ("testing...");
frame.getContentPane().setLayout (new FlowLayout());
frame.getContentPane().add (l1);
frame.getContentPane().add (l2);
//frame.setSize (300,200);
frame.pack();
frame.show();
frame.setVisible (true);
}Good luck,
Calin
Similar Messages
-
JLabel constructor call problem
Hello,
I've problem with calling JLabel's constructor with passing String value to constructor.
jobject jobjLabel;
jclass JLabelClass;
jmethodID mid;
JLabelClass = (*env)->FindClass(env,"javax/swing/JLabel");
if(JLabelClass == NULL) {
printf("Can't find class JLabel\n");
goto destroy;
mid = (*env)->GetMethodID(env,JLabelClass,"<init>","(Ljava/lang/String;)V");
jobjLabel = (*env)->NewObject(env,JLabelClass,mid,"Hello World");At line:
jobjLabel = (*env)->NewObject(env,JLabelClass,mid,"Hello World");Main Thread exits with error code 1. I am sure that this line is true but I didn't find problem.
Are there any methods to find errors before program exit?Probably I've found. I must pass constructor value as String object. Am I wrong?
But Are there any methods to find our errors before program exit?
Thanks in Advance -
How to display Long text in a JLabel with multiline??
Hi,
Suppose I have a label that displays a long text....
""This is an example label that displays long text, how to break the line????.........""
how to display it like below with one label?
""This is an example label
that displays long text, how
to break the line????.........""
Thanksso basically do this
JLabel myLabel = new JLabel();
String theText = "<html>This is an example label<br>
that displays long text, how<br>
to break the line????.........</html>";
myLabel.setText(theText);Obivously, u dont have to use a separate string, u could just call setText or pass it into the JLabel constructor, i just separated it to make it easier to see what your supposed to do.
GOod Luck -
Unicode Characters in Label/JLabels
Hi All,
Does anyone know how when any unicode characters within a String get transformed into the character they represent? I ask because I'm getting conflicting behaviour depending on whether the String is hard-coded or read from file at runtime.
For instance, the following code works fine and produces a label on the GUI containing the infinity character:
String name = "100 to \u221E";
JLabel label = new JLabel(name);
However, if <name> is read from an XML file, the label produced shows "100 to \u221E" verbatim.
Has anyone else seen this effect?
Thanks in advance for any advice,
Andy ChamberlainThanks for that. If I understand correctly, is it
therefore the case that by the time the JLabel
constructor gets called, the String object ("name", in
this case) already has any unicode characters
encoded within it?
Exactly. The compiled .class file already has the unicode characters in it; JLabel has nothing to do with it.
If so, then when debugging, any such characters must
get decoded again back to ASCII when the value of
"name" is inspected within the debugger environment
(JDeveloper in this case).
Depends on the unicode-awareness of JDeveloper; I don't know anything about it.
And the finger would certainly then point to when the
String was created by the XML parser (I'm using
org.dom4j.io.SAXReader). I'll investigate this
further.If you have a text editor that can save a file in UTF-8, you could try saving the xml with the infinity symbol as plain text and specify the encoding of the file with <?xml encoding='UTF-8'?>... Or does your parser accept the &#some-decimal-number; way? -
I have written code to load in an object but this keeps giving me exceptions when i run the code to try and display the data from the object read in. My code is below:
Thanks
//--- cFaceRecGUIMain.java ---
//--- Edmund Smith 23/08/04 ---
//--- The GUI for the face recognition sofware contains buttons and ---
//--- display area for an image of a face ---
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
public class cFaceRecGUIMain extends JFrame implements ActionListener {
//Create menu bar items
private JMenuItem jmiLoadPicture, jmiExit, jmiEdit;
//Recognize Button
private JButton jbtRecognize;
//Labels with info about picture
private String lblName, lblDOB, lblNI, lblStaffID;
//Panel to hold an image
private ImagePanel imagePanel = new ImagePanel();
//File Chooser
JFileChooser jFileChooser = new JFileChooser();
//BitmapReader
//cGetBytes getBytes = new cGetBytes();
//Face database
cFaceRecData faceDatabase = new cFaceRecData();
//Set default window sizes
final int xSize = 600;
final int ySize = 400;
//Array for holding pixels
int pixels[];
//Labels for menu items
final String lbljmiLoadPicture = "Load Picture for recogniton";
final String lbljmiExit = "Exit";
final String lbljmiEdit = "Edit face database";
//Create the frame to enter details about people
cFaceRecGUIEDetails enterDetailsFrame = new cFaceRecGUIEDetails();
//BitmapReader
cGetBytes getImageBytes = new cGetBytes();
//Main method
public static void main(String[] args)
cFaceRecGUIMain programFrame = new cFaceRecGUIMain();
programFrame.pack();
programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
programFrame.setTitle("Face Recognizer");
programFrame.setSize(600, 400);
programFrame.setVisible(true);
//Constructor
public cFaceRecGUIMain() {
//Initialize menu bar
JMenuBar jmb = new JMenuBar();
setJMenuBar(jmb);
//Add menus
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
jmb.add(fileMenu);
JMenu faceMenu = new JMenu("Face");
fileMenu.setMnemonic('A');
jmb.add(faceMenu);
JMenu helpMenu = new JMenu("Help");
fileMenu.setMnemonic('H');
jmb.add(helpMenu);
//Add menu items
fileMenu.add(jmiLoadPicture =
new JMenuItem(lbljmiLoadPicture, 'L'));
fileMenu.addSeparator();
fileMenu.add(jmiExit = new JMenuItem(lbljmiExit, 'X'));
faceMenu.add(jmiEdit = new JMenuItem(lbljmiEdit, 'E'));
//Set keyboard accelerators
jmiExit.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
jmiLoadPicture.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
//Set up new panel
imagePanel.setBorder(new TitledBorder("Face"));
//Lay components on panel
imagePanel.setImageIcon(new ImageIcon("C:/Documents and Settings/" +
"Edmund Smith/My Documents/aface.bmp"));
imagePanel.add(jbtRecognize = new JButton("Recognize"),
BorderLayout.SOUTH);
setTitle("Face Recognizer");
//Labels to hold info
JPanel lblsAboutImagePanel = new JPanel();
lblsAboutImagePanel.setBorder(new TitledBorder("Details"));
lblsAboutImagePanel.setLayout(new GridLayout(4, 2));
lblsAboutImagePanel.add(new JLabel("Name"));
lblsAboutImagePanel.add(new JLabel(lblName));
lblsAboutImagePanel.add(new JLabel("DOB"));
lblsAboutImagePanel.add(new JLabel(lblDOB));
lblsAboutImagePanel.add(new JLabel("National insurance number"));
lblsAboutImagePanel.add(new JLabel(lblNI));
lblsAboutImagePanel.add(new JLabel("Staff ID"));
lblsAboutImagePanel.add(new JLabel(lblStaffID));
//Add the different panels to the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(imagePanel, BorderLayout.WEST);
getContentPane().add(lblsAboutImagePanel, BorderLayout.CENTER);
//Register listeners
jmiExit.addActionListener(this);
jmiLoadPicture.addActionListener(this);
jmiEdit.addActionListener(this);
//Create the frame where you can enter the details of a person
enterDetailsFrame.pack();
enterDetailsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
enterDetailsFrame.setTitle("Set up database");
enterDetailsFrame.setSize(xSize, ySize);
class edfClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
//Check to see if the record has been changed
if (enterDetailsFrame.isRecordModified)
JOptionPane.showConfirmDialog(
null,
"Do you want to save changes to this record?",
"Face datbase",
JOptionPane.YES_NO_CANCEL_OPTION);
if (enterDetailsFrame.newPeople.size() > 0)
//create a temporary array to store the new people
person[] newPersons = new
person[enterDetailsFrame.newPeople.size()];
//Copy the people in the vector to the array
person tempPerson;
for (int i = 0; i < newPersons.length; i++)
tempPerson =
(person)enterDetailsFrame.newPeople.elementAt(i);
newPersons.path = tempPerson.path;
newPersons[i].personsName = tempPerson.personsName;
newPersons[i].personsDOB = tempPerson.personsDOB;
newPersons[i].personsNI = tempPerson.personsNI;
newPersons[i].personsStaffID = tempPerson.personsStaffID;
//Create new database
allPeople outPeople =
new allPeople(enterDetailsFrame.peopleInfo, newPersons);
//Save the database with the added records
enterDetailsFrame.faceDatabase.saveDatabase(outPeople);
else
//Save the database with the same number of records
enterDetailsFrame.faceDatabase.saveDatabase(
enterDetailsFrame.peopleInfo);
//Set the actions to happen when windows are closed
enterDetailsFrame.addWindowListener(new edfClosingListener());
closeWindow closeMainFrame = new closeWindow();
addWindowListener(closeMainFrame);
public void actionPerformed(ActionEvent e)
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JMenuItem) {
if (lbljmiExit.equals(actionCommand))
System.exit(0);
else if (lbljmiLoadPicture.equals(actionCommand))
open();
else if (lbljmiEdit.equals(actionCommand)) {
enterDetailsFrame.setVisible(true);
//No records have been modified
enterDetailsFrame.isRecordModified = false;
//Open a file
private void open() {
if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
try {
//Get the file name
String fileName = jFileChooser.getSelectedFile().getPath();
//Display the image
ImageIcon imagei = new ImageIcon(fileName);
imagePanel.setImageIcon(imagei);
//Set size of array for holiding bytes in the image
pixels =
new int[51 * 55];
//Get the pixels
// getBytes.getBMPImage(new FileInputStream(new File(fileName)), pixels);
catch (Exception e) {
System.out.print(e);
class ImagePanel extends JPanel {
//Label to hold the face
private JLabel jlblFace = new JLabel();
//Constructor
public ImagePanel() {
setLayout(new BorderLayout());
add(jlblFace, BorderLayout.CENTER);
//Set image and show it
public void setImageIcon(ImageIcon icon) {
jlblFace.setIcon(icon);
Dimension dimension =
new Dimension(icon.getIconWidth(), icon.getIconHeight());
jlblFace.setPreferredSize(dimension);
//--- cFaceRecGUIEDetails.java ---
//--- Edmund Smith 06/10/04 ---
//--- Allows the user to enter details about a person, view the ---
//--- database and add people to the database ---
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
class cFaceRecGUIEDetails extends JFrame implements KeyListener, ActionListener
//Buttons to navigate the database
private JButton jbtPrevious, jbtNext;
//Button to load a face
private JButton jbtLoadFace;
//Fields to display info about the person
private JTextField jtfName, jtfDOB, jtfNI, jtfStaffID;
//Panel to hold an image
private ImagePanel imagePanel = new ImagePanel();
//File Chooser
private JFileChooser jFileChooser = new JFileChooser();
//Variable to tell whether record has been modified
boolean isRecordModified = false;
//Tells which record current being veiwed/changed
int currentRecord = 0;
//Stores new people to be added to database
Vector newPeople = new Vector();
//Face database
cFaceRecData faceDatabase;
public allPeople peopleInfo;
//Default Constructor
public cFaceRecGUIEDetails()
//Get the face database
faceDatabase = new cFaceRecData();
peopleInfo = faceDatabase.restoreDatabase();
//Panel to hold two buttons to navigate the database
JPanel jpButtons = new JPanel();
//Add navigation buttons to panel
jpButtons.setLayout(new FlowLayout());
jpButtons.add(jbtPrevious = new JButton());
jpButtons.add(jbtNext = new JButton());
//Set button text
jbtPrevious.setText("<");
jbtNext.setText(">");
//Panel to hold details about the person
JPanel jpDetails = new JPanel();
jpDetails.setBorder(new TitledBorder("Details"));
jpDetails.setLayout(new GridLayout(4, 2));
jpDetails.add(new JLabel("Name"));
jpDetails.add(jtfName = new JTextField());
jpDetails.add(new JLabel("DOB"));
jpDetails.add(jtfDOB = new JTextField());
jpDetails.add(new JLabel("National insurance number"));
jpDetails.add(jtfNI = new JTextField());
jpDetails.add(new JLabel("StaffID"));
jpDetails.add(jtfStaffID = new JTextField());
try
jtfName.setText(peopleInfo.people[currentRecord].personsName);
/* jtfDOB.setText(String.valueOf(
peopleInfo.people[currentRecord].personsDOB));
jtfNI.setText(String.valueOf(
peopleInfo.people[currentRecord].personsNI));
jtfStaffID.setText(String.valueOf(
peopleInfo.people[currentRecord].personsStaffID));*/
catch (Exception e)
System.out.print(e);
imagePanel.setBorder(new TitledBorder("Face"));
imagePanel.add(jbtLoadFace = new JButton("Load Face"));
//Main body panel
JPanel jpBody = new JPanel();
jpBody.add(imagePanel, BorderLayout.WEST);
jpBody.add(jpDetails, BorderLayout.CENTER);
//Place panels on frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(jpBody, BorderLayout.CENTER);
getContentPane().add(jpButtons, BorderLayout.SOUTH);
//Register listeners
jbtLoadFace.addActionListener(this);
jbtPrevious.addActionListener(this);
jbtNext.addActionListener(this);
//jtfName.addKeyListener(this);
jtfDOB.addKeyListener(this);
jtfNI.addKeyListener(this);
jtfStaffID.addKeyListener(this);
public void actionPerformed(ActionEvent e)
boolean goOn = false;
if (e.getSource() == jbtLoadFace)
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
if (e.getSource() == jbtPrevious || e.getSource() == jbtNext)
if (isRecordModified == true)
int result = JOptionPane.showConfirmDialog(
null,
"Do you want to save changes to this record?",
"Face datbase",
JOptionPane.YES_NO_CANCEL_OPTION);
switch (result)
case JOptionPane.YES_OPTION:
saveRecordChanges();
goOn = true;
break;
case JOptionPane.NO_OPTION:
goOn = true;
break;
if (goOn == true)
//If user has not cancelled move to another record
if (e.getSource() == jbtPrevious)
moveForwardToRecord(true);
else
moveForwardToRecord(false);
public void saveRecordChanges()
boolean alreadyInDatabase = false;
//Put the values in the field into the database
try
if (currentRecord < peopleInfo.people.length)
alreadyInDatabase = true;
peopleInfo.people[currentRecord].personsName =
jtfName.getText();
peopleInfo.people[currentRecord].personsDOB =
Integer.parseInt(jtfDOB.getText());
peopleInfo.people[currentRecord].personsNI =
Integer.parseInt(jtfNI.getText());
peopleInfo.people[currentRecord].personsStaffID =
Integer.parseInt(jtfStaffID.getText());
catch (Exception e)
System.out.print(e);
if (alreadyInDatabase = false)
newPeople.add(new person("", jtfName.getText(),
Integer.parseInt(jtfDOB.getText()),
Integer.parseInt(jtfNI.getText()),
Integer.parseInt(jtfStaffID.getText())));
public void moveForwardToRecord(boolean forward)
isRecordModified = false;
setTitle("Set up datbase");
if (forward)
else
public void keyPressed(KeyEvent e)
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
public void keyReleased(KeyEvent e) {
public void keyTyped(KeyEvent e) {
//Open a file
private void open()
if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
String fileName = jFileChooser.getSelectedFile().getPath();
imagePanel.setImageIcon(new ImageIcon(fileName));
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
//--- cFaceRecData.java ---
//--- Edmund Smith 18/11/04 ---
//--- Stores and retrives info about a person and their face ---
import java.io.*;
import java.util.*;
class cFaceRecData
//The location of the database
final String dbPath = "C:/Documents and Settings/" +
"Edmund Smith/My Documents/fdatabase.dat";
//The data
allPeople inPeople;
//Saves the file
void saveDatabase(allPeople outPeople)
try
//Object output stream
ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream(dbPath));
//Write the object
out.writeObject(outPeople);
//Close the object output stream
out.close();
catch (IOException ex)
System.out.println(ex);
//Opens the file
allPeople restoreDatabase()
try
//Object input steam
ObjectInputStream in =
new ObjectInputStream(new FileInputStream(dbPath));
//Get the database
inPeople = (allPeople)in.readObject();
//Close the input stream
in.close();
catch (IOException ex)
System.out.println(ex);
catch (ClassNotFoundException ex)
System.out.println(ex);
//Return the database
return inPeople;
//Holds the info about a person
class person
//Stores the location of the image on disk
String path;
//Stores the name of a person
String personsName;
//Stores the dob of a person, their NI no, and employee ID
int personsDOB, personsNI, personsStaffID;
//Default constructor
public person(String inPath, String inName, int inDOB, int inNI,
int inStaffID)
//Stores the values which passed in
path = inPath;
personsName = inName;
personsDOB = inDOB;
personsNI = inNI;
personsStaffID = inStaffID;
//The database
class allPeople
person[] people;
int numPeople;
//Default constructor
public allPeople(person[] persons)
//Create the array to hold the people
people = new person[persons.length];
for (int i = 0; i < persons.length; i++)
people[i] = new person(persons[i].path,
persons[i].personsName,
persons[i].personsDOB,
persons[i].personsStaffID,
persons[i].personsNI);
//Updates the database
public allPeople(allPeople thePeople, person[] persons)
//Create the array to hold the people
int totalPeople = thePeople.people.length + persons.length;
people = new person[totalPeople];
for (int i = 0; i < totalPeople; i++)
if (i < thePeople.people.length)
people[i] = new person(thePeople.people[i].path,
thePeople.people[i].personsName,
thePeople.people[i].personsDOB,
thePeople.people[i].personsStaffID,
thePeople.people[i].personsNI);
else
people[i] = new person(persons[i].path,
persons[i].personsName,
persons[i].personsDOB,
persons[i].personsStaffID,
persons[i].personsNI);When posting code to the forum, please use the code button.
Also, post the exception message and indicate the line that gives the error. -
Hi,
I'm giving Java another try and I'm working through the short courses and Magercises. I'm having a problem with the code below.
<pre>
package examples.myapps.test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FirstSwing extends JFrame {
// The initial width and height of the frame
public static int WIDTH = 300;
public static int HEIGHT = 300;
// images for buttons
public Icon bee = new ImageIcon("bee.gif");
public Icon dog = new ImageIcon("dog.gif");
public FirstSwing(String lab) {
super(lab);
JButton top = new JButton("A bee", bee);
top.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("bee");
JButton bottom = new JButton("and a dog", dog);
bottom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("dog");
top.setMnemonic (KeyEvent.VK_B);
bottom.setMnemonic (KeyEvent.VK_D);
Container content = getContentPane();
content.setLayout(new GridLayout(2,1));
content.add(top);
content.add(bottom);
public static void main(String args[]) {
FirstSwing frame = new FirstSwing("First Swing Stuff");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
</pre>
The problem is that the icons don't appear. The image files (bee.gif and dog.gif) are in the same directory as the source file. I get no errors, the images just do not appear in the button like they are supposed to according to the example. What am I doing wrong?
Thanks,
MikeI had the same problem with ONE STUDIO 4 trying the example below ... the image is in the same directory as the class is and it�s ok ... it only work fine if I set the full absolute path, but not with a relative one ....
But I tryed the same example in the same dir with Jbuider 3 ... and it works fine and the ImageIcon appears .... I think it�s something related to Filesystems in the Studio One ....
Jo�o Carlos
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelTest extends JFrame {
private JLabel label1, label2, label3;
public LabelTest()
super( "Testing JLabel" );
Container c = getContentPane();
c.setLayout( new GridLayout(3,1) );
// JLabel constructor with a string argument
label1 = new JLabel( "Label with text" );
label1.setToolTipText( "This is label1" );
c.add( label1 );
// JLabel constructor with string, Icon and
// alignment arguments
//Icon bug = new ImageIcon( "C:\\Documents and Settings\\Administrador\\examples\\ch12\\fig12_04\\bug1.GIF" );
Icon bug = new ImageIcon( "bug1.GIF" );
label2 = new JLabel( "Label with text and icon",
bug, SwingConstants.LEFT );
label2.setToolTipText( "This is label2" );
c.add( label2 );
// JLabel constructor no arguments
label3 = new JLabel();
label3.setText( "Label with icon and text at bottom" );
label3.setIcon( bug );
label3.setHorizontalTextPosition(
SwingConstants.CENTER );
label3.setVerticalTextPosition(
SwingConstants.BOTTOM );
label3.setToolTipText( "This is label3" );
c.add( label3 );
setSize( 275, 170 );
show();
public static void main( String args[] )
LabelTest app = new LabelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
System.exit( 0 );
if your source is in
C:\foo\examples\myapps\test
put the gifs in
C:\fooThanks, but this isn't working either. My source is
in:
c:\java-ide\sampledir\examples\myapps\test.
I've placed the gifs in c:\java-ide,
c:\java-ide\sampledir, c:\java-ide\sampledir\examples,
etc. (all directories) and nothing shows the gifs in
the buttons. Any ideas? -
Hi i need help with getting my homework for school
im in a nine week class that ends tommorw and need help go\etting my program working properly these are the requirements ofr the assignments:
Modify the Inventory Program by adding a button to the GUI that allows the user to move
to the first item, the previous item, the next item, and the last item in the inventory. If the
first item is displayed and the user clicks on the Previous button, the last item should
display. If the last item is displayed and the user clicks on the Next button, the first item
should display.
· Add a company logo to the GUI using Java graphics classes.
Modify the Inventory Program to include an Add button, a Delete button, and a Modifybutton on the GUI. These buttons should allow the user to perform the corresponding actions on the item name, the number of units in stock, and the price of each unit. An item added to the inventory should have an item number one more than the previous last item. Add a Save button to the GUI that saves the inventory to a C:\data\inventory.dat file. Use exception handling to create the directory and file if necessary. Add a search button to the GUI that allows the user to search for an item in the inventory by the product name. If the product is not found, the GUI should display an appropriate message. If the product is found, the GUI should display that products information in the GUI. Post final .class and .java files as an attachment.
this is what i have there are three java files im puttong in here
first is the panel frame
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Component;
import javax.swing.SwingConstants;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.util.*;
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.NumberFormat;
public class PanelFrame extends JFrame
private JPanel buttonJPanel; // panel to hold buttons
private JButton buttons[]; // array of buttons
private JLabel label1; // JLabel iventory number
private JLabel label2; // JLabel product name
private JLabel label3; // JLabel product price
private JLabel label4; // JLabel product in stock
private String p_ProductName; // private variable for the employee name.
private int p_UnitCount; // private variable for the hours worked.
private double p_UnitPrice; // private variable for the hourly wage.
private int p_ItemNumber; // private inventory number
//create inventory object
Inventory myInventory = new Inventory ();
// no-argument constructor
public PanelFrame()
super( "Panel Demo" );
//Add items to the inventory within the Invntory
myInventory.addItem(new productinfo(1,"Html a Begginers Guide",14,29.99));
myInventory.addItem(new productinfo(2,"Html 4 for Dummies",6,29.99));
myInventory.addItem(new productinfo(3,"Visio Step by Step",7,24.99));
myInventory.addItem(new productinfo(4,"APA Publication Manual",14,47.99));
myInventory.addItem(new productinfo(5,"The Gregg Reference Manual",14,37.56));
setLayout( new FlowLayout() ); // set frame layout
// JLabel constructor with a string argument
label1 = new JLabel( "Inventory Number:%s: %d\n ",p_ItemNumber );
label1.setToolTipText( "This is Inventory number" );
add( label1 ); // add label1 to JFrame
label2 = new JLabel( "\n\nProduct Name: %s: %s\n", p_ProductName);
label2.setToolTipText( "This is Product Name" );
add( label2 ); // add label1 to JFrame
label3 = new JLabel( "\n\nPrice : %s:$%.2f\n",p_UnitPrice );
label3.setToolTipText( "This is product Price");
add( label3 ); // add label1 to JFrame
label4 = new JLabel( "\n\nQuanity %s: %d\n",p_UnitCount);
label4.setToolTipText( "This is Quanity in stock: " );
add( label4 ); // add label1 to JFrame
buttons = new JButton[ 4 ]; // create buttons array
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) );
String names[] = { "First", "Previous", "Next", "Last" };
JButton buttons[] = new JButton[ names.length ];
// create and add buttons
for ( int count = 0; count < buttons.length; count++ )
buttons[ count ] = new JButton( names[ count ] );
buttonJPanel.add( buttons[ count ] ); // add button to panel
} // end for
// setup the logo for the GUI ...image needs to be in same directory as source code
URL url = this.getClass().getResource("book103.gif");
Image img = Toolkit.getDefaultToolkit().getImage(url);
// scale the image so that it'll fit in the GUI
Image scaledImage = img.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING);
// create a JLabel with the image as the label's Icon
Icon logoIcon = new ImageIcon(scaledImage);
JLabel companyLogoLabel = new JLabel(logoIcon);
companyLogoLabel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
// add the logo to the GUI
getContentPane().add(companyLogoLabel, BorderLayout.WEST);
add( buttonJPanel, BorderLayout.SOUTH ); // add panel to JFrame
} // end PanelFrame constructor
} // end class PanelFramethis is the original part again with the code tag added
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Component;
import javax.swing.SwingConstants;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.util.;
import java.text.NumberFormat;
import javax.swing.;
import java.awt.;
import java.awt.event.;
import java.net.URL;
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.NumberFormat;
public class PanelFrame extends JFrame
private JPanel buttonJPanel; // panel to hold buttons
private JButton buttons[]; // array of buttons
private JLabel label1; // JLabel iventory number
private JLabel label2; // JLabel product name
private JLabel label3; // JLabel product price
private JLabel label4; // JLabel product in stock
private String p_ProductName; // private variable for the employee name.
private int p_UnitCount; // private variable for the hours worked.
private double p_UnitPrice; // private variable for the hourly wage.
private int p_ItemNumber; // private inventory number
//create inventory object
Inventory myInventory = new Inventory ();
// no-argument constructor
public PanelFrame()
super( "Panel Demo" );
//Add items to the inventory within the Invntory
myInventory.addItem(new productinfo(1,"Html a Begginers Guide",14,29.99));
myInventory.addItem(new productinfo(2,"Html 4 for Dummies",6,29.99));
myInventory.addItem(new productinfo(3,"Visio Step by Step",7,24.99));
myInventory.addItem(new productinfo(4,"APA Publication Manual",14,47.99));
myInventory.addItem(new productinfo(5,"The Gregg Reference Manual",14,37.56));
setLayout( new FlowLayout() ); // set frame layout
// JLabel constructor with a string argument
label1 = new JLabel( "Inventory Number:%s: %d\n ",p_ItemNumber );
label1.setToolTipText( "This is Inventory number" );
add( label1 ); // add label1 to JFrame
label2 = new JLabel( "\n\nProduct Name: %s: %s\n", p_ProductName);
label2.setToolTipText( "This is Product Name" );
add( label2 ); // add label1 to JFrame
label3 = new JLabel( "\n\nPrice : %s:$%.2f\n",p_UnitPrice );
label3.setToolTipText( "This is product Price");
add( label3 ); // add label1 to JFrame
label4 = new JLabel( "\n\nQuanity %s: %d\n",p_UnitCount);
label4.setToolTipText( "This is Quanity in stock: " );
add( label4 ); // add label1 to JFrame
buttons = new JButton[ 4 ]; // create buttons array
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout( 1, buttons.length ) );
String names[] = { "First", "Previous", "Next", "Last" };
JButton buttons[] = new JButton[ names.length ];
// create and add buttons
for ( int count = 0; count < buttons.length; count++ )
buttons[ count ] = new JButton( names[ count ] );
buttonJPanel.add( buttons[ count ] ); // add button to panel
} // end for
// setup the logo for the GUI ...image needs to be in same directory as source code
URL url = this.getClass().getResource("book103.gif");
Image img = Toolkit.getDefaultToolkit().getImage(url);
// scale the image so that it'll fit in the GUI
Image scaledImage = img.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING);
// create a JLabel with the image as the label's Icon
Icon logoIcon = new ImageIcon(scaledImage);
JLabel companyLogoLabel = new JLabel(logoIcon);
companyLogoLabel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
// add the logo to the GUI
getContentPane().add(companyLogoLabel, BorderLayout.WEST);
add( buttonJPanel, BorderLayout.SOUTH ); // add panel to JFrame
} // end PanelFrame constructor
} // end class PanelFrame -
Class, interface, or enum expected error
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class InventoryFinal
//main method begins execution of java application
public static void main(final String args[])
int i; // varialbe for looping
double total = 0; // variable for total inventory
final int dispProd = 0; // variable for actionEvents
// Instantiate a product object
final ProductAdd[] nwProduct = new ProductAdd[5];
// Instantiate objects for the array
for (i=0; i<5; i++)
nwProduct[0] = new ProductAdd("CD", 10, 18, 12.00, "Jewel Case");
nwProduct[1] = new ProductAdd("Blue Ray", 9, 20, 25.00, "HD");
nwProduct[2] = new ProductAdd("Game", 8, 30, 40.00, "Game Case");
nwProduct[3] = new ProductAdd("iPod", 7, 40, 50.00, "Box");
nwProduct[4] = new ProductAdd("DVD", 6, 15, 15.00, "DVD Case");
for (i=0; i<5; i++)
total += nwProduct.length; // calculate total inventory cost
final JButton firstBtn = new JButton("First"); // first button
final JButton prevBtn = new JButton("Previous"); // previous button
final JButton nextBtn = new JButton("Next"); // next button
final JButton lastBtn = new JButton("Last"); // last button
final JButton AddBtn = new JButton("Add"); // Add button
final JButton DeleteBtn = new JButton("Delete"); // Delete button
final JButton ModifyBtn = new JButton("Modify"); // Modify button
final JButton SaveBtn = new JButton("Save"); // Save button
final JButton SearchBtn = new JButton("Search"); // Search button
final JLabel label; // logo
final JTextArea textArea; // text area for product list
final JPanel buttonJPanel; // panel to hold buttons
//JLabel constructor for logo
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
buttonJPanel = new MyJPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
// add buttons to buttonPanel
buttonJPanel.add(firstBtn);
buttonJPanel.add(prevBtn);
buttonJPanel.add(nextBtn);
buttonJPanel.add(lastBtn);
buttonJPanel.add(AddBtn);
buttonJPanel.add(DeleteBtn);
buttonJPanel.add(ModifyBtn);
buttonJPanel.add(SaveBtn);
buttonJPanel.add(SearchBtn);
textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
// add total inventory value to GUI
textArea.append("/nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
textArea.setEditable(false); // make text uneditable in main display
JFrame invFrame = new JFrame(); // create JFrame container
invFrame.setLayout(new BorderLayout()); // set layout
invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
invFrame.setTitle("CD & DVD Inventory"); // set JFrame title
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
//invFrame.pack();
invFrame.setSize(600, 600); // set size of JPanel
invFrame.setLocationRelativeTo(null); // set screen location
invFrame.setVisible(true); // display window
// assign actionListener and actionEvent for each button
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end firstBtn actionEvent
}); // end firstBtn actionListener
textArea.setText(nwProduct[4]+"n");
prevBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[4]+"\n");
} // end prevBtn actionEvent
}); // end prevBtn actionListener
textArea.setText(nwProduct[4]+"n");
nextBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[2]+"\n");
} // end nextBtn actionEvent
}); // end nextBtn actionListener
textArea.setText(nwProduct[4]+"n");
lastBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[3]+"\n");
} // end lastBtn actionEvent
}); // end lastBtn actionListener
textArea.setText(nwProduct[4]+"n");// assign actionListener and actionEvent for each button
AddBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end AddBtn actionEvent
}); // end AddBtn actionListener
textArea.setText(nwProduct[4]+"n");
// assign actionListener and actionEvent for each button
DeleteBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end DeleteBtn actionEvent
}); // end DeleteBtn actionListener
textArea.setText(nwProduct[4]+"n");
// assign actionListener and actionEvent for each button
ModifyBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end ModifyBtn actionEvent
}); // end ModifyBtn actionListener
textArea.setText(nwProduct[4]+"n");
// assign actionListener and actionEvent for each button
SaveBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end SaveBtn actionEvent
}); // end SaveBtn actionListener
textArea.setText(nwProduct[4]+"n");
// assign actionListener and actionEvent for each button
SearchBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end SearchBtn actionEvent
}); // end SearchBtn actionListener
textArea.setText(nwProduct[4]+"n");
// prevBtn.addActionListener(new ActionListener()
// public void actionPerformed(ActionEvent ae)
// dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
// textArea.setText(nwProduct.display(dispProd)+"\n");
// } // end prevBtn actionEvent
// }); // end prevBtn actionListener
} // end main
} // end class Inventory4
class Product
protected String prodName; // name of product
protected int itmNumber; // item number
protected int units; // number of units
protected double price; // price of each unit
protected double value; // value of total units
public Product(String name, int number, int unit, double each) // Constructor for class Product
prodName = name;
itmNumber = number;
units = unit;
price = each;
} // end constructor
public void setProdName(String name) // method to set product name
prodName = name;
public String getProdName() // method to get product name
return prodName;
public void setItmNumber(int number) // method to set item number
itmNumber = number;
public int getItmNumber() // method to get item number
return itmNumber;
public void setUnits(int unit) // method to set number of units
units = unit;
public int getUnits() // method to get number of units
return units;
public void setPrice(double each) // method to set price
price = each;
public double getPrice() // method to get price
return price;
public double calcValue() // method to set value
return units * price;
} // end class Product
class ProductAdd extends Product
private String feature; // variable for added feature
public ProductAdd(String name, int number, int unit, double each, String addFeat)
// call to superclass Product constructor
super(name, number, unit, each);
feature = addFeat;
}// end constructor
public void setFeature(String addFeat) // method to set added feature
feature = addFeat;
public String getFeature() // method to get added feature
return feature;
public double calcValueRstk() // method to set value and add restock fee
return units * price * 0.10;
public String toString()
return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n",
getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
} // end class ProductAdd
class MyJPanel extends JPanel
//private static Random generator = new Random();
private ImageIcon picture; //image to be displayed
// load image
public MyJPanel()
picture = new ImageIcon("mypicture.png"); // set icon
} // end MyJPanel constructor
// display imageIcon on panel
public void paintComponent( Graphics g )
super.paintComponent( g );
picture.paintIcon( this, g, 0, 0 ); // display icon
} // end method paintComponent
// return image dimensions
//public Dimension getPreferredSize()
// return new Dimension ( picture.getIconWidth(),
//picture.getIconHeight() );
} // end method getPreferredSize
} // end class MyJPanel
import java.io.File;
import java.io.IOException;
public class FileAccessDemo
public static void main( String[] args ) throws IOException
// declare variables
String formatStr = "%s exists in %s? %b\n\n";
// processing and output
File file1 = new File( "studentScores.txt" ); // create a File object
System.out.printf
(formatStr, file1.getName(), file1.getAbsolutePath(), file1.exists());
// processing and output
File folder1 = new File( "c:/personnel/" ); // create a File object
folder1.mkdir(); // make a directory
File file2 = new File( "/personnel/faculty.txt" );
file2.createNewFile(); // create a new file
System.out.printf
( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
// processing and output
file2.delete(); // delete a file, but not the directory
System.out.printf
( formatStr, file2.getName(), file2.getAbsolutePath(), file2.exists() );
} // end main
} // end class
I need help in resolving this error.
ThanksThat code isn't where your error is. Here's the errors I get compiling your code:
H:\java>javac InventoryFinal.java
InventoryFinal.java:78: ')' expected
textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
^
InventoryFinal.java:78: ';' expected
textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n
^
InventoryFinal.java:340: class, interface, or enum expected
import java.io.File;
^
InventoryFinal.java:341: class, interface, or enum expected
import java.io.IOException;
^
4 errorsThe last two errors are on your import statements, which can't be in the middle of a source file. The first two are on this line:
textArea.append("/nTotal value of Inventory "new java.text.DecimalFormat("$0.00").format(total)"\n\n");Which certainly isn't a legal line of Java code. If you want to connect multiple Strings you need to use the "+" operator. -
Positioning different objects over containers
Dear Forum members,
Thanks to the help of woogly, I have a grid in my program, so my main looks like this:
public class Example extends JFrame {
public static void main(String[] args) {
new Example();
public Example() {
super("Grid Example");
setSize(new Dimension(300,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(new Grid(),BorderLayout.CENTER);
show();
1. Please tell me how to change the main to put two boxes with labels in the bottom of the grid so it will look like:
G R I D
Labl1 labl2
(The grid and at the bottom 2 labels side by side)
2. Do you now what is the difference between:
BorderLayout.CENTER and
SwingConstants.CENTER
What CENTER each of the mean and when to use each (CENTER is only for the example)?
3. I have seen a code using both of them. Like:
getContentPane().add(new JLabel("Player1", SwingConstants.CENTER),
BorderLayout.SOUTH);
Why both ?
Sorry I have so little Duke Dollars to offer..
Thanks
EranHi.
What you need is to specify a LayoutManager that will actually do the layout in your ContentPane. Those constants are simply instructions to the LayoutManager where and how to place the sub-component.
The code that does what you ask could look like
public class Example extends JFrame {
public static void main(String[] args) {
new Example();
public Example() {
super("Grid Example");
setSize(new Dimension(300,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout()); // set the LayoutManager
getContentPane().add(new Grid(),BorderLayout.CENTER);
JPanel labels = new JPanel();
labels.setLayout(new FlowLayout()); // or could be 'new GridLayout(1, 2)'
labels.add(new JLabel("Label 1"));
labels.add(new JLabel("Label 2"));
getContentPane().add(labels, BorderLayout.SOUTH);
show();
}Those two constnts are very different because
BorderLayout.CENTER is a string of value "Center" and
SwingConstants.CENTER is an int of value 0.
In this code
getContentPane().add(new JLabel("Player1", SwingConstants.CENTER), BorderLayout.SOUTH);
the
SwingConstants.CENTER is a second argument to the JLabel constructor indicating on how JLabel sould draw its text, and the BorderLayout.SOUTH is a second argument to add method.
Read about LayoutManager interface and implementing classes in the API docs
http://java.sun.com/j2se/1.4.2/docs/api/java/awt/LayoutManager.html
and there sould also be some tutorials on Layouts.
Filip -
Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item
should display. the GUI using Java graphics classes.
? Add a company logo to? Post as an attachment Course Syllabus
here is my code // created by Nicholas Baatz on July 24,2007
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Inventory2
//main method begins execution of java application
public static void main(final String args[])
int i; // varialbe for looping
double total = 0; // variable for total inventory
final int dispProd = 0; // variable for actionEvents
// Instantiate a product object
final ProductAdd[] nwProduct = new ProductAdd[5];
// Instantiate objects for the array
for (i=0; i<5; i++)
nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
for (i=0; i<5; i++)
total += nwProduct.length; // calculate total inventory cost
final JButton firstBtn = new JButton("First"); // first button
final JButton prevBtn = new JButton("Previous"); // previous button
final JButton nextBtn = new JButton("Next"); // next button
final JButton lastBtn = new JButton("Last"); // last button
final JLabel label; // logo
final JTextArea textArea; // text area for product list
final JPanel buttonJPanel; // panel to hold buttons
//JLabel constructor for logo
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
// add buttons to buttonPanel
buttonJPanel.add(firstBtn);
buttonJPanel.add(prevBtn);
buttonJPanel.add(nextBtn);
buttonJPanel.add(lastBtn);
textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
// add total inventory value to GUI
textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
textArea.setEditable(false); // make text uneditable in main display
JFrame invFrame = new JFrame(); // create JFrame container
invFrame.setLayout(new BorderLayout()); // set layout
invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
invFrame.setTitle("Office Min Inventory"); // set JFrame title
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
//invFrame.pack();
invFrame.setSize(400, 400); // set size of JPanel
invFrame.setLocationRelativeTo(null); // set screem location
invFrame.setVisible(true); // display window
// assign actionListener and actionEvent for each button
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end firstBtn actionEvent
}); // end firstBtn actionListener
textArea.setText(nwProduct[4]+"n");
// prevBtn.addActionListener(new ActionListener()
// public void actionPerformed(ActionEvent ae)
// dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
// textArea.setText(nwProduct.display(dispProd)+"\n");
// } // end prevBtn actionEvent
// }); // end prevBtn actionListener
} // end main
} // end class Inventory2
class Product
protected String prodName; // name of product
protected int itmNumber; // item number
protected int units; // number of units
protected double price; // price of each unit
protected double value; // value of total units
public Product(String name, int number, int unit, double each) // Constructor for class Product
prodName = name;
itmNumber = number;
units = unit;
price = each;
} // end constructor
public void setProdName(String name) // method to set product name
prodName = name;
public String getProdName() // method to get product name
return prodName;
public void setItmNumber(int number) // method to set item number
itmNumber = number;
public int getItmNumber() // method to get item number
return itmNumber;
public void setUnits(int unit) // method to set number of units
units = unit;
public int getUnits() // method to get number of units
return units;
public void setPrice(double each) // method to set price
price = each;
public double getPrice() // method to get price
return price;
public double calcValue() // method to set value
return units * price;
} // end class Product
class ProductAdd extends Product
private String feature; // variable for added feature
public ProductAdd(String name, int number, int unit, double each, String addFeat)
// call to superclass Product constructor
super(name, number, unit, each);
feature = addFeat;
}// end constructor
public void setFeature(String addFeat) // method to set added feature
feature = addFeat;
public String getFeature() // method to get added feature
return feature;
public double calcValueRstk() // method to set value and add restock fee
return units * price * 0.05;
public String toString()
return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
} // end class ProductAddI can not get all the buttons to work and do not know why can someone help meYou have to have your code formatted correctly to begin with before you add the code tags. All your current code is left-justified and is not indented correctly.
I only see that you've added an actionlistener to the "first" button.
I recommend that you:
1) again, do this first in a nonGUI class, then use this nonGUI class in your GUI class.
2) Have a integer variable that holds the location of the current Product that your application is pointing to.
3) Have a method called getProduct(int index) that returns the product that is at the location specified by the index in your array / arraylist / or whatever collection that you are using.
4) Have your first button set index to 0 and then call getProduct(index).
5) Have your last button set your index to the last product in your collection (i.e.: index = productCollection.length - 1 if this is an array), and then call getProduct(index).
5) Have your next button increment your index up to the maximum allowed and then call getProduct(index). If it's an array it goes up to the array length - 1.
6) If you want the next button to cause the index to roll over to the first, when you are at the last then then increment the index and mod it ("%" operator) by the length of the array... -
Problem showing imageicon in cell using TableCellRenderer
Hi all,
I am using a tablecellrenderer to display an icon in a particular jtable column to reflect a value in the underlying model.
When I do this, the column does not display the ImageIcon at all. My code for the CellRenderer is below.
It should also be noted that I use another table cell renderer on the whole table to remove the line around the selection on the selected cell. This all works fine.
public class StatusCellRenderer implements TableCellRenderer {
private static ImageIcon blueIcon = new ImageIcon("images/blue.gif");
private static ImageIcon redIcon = new ImageIcon("images/red.gif");
private JLabel label = new JLabel();
// Constructors
public StatusCellRenderer() {
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
// TableCellRenderer interface implementation
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (Integer.parseInt(value.toString()) > 0){
label.setIcon(blueIcon);
label.repaint();
return label;
else if (Integer.parseInt(value.toString()) == 0){
label.setIcon(redIcon);
label.repaint();
return label;
else
return null;
}First question: What do you see in the column where you expect the Icon?
First suggestion: extend DefaultTableCellRenderer instead of implementing TableCellRenderer interface. Just a suggestion.
second question: Have you set the renderer for the class of objects in target column to be the StatusCellRenderer?
As camrickr says you need to post a little more code. Maybe a SMALL demo program illustrating your problem. Use code tags for legibility.
Cheers
DB -
Centralizing text in JButtons in a JPanel with a boxLayout doesn't work!!!
Hello, I tried to use the JLabel constructor:
JLabel saveButtonLabel = new JLabel("Save", JLabel.CENTER);
and then put it in the JPanel:
controlPanel.add(saveButton);
but the text is still aligned to the left. What have I done wrong please!!!
I am using the folling to seperate the JButtons, if this is at all affecting it:
controlPanel.add(Box.createHorizontalGlue());
controlPanel.add(Box.createRigidArea(new Dimension(13, 0)));
regardsIs your control panel being added to a border layout, and if so, what section (SOUTH?)
-
I can't figure out how to get this to work correctly. I need the GUI to display one product at a time and add buttons "next, previous, last, first". My main problem is not being able to step through displaying the arrat one product at a time. That of course prevents me from applying any button actions. Any help for this Java moron would be greatly appreciated.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Inventory7 // Main class
//main method begins execution of java application
public static void main(String args[])
int i; // varialbe for looping
double total = 0; // variable for total inventory
final int dispProd = 0; // variable for actionEvents
// Instantiate a product object
final ProductAdd[] nwProduct = new ProductAdd[5];
// Instantiate objects for the array
for (i=0; i<5; i++)
nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
for (i=0; i<5; i++)
total += nwProduct.calcValue(); // calculate total inventory cost
final JButton firstBtn = new JButton("First"); // first button
final JButton prevBtn = new JButton("Previous"); // previous button
final JButton nextBtn = new JButton("Next"); // next button
final JButton lastBtn = new JButton("Last"); // last button
final JLabel label; // logo
final JTextArea textArea; // text area for product list
final JPanel buttonJPanel; // panel to hold buttons
//JLabel constructor for logo
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
// add buttons to buttonPanel
buttonJPanel.add(firstBtn);
buttonJPanel.add(prevBtn);
buttonJPanel.add(nextBtn);
buttonJPanel.add(lastBtn);
textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
// add total inventory value to GUI
textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
textArea.setEditable(false); // make text uneditable in main display
JFrame invFrame = new JFrame(); // create JFrame container
invFrame.setLayout(new BorderLayout()); // set layout
invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
invFrame.setTitle("Office Min Inventory"); // set JFrame title
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
//invFrame.pack();
invFrame.setSize(400, 400); // set size of JPanel
invFrame.setLocationRelativeTo(null); // set screem location
invFrame.setVisible(true); // display window
// assign actionListener and actionEvent for each button
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[0]+"\n");
} // end firstBtn actionEvent
}); // end firstBtn actionListener
lastBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
textArea.setText(nwProduct[4]+"n");
} // end lastBtn actionEvent
}); // end lastBtn actionListener
// prevBtn.addActionListener(new ActionListener()
// public void actionPerformed(ActionEvent ae)
// dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
// textArea.setText(nwProduct.display(dispProd)+"\n");
// } // end prevBtn actionEvent
// }); // end prevBtn actionListener
} // end main
} // end class Inventory6
class Product
protected String prodName; // name of product
protected int itmNumber; // item number
protected int units; // number of units
protected double price; // price of each unit
protected double value; // value of total units
public Product(String name, int number, int unit, double each) // Constructor for class Product
prodName = name;
itmNumber = number;
units = unit;
price = each;
} // end constructor
public void setProdName(String name) // method to set product name
prodName = name;
public String getProdName() // method to get product name
return prodName;
public void setItmNumber(int number) // method to set item number
itmNumber = number;
public int getItmNumber() // method to get item number
return itmNumber;
public void setUnits(int unit) // method to set number of units
units = unit;
public int getUnits() // method to get number of units
return units;
public void setPrice(double each) // method to set price
price = each;
public double getPrice() // method to get price
return price;
public double calcValue() // method to set value
return units * price;
} // end class Product
class ProductAdd extends Product
private String feature; // variable for added feature
public ProductAdd(String name, int number, int unit, double each, String addFeat)
// call to superclass Product constructor
super(name, number, unit, each);
feature = addFeat;
}// end constructor
public void setFeature(String addFeat) // method to set added feature
feature = addFeat;
public String getFeature() // method to get added feature
return feature;
public double calcValueRstk() // method to set value and add restock fee
return units * price * 0.05;
public String toString()
return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
} // end class ProductAddI just have one more question. I have intergrated the code example you gave me into my original code. Now I have a ton of errors that seem to pertain to the fact that I have numbers involved. Please help.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Inventory extends JFrame// Main class
private JLabel prodNameLabel;
private JLabel numberLabel;
private JLabel unitLabel;
private JLabel priceLabel;
private JLabel featureLabel;
private JLabel valueLabel;
private JLabel rstkLabel;
private JLabel totalLabel;
private JTextField prodNameField;
private JTextField numberField;
private JTextField unitField;
private JTextField priceField;
private JTextField featureField;
private JTextField valueField;
private JTextField rstkField;
private JTextField totalField;
private JButton firstBtn;
private JButton prevBtn;
private JButton nextBtn;
private JButton lastBtn;
private JPanel buttonJPanel;
private JPanel fieldJPanel;
private JPanel fontJPanel;
private List<ProductAdd> nwProduct;
private int currProd = 0;
private double total; // variable for total inventory
public Inventory()
initComponents();
private void initComponents()
prodNameLabel = new JLabel("Product Name:");
numberLabel = new JLabel("Item Number:");
unitLabel = new JLabel("In Stock:");
priceLabel = new JLabel("Each Item Cost:");
featureLabel = new JLabel("Type of Item:");
valueLabel = new JLabel("Value of Item Inventory:");
rstkLabel = new JLabel("Cost to Re-Stock Item:");
totalLabel = new JLabel("Total Value of Inventory:");
firstBtn = new JButton("First");
prevBtn = new JButton("Previous");
nextBtn = new JButton("Next");
lastBtn = new JButton("Last");
prodNameField = new JTextField();
prodNameField.setEditable(false);
numberField = new JTextField();
numberField.setEditable(false);
unitField = new JTextField();
unitField.setEditable(false);
priceField = new JTextField();
priceField.setEditable(false);
featureField = new JTextField();
featureField.setEditable(false);
valueField = new JTextField();
valueField.setEditable(false);
rstkField = new JTextField();
rstkField.setEditable(false);
totalField = new JTextField();
totalField.setEditable(false);
prodNameLabel.setSize(200, 20);
numberLabel.setSize(200, 20);
unitLabel.setSize(200, 20);
priceLabel.setSize(200, 20);
featureLabel.setSize(200, 20);
valueLabel.setSize(200, 20);
rstkLabel.setSize(200, 20);
totalLabel.setSize(200, 20);
prodNameField.setSize(100, 20);
numberField.setSize(100, 20);
unitField.setSize(100, 20);
priceField.setSize(100, 20);
featureField.setSize(100, 20);
valueField.setSize(100, 20);
rstkField.setSize(100, 20);
totalField.setSize(100, 20);
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
// add buttons to buttonJPanel
buttonJPanel.add(firstBtn);
buttonJPanel.add(prevBtn);
buttonJPanel.add(nextBtn);
buttonJPanel.add(lastBtn);
nwProduct = new ArrayList<ProductAdd>();
nwProduct.add(new ProductAdd("Paper", 101, 10, 1.00, "Box"));
nwProduct.add(new ProductAdd("Pen", 102, 10, 0.75, "Pack"));
nwProduct.add(new ProductAdd("Pencil", 103, 10, 0.50, "Pack"));
nwProduct.add(new ProductAdd("Staples", 104, 10, 1.00, "Box"));
nwProduct.add(new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack"));
total = (nwProduct.size() += calcValue());
prodNameField.setText(nwProduct.get(currProd).getProdName());
numberField.setInt(nwProduct.get(currProd).getItmNumber());
unitField.setInt(nwProduct.get(currProd).getUnits());
priceField.setInt(nwProduct.get(currProd).getPrice());
featureField.setText(nwProduct.get(currProd).getFeature());
valueField.setInt(nwProduct.get(currProd).calcValue());
rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
totalField.setInt(total);
fieldJPanel = new JPanel();
fieldJPanel.setLayout(new GridLayout(8, 2));
fieldJPanel.add(prodNameLabel);
fieldJPanel.add(prodNameField);
fieldJPanel.add(numberLabel);
fieldJPanel.add(numberField);
fieldJPanel.add(unitLabel);
fieldJPanel.add(unitField);
fieldJPanel.add(priceLabel);
fieldJPanel.add(priceField);
fieldJPanel.add(featureLabel);
fieldJPanel.add(featureField);
fieldJPanel.add(valueLabel);
fieldJPanel.add(valueField);
fieldJPanel.add(rstkLabel);
fieldJPanel.add(rstkField);
fieldJPanel.add(totalLabel);
fieldJPanel.add(totalField);
JFrame invFrame = new JFrame();
invFrame.setLayout( new BorderLayout());
invFrame.setTitle("Office Min Inventory");
invFrame.getContentPane().add(fontJPanel, BorderLayout.NORTH);
invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH);
invFrame.getContentPane().add(fieldJPanel, BorderLayout.CENTER);
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
invFrame.setSize(400, 400); // set size of JPanel
invFrame.setLocationRelativeTo(null); // set screem location
invFrame.setVisible(true); // display window
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent evt)
goFirst();
lastBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent evt)
goLast();
prevBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent evt)
goBack();
nextBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent evt)
goNext();
private void goFirst()
prodNameField.setText(nwProduct.get(0).getProdName());
numberField.setInt(nwProduct.get(0).getItmNumber());
unitField.setInt(nwProduct.get(0).getUnits());
priceField.setInt(nwProduct.get(0).getPrice());
featureField.setText(nwProduct.get(0).getFeature());
valueField.setInt(nwProduct.get(0).calcValue());
rstkField.setInt(nwProduct.get(0).calcValueRstk());
totalField.setInt(total);
private void goLast()
prodNameField.setText(nwProduct.get(nwProduct.size() - 1).getProdName());
numberField.setInt(nwProduct.get(nwProduct.size() - 1).getItmNumber());
unitField.setInt(nwProduct.get(nwProduct.size() - 1).getUnits());
priceField.setInt(nwProduct.get(nwProduct.size() - 1).getPrice());
featureField.setText(nwProduct.get(nwProduct.size() - 1).getFeature());
valueField.setInt(nwProduct.get(nwProduct.size() - 1).calcValue());
rstkField.setInt(nwProduct.get(nwProduct.size() - 1).calcValueRstk());
totalField.setInt(total);
private void goBack()
if(currProd > 0)
currProd--;
prodNameField.setText(nwProduct.get(currProd).getProdName());
numberField.setInt(nwProduct.get(currProd).getItmNumber());
unitField.setInt(nwProduct.get(currProd).getUnits());
priceField.setInt(nwProduct.get(currProd).getPrice());
featureField.setText(nwProduct.get(currProd).getFeature());
valueField.setInt(nwProduct.get(currProd).calcValue());
rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
totalField.setInt(total);
private void goNext()
if(currProd < nwProduct.size() - 1)
currProd++;
prodNameField.setText(nwProduct.get(currProd).getProdName());
numberField.setInt(nwProduct.get(currProd).getItmNumber());
unitField.setInt(nwProduct.get(currProd).getUnits());
priceField.setInt(nwProduct.get(currProd).getPrice());
featureField.setText(nwProduct.get(currProd).getFeature());
valueField.setInt(nwProduct.get(currProd).calcValue());
rstkField.setInt(nwProduct.get(currProd).calcValueRstk());
totalField.setInt(total);
//main method begins execution of java application
public static void main(String args[])
new Inventory().setVisible(true);
} // end main method
} // end class Inventory
class Product
protected String prodName; // name of product
protected int itmNumber; // item number
protected int units; // number of units
protected double price; // price of each unit
protected double value; // value of total units
public Product(String name, int number, int unit, double each) // Constructor for class Product
prodName = name;
itmNumber = number;
units = unit;
price = each;
} // end constructor
public void setProdName(String name) // method to set product name
prodName = name;
public String getProdName() // method to get product name
return prodName;
public void setItmNumber(int number) // method to set item number
itmNumber = number;
public int getItmNumber() // method to get item number
return itmNumber;
public void setUnits(int unit) // method to set number of units
units = unit;
public int getUnits() // method to get number of units
return units;
public void setPrice(double each) // method to set price
price = each;
public double getPrice() // method to get price
return price;
public double calcValue() // method to set value
return units * price;
} // end class Product
class ProductAdd extends Product
private String feature; // variable for added feature
public ProductAdd(String name, int number, int unit, double each, String addFeat)
// call to superclass Product constructor
super(name, number, unit, each);
feature = addFeat;
}// end constructor
public void setFeature(String addFeat) // method to set added feature
feature = addFeat;
public String getFeature() // method to get added feature
return feature;
public double calcValueRstk() // method to set value and add restock fee
return units * price * 0.05;
public String toString()
return String.format("%s%d%d$%.2f%s$%.2f$%.2f",
getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
} // end class ProductAdd
class FontJPanel extends JPanel
// display welcome message
public void paintComponent( Graphics g )
super.paintComponent( g ); //call superclass's paintComponent
// set font to Monospaced (Courier), italic, 12pt and draw a string
g.setFont( new Font( "Monospaced", Font.ITALIC, 12 ) );
g.drawString( "min", 90, 70 );
// set font to Serif (Times), bold, 24pt and draw a string
g.setColor( Color.RED );
g.setFont( new Font( "Serif", Font.BOLD, 24 ) );
g.drawString( "OFFICE", 60, 60 );
} // end method paintComponent
} // end class FontJPanel -
:( I Just can't get this code to work (Help plzzzz)
I was assigned a final exam project, but most of the stuff we never actually saw in class, so I just have to figure it out for myself.
The part I'm stucked in (among other stuff) is:
room = new JLabel[4];
selec = new JRadioButton[4];
roomg= new ButtonGroup();
for(int i = 0; i < 4; i++) {
room[i] = new JLabel(arean);
selec[i] = new JRadioButton();
selec[i].addActionListener(this);
areap.add(room[i]);
areap.add(selec[i]);
roomg.add(selec[i]);
areap.setBorder(new TitledBorder(""+arean[i]));
This part of the code successfully created a group of JRadioButtons each with the names previously established in arean[ ]. However, I'm supposed to make it so that whenever I press any of the RadioButtons, the border of the JPanel changes as well. As it is, Java will put only the last name, and won't change it as I click the different JRadioButtons.
I'm not sure if I made myself clear, so if anyone is interested in helping me and needs further information, plz let me know.
Thanks in advance.
Message was edited by:
SmaSh_If it's an array of Strings of area names, then the
append to an empty string in this line of code:
areap.setBorder(new TitledBorder(""+arean)); is extraneous (as
well as being a nasty idiom anyway, IMHO). I see
that you removed it in your example...
I agree that the empty string is a nasty idiom (hence my removal of it). I figured arean had to be an array of Strings, if it is passed to the JLabel constructor (because toString on an Icon would probably be usely). -
I have written code to load in an object but this keeps giving me exceptions when i run the code to try and display the data from the object read in. I get a java.lang.NullPointerException at line 80 in cFaceRecEDetails.java My code is below:
Thanks
//--- cFaceRecGUIMain.java ---
//--- Edmund Smith 23/08/04 ---
//--- The GUI for the face recognition sofware contains buttons and ---
//--- display area for an image of a face ---
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
public class cFaceRecGUIMain extends JFrame implements ActionListener {
//Create menu bar items
private JMenuItem jmiLoadPicture, jmiExit, jmiEdit;
//Recognize Button
private JButton jbtRecognize;
//Labels with info about picture
private String lblName, lblDOB, lblNI, lblStaffID;
//Panel to hold an image
private ImagePanel imagePanel = new ImagePanel();
//File Chooser
JFileChooser jFileChooser = new JFileChooser();
//BitmapReader
//cGetBytes getBytes = new cGetBytes();
//Face database
cFaceRecData faceDatabase = new cFaceRecData();
//Set default window sizes
final int xSize = 600;
final int ySize = 400;
//Array for holding pixels
int pixels[];
//Labels for menu items
final String lbljmiLoadPicture = "Load Picture for recogniton";
final String lbljmiExit = "Exit";
final String lbljmiEdit = "Edit face database";
//Create the frame to enter details about people
cFaceRecGUIEDetails enterDetailsFrame = new cFaceRecGUIEDetails();
//BitmapReader
cGetBytes getImageBytes = new cGetBytes();
//Main method
public static void main(String[] args)
cFaceRecGUIMain programFrame = new cFaceRecGUIMain();
programFrame.pack();
programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
programFrame.setTitle("Face Recognizer");
programFrame.setSize(600, 400);
programFrame.setVisible(true);
//Constructor
public cFaceRecGUIMain() {
//Initialize menu bar
JMenuBar jmb = new JMenuBar();
setJMenuBar(jmb);
//Add menus
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
jmb.add(fileMenu);
JMenu faceMenu = new JMenu("Face");
fileMenu.setMnemonic('A');
jmb.add(faceMenu);
JMenu helpMenu = new JMenu("Help");
fileMenu.setMnemonic('H');
jmb.add(helpMenu);
//Add menu items
fileMenu.add(jmiLoadPicture =
new JMenuItem(lbljmiLoadPicture, 'L'));
fileMenu.addSeparator();
fileMenu.add(jmiExit = new JMenuItem(lbljmiExit, 'X'));
faceMenu.add(jmiEdit = new JMenuItem(lbljmiEdit, 'E'));
//Set keyboard accelerators
jmiExit.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
jmiLoadPicture.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
//Set up new panel
imagePanel.setBorder(new TitledBorder("Face"));
//Lay components on panel
imagePanel.setImageIcon(new ImageIcon("C:/Documents and Settings/" +
"Edmund Smith/My Documents/aface.bmp"));
imagePanel.add(jbtRecognize = new JButton("Recognize"),
BorderLayout.SOUTH);
setTitle("Face Recognizer");
//Labels to hold info
JPanel lblsAboutImagePanel = new JPanel();
lblsAboutImagePanel.setBorder(new TitledBorder("Details"));
lblsAboutImagePanel.setLayout(new GridLayout(4, 2));
lblsAboutImagePanel.add(new JLabel("Name"));
lblsAboutImagePanel.add(new JLabel(lblName));
lblsAboutImagePanel.add(new JLabel("DOB"));
lblsAboutImagePanel.add(new JLabel(lblDOB));
lblsAboutImagePanel.add(new JLabel("National insurance number"));
lblsAboutImagePanel.add(new JLabel(lblNI));
lblsAboutImagePanel.add(new JLabel("Staff ID"));
lblsAboutImagePanel.add(new JLabel(lblStaffID));
//Add the different panels to the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(imagePanel, BorderLayout.WEST);
getContentPane().add(lblsAboutImagePanel, BorderLayout.CENTER);
//Register listeners
jmiExit.addActionListener(this);
jmiLoadPicture.addActionListener(this);
jmiEdit.addActionListener(this);
//Create the frame where you can enter the details of a person
enterDetailsFrame.pack();
enterDetailsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
enterDetailsFrame.setTitle("Set up database");
enterDetailsFrame.setSize(xSize, ySize);
class edfClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
//Check to see if the record has been changed
if (enterDetailsFrame.isRecordModified)
JOptionPane.showConfirmDialog(
null,
"Do you want to save changes to this record?",
"Face datbase",
JOptionPane.YES_NO_CANCEL_OPTION);
if (enterDetailsFrame.newPeople.size() > 0)
//create a temporary array to store the new people
person[] newPersons = new
person[enterDetailsFrame.newPeople.size()];
//Copy the people in the vector to the array
person tempPerson;
for (int i = 0; i < newPersons.length; i++)
tempPerson =
(person)enterDetailsFrame.newPeople.elementAt(i);
newPersons.path = tempPerson.path;
newPersons.personsName = tempPerson.personsName;
newPersons.personsDOB = tempPerson.personsDOB;
newPersons.personsNI = tempPerson.personsNI;
newPersons.personsStaffID = tempPerson.personsStaffID;
//Create new database
allPeople outPeople =
new allPeople(enterDetailsFrame.peopleInfo, newPersons);
//Save the database with the added records
enterDetailsFrame.faceDatabase.saveDatabase(outPeople);
else
//Save the database with the same number of records
enterDetailsFrame.faceDatabase.saveDatabase(
enterDetailsFrame.peopleInfo);
//Set the actions to happen when windows are closed
enterDetailsFrame.addWindowListener(new edfClosingListener());
closeWindow closeMainFrame = new closeWindow();
addWindowListener(closeMainFrame);
public void actionPerformed(ActionEvent e)
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JMenuItem) {
if (lbljmiExit.equals(actionCommand))
System.exit(0);
else if (lbljmiLoadPicture.equals(actionCommand))
open();
else if (lbljmiEdit.equals(actionCommand)) {
enterDetailsFrame.setVisible(true);
//No records have been modified
enterDetailsFrame.isRecordModified = false;
//Open a file
private void open() {
if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
try {
//Get the file name
String fileName = jFileChooser.getSelectedFile().getPath();
//Display the image
ImageIcon imagei = new ImageIcon(fileName);
imagePanel.setImageIcon(imagei);
//Set size of array for holiding bytes in the image
pixels =
new int[51 * 55];
//Get the pixels
// getBytes.getBMPImage(new FileInputStream(new File(fileName)), pixels);
catch (Exception e) {
System.out.print(e);
class ImagePanel extends JPanel {
//Label to hold the face
private JLabel jlblFace = new JLabel();
//Constructor
public ImagePanel() {
setLayout(new BorderLayout());
add(jlblFace, BorderLayout.CENTER);
//Set image and show it
public void setImageIcon(ImageIcon icon) {
jlblFace.setIcon(icon);
Dimension dimension =
new Dimension(icon.getIconWidth(), icon.getIconHeight());
jlblFace.setPreferredSize(dimension);
//--- cFaceRecGUIEDetails.java ---
//--- Edmund Smith 06/10/04 ---
//--- Allows the user to enter details about a person, view the ---
//--- database and add people to the database ---
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.util.*;
class cFaceRecGUIEDetails extends JFrame implements KeyListener, ActionListener
//Buttons to navigate the database
private JButton jbtPrevious, jbtNext;
//Button to load a face
private JButton jbtLoadFace;
//Fields to display info about the person
private JTextField jtfName, jtfDOB, jtfNI, jtfStaffID;
//Panel to hold an image
private ImagePanel imagePanel = new ImagePanel();
//File Chooser
private JFileChooser jFileChooser = new JFileChooser();
//Variable to tell whether record has been modified
boolean isRecordModified = false;
//Tells which record current being veiwed/changed
int currentRecord = 0;
//Stores new people to be added to database
Vector newPeople = new Vector();
//Face database
cFaceRecData faceDatabase;
public allPeople peopleInfo;
//Default Constructor
public cFaceRecGUIEDetails()
//Get the face database
faceDatabase = new cFaceRecData();
peopleInfo = faceDatabase.restoreDatabase();
//Panel to hold two buttons to navigate the database
JPanel jpButtons = new JPanel();
//Add navigation buttons to panel
jpButtons.setLayout(new FlowLayout());
jpButtons.add(jbtPrevious = new JButton());
jpButtons.add(jbtNext = new JButton());
//Set button text
jbtPrevious.setText("<");
jbtNext.setText(">");
//Panel to hold details about the person
JPanel jpDetails = new JPanel();
jpDetails.setBorder(new TitledBorder("Details"));
jpDetails.setLayout(new GridLayout(4, 2));
jpDetails.add(new JLabel("Name"));
jpDetails.add(jtfName = new JTextField());
jpDetails.add(new JLabel("DOB"));
jpDetails.add(jtfDOB = new JTextField());
jpDetails.add(new JLabel("National insurance number"));
jpDetails.add(jtfNI = new JTextField());
jpDetails.add(new JLabel("StaffID"));
jpDetails.add(jtfStaffID = new JTextField());
try
jtfName.setText(peopleInfo.people[currentRecord].personsName);
/* jtfDOB.setText(String.valueOf(
peopleInfo.people[currentRecord].personsDOB));
jtfNI.setText(String.valueOf(
peopleInfo.people[currentRecord].personsNI));
jtfStaffID.setText(String.valueOf(
peopleInfo.people[currentRecord].personsStaffID));*/
catch (Exception e)
System.out.print(e);
imagePanel.setBorder(new TitledBorder("Face"));
imagePanel.add(jbtLoadFace = new JButton("Load Face"));
//Main body panel
JPanel jpBody = new JPanel();
jpBody.add(imagePanel, BorderLayout.WEST);
jpBody.add(jpDetails, BorderLayout.CENTER);
//Place panels on frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(jpBody, BorderLayout.CENTER);
getContentPane().add(jpButtons, BorderLayout.SOUTH);
//Register listeners
jbtLoadFace.addActionListener(this);
jbtPrevious.addActionListener(this);
jbtNext.addActionListener(this);
//jtfName.addKeyListener(this);
jtfDOB.addKeyListener(this);
jtfNI.addKeyListener(this);
jtfStaffID.addKeyListener(this);
public void actionPerformed(ActionEvent e)
boolean goOn = false;
if (e.getSource() == jbtLoadFace)
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
if (e.getSource() == jbtPrevious || e.getSource() == jbtNext)
if (isRecordModified == true)
int result = JOptionPane.showConfirmDialog(
null,
"Do you want to save changes to this record?",
"Face datbase",
JOptionPane.YES_NO_CANCEL_OPTION);
switch (result)
case JOptionPane.YES_OPTION:
saveRecordChanges();
goOn = true;
break;
case JOptionPane.NO_OPTION:
goOn = true;
break;
if (goOn == true)
//If user has not cancelled move to another record
if (e.getSource() == jbtPrevious)
moveForwardToRecord(true);
else
moveForwardToRecord(false);
public void saveRecordChanges()
boolean alreadyInDatabase = false;
//Put the values in the field into the database
try
if (currentRecord < peopleInfo.people.length)
alreadyInDatabase = true;
peopleInfo.people[currentRecord].personsName =
jtfName.getText();
peopleInfo.people[currentRecord].personsDOB =
Integer.parseInt(jtfDOB.getText());
peopleInfo.people[currentRecord].personsNI =
Integer.parseInt(jtfNI.getText());
peopleInfo.people[currentRecord].personsStaffID =
Integer.parseInt(jtfStaffID.getText());
catch (Exception e)
System.out.print(e);
if (alreadyInDatabase = false)
newPeople.add(new person("", jtfName.getText(),
Integer.parseInt(jtfDOB.getText()),
Integer.parseInt(jtfNI.getText()),
Integer.parseInt(jtfStaffID.getText())));
public void moveForwardToRecord(boolean forward)
isRecordModified = false;
setTitle("Set up datbase");
if (forward)
else
public void keyPressed(KeyEvent e)
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
public void keyReleased(KeyEvent e) {
public void keyTyped(KeyEvent e) {
//Open a file
private void open()
if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
String fileName = jFileChooser.getSelectedFile().getPath();
imagePanel.setImageIcon(new ImageIcon(fileName));
isRecordModified = true;
setTitle("Set up datbase: Record Modified");
//--- cFaceRecData.java ---
//--- Edmund Smith 18/11/04 ---
//--- Stores and retrives info about a person and their face ---
import java.io.*;
import java.util.*;
class cFaceRecData
//The location of the database
final String dbPath = "C:/Documents and Settings/" +
"Edmund Smith/My Documents/fdatabase.dat";
//The data
allPeople inPeople;
//Saves the file
void saveDatabase(allPeople outPeople)
try
//Object output stream
ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream(dbPath));
//Write the object
out.writeObject(outPeople);
//Close the object output stream
out.close();
catch (IOException ex)
System.out.println(ex);
//Opens the file
allPeople restoreDatabase()
try
//Object input steam
ObjectInputStream in =
new ObjectInputStream(new FileInputStream(dbPath));
//Get the database
inPeople = (allPeople)in.readObject();
//Close the input stream
in.close();
catch (IOException ex)
System.out.println(ex);
catch (ClassNotFoundException ex)
System.out.println(ex);
//Return the database
return inPeople;
//Holds the info about a person
class person
//Stores the location of the image on disk
String path;
//Stores the name of a person
String personsName;
//Stores the dob of a person, their NI no, and employee ID
int personsDOB, personsNI, personsStaffID;
//Default constructor
public person(String inPath, String inName, int inDOB, int inNI,
int inStaffID)
//Stores the values which passed in
path = inPath;
personsName = inName;
personsDOB = inDOB;
personsNI = inNI;
personsStaffID = inStaffID;
//The database
class allPeople
person[] people;
int numPeople;
//Default constructor
public allPeople(person[] persons)
//Create the array to hold the people
people = new person[persons.length];
for (int i = 0; i < persons.length; i++)
people = new person(persons.path,
persons.personsName,
persons.personsDOB,
persons.personsStaffID,
persons.personsNI);
//Updates the database
public allPeople(allPeople thePeople, person[] persons)
//Create the array to hold the people
int totalPeople = thePeople.people.length + persons.length;
people = new person[totalPeople];
for (int i = 0; i < totalPeople; i++)
if (i < thePeople.people.length)
people = new person(thePeople.people.path,
thePeople.people.personsName,
thePeople.people.personsDOB,
thePeople.people.personsStaffID,
thePeople.people.personsNI);
else
people = new person(persons.path,
persons.personsName,
persons.personsDOB,
persons.personsStaffID,
persons.personsNI);
}line 80 is jtfName.setText(peopleInfo.people[currentRecord].personsName);So put these lines between line 79 and 80System.out.println(jtfName);System.out.println(peopleInfo);
System.out.println(peopleInfo.people);
System.out.println(peopleInfo.people[currentRecord]);
System.out.println(peopleInfo.people[currentRecord].personsName);One of those will print null. Then you will see a NullPointerException. Then you can trace your code back to where you are setting these to some value.
Maybe you are looking for
-
Hi. I am using sql server 2005 and vb 2008 from visual studio 2008. Opened vb and created a database with 2 tables namely client and trousers having fields as following: client(client_id, name)......client_id as pk trousers(trousers_id,client_id,wais
-
How to transfer Files from an iPod touch to a new computer?
Hello all, recently i ran into some computer problems and my computer needed to be replaced. I did not keep my old computer. I want to transfer files such as notes, contacts, apps ect. to the new computer. I do not care about transfering music or pho
-
hi Seniors, I have a Requirement to use Read_Text function module and Read text from the Text Object. Object is Material......please tell me how to proceed with this.....urgent please. Thanks , Nalini.
-
Trouble with 5310 internet settings
Hi, ive recently bought a nokia 5310 and have downloaded all the correct settings for me to send and receive multimedia messages aswell access the internet. These all work, however I am unable to access the nokia.com homepage, im unable to create an
-
I can't compile servlet code because it doesn't recognize the http... classes. I downloaded the servlet api but don't know what to do with it (unziped it but no installation!) please help