JPanel displaying
Hi folks!
We built a swing based application: a JFrame containig a JPanel containing a JButton. We packaged our classes in a jar file (the main class and two other secondary classes) to be run on a Win2000 Server S.P. 2 machine with JVM 1.4.0.
When the application runs, we see only the JFrame edges and its title bar. It seems that the application freezes: we can't close it using "x" icon on the top right corner.
The development environment: Win2000 Professional + VisualAge 4.0 Enterprise Edition.
We hope find an help. Thanks in advance,
Alberto and Amal
Is this an executable JAR file that you are running? Executable JARs usually run with Javaw.exe (no console window) instead of Java.exe. Try changing your file type associations to open executable JARs with Java.exe (or run from the command line) so that you can view the stack trace and maybe get some insight into your problem.
Similar Messages
-
How can I Print a JPanel including all added Components?
Hello dear saviours,
I have a JPanel object which is responsible for displaying a Graph.
I need to Print the Components of this JPanel as close to what they look like to the user as possible.
I thought about casting the JPanel into an Image of some kind, but couldn't find anything but how to add am Image to a JPanel (God damned search engines :-).
But wait, this gets more interesting!
I need to have control over the scale of the Printed matterial.
I want the option to choose between a single page and dividing the drawing the JPanel displays into Multiple-Pages.
In both cases I need full details of all the data (Nodes, Arcs, Text describing the various Nodes and Arcs names or type, etc.).Keeping the sizes of all these components is also important (that means, I don't want the nodes to be tinny-winny and the Fonts to be twice as large as the nodes and so on...).
Attached is the code of the PrintUtillity class I created as an API for printing the JPanel data:
package ild;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class that lets you very simply print
* an arbitrary component. Just pass the component to the
* PrintUtilities.printComponent. The component you want to
* print doesn't need a print method and doesn't have to
* implement any interface or do anything special at all.
* <P>
* If you are going to be printing many times, it is marginally more
* efficient to first do the following:
* <PRE>
* PrintUtilities printHelper = new PrintUtilities(theComponent);
* </PRE>
* then later do printHelper.print(). But this is a very tiny
* difference, so in most cases just do the simpler
* PrintUtilities.printComponent(componentToBePrinted).
* 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
* May be freely used or adapted.
public class PrintUtilities implements Printable {
private Component componentToBePrinted;
public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
// double scale = 2;
// g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
double scaleFactor = java.lang.Math.min((double)this.componentToBePrinted.getSize().width/(double)(pageFormat.getImageableWidth()),
(double)this.componentToBePrinted.getSize().height/(double)(pageFormat.getImageableHeight()));
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.scale(1.0/scaleFactor,1.0/scaleFactor);
// disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on.
* So this turns if off globally.
* @see enableDoubleBuffering
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
/** Re-enables double buffering globally. */
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);That's a nice utility, but my JPanel gets truncated when printed. Is there a way to print a JPanel in full.
-
hi people
I have been trying to get a jpanel show when the main is initializes. I don't get any errors. I am using Netbeans as my IDE. The jpanel I want to show is timerPanel. I am very new to java so I am sure that it is something simple. does anyone know what I am going wrong?
public class Timer extends javax.swing.JPanel {
public static void main(String[] args){
new Timer().setVisible(true);
/** Creates new form timer */
public Timer() {
initComponents();
JPanel panel= new JPanel();
panel.setVisible(true);
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
timerPanel = new javax.swing.JPanel();
display = new javax.swing.JLabel();
start = new javax.swing.JButton();
pause = new javax.swing.JButton();
reset = new javax.swing.JButton();
save = new javax.swing.JButton();
exit = new javax.swing.JButton();
timerPanel.setBackground(new java.awt.Color(232, 227, 234));
display.setBackground(new java.awt.Color(217, 217, 62));
display.setText("wa");
display.setToolTipText("shows hr:mins:sec");
start.setText("Start");
start.setToolTipText("Starts Timer");
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
pause.setText("Pause");
pause.setToolTipText("To Restart Press");
pause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseActionPerformed(evt);
reset.setText("Reset");
reset.setToolTipText("Clears Timer");
reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetActionPerformed(evt);
save.setText("Save");
save.setToolTipText("Saves Timer Amount");
save.setActionCommand("Save");
save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
exit.setText("Exit");
exit.setToolTipText("Exits without saving");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
javax.swing.GroupLayout timerPanelLayout = new javax.swing.GroupLayout(timerPanel);
timerPanel.setLayout(timerPanelLayout);
timerPanelLayout.setHorizontalGroup(
timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(display, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, timerPanelLayout.createSequentialGroup()
.addComponent(start)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pause)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(reset)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
.addComponent(save)
.addGap(4, 4, 4)
.addComponent(exit)
.addContainerGap())
timerPanelLayout.setVerticalGroup(
timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timerPanelLayout.createSequentialGroup()
.addContainerGap(47, Short.MAX_VALUE)
.addComponent(display, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(start)
.addComponent(pause)
.addComponent(reset)
.addComponent(save)
.addComponent(exit))
.addContainerGap())
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(timerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(timerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(287, Short.MAX_VALUE))
}// </editor-fold>
private void startActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void pauseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void resetActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Variables declaration - do not modify
private javax.swing.JLabel display;
private javax.swing.JButton exit;
private javax.swing.JButton pause;
private javax.swing.JButton reset;
private javax.swing.JButton save;
private javax.swing.JButton start;
private javax.swing.JPanel timerPanel;
// End of variables declaration
}gishaust wrote:
Who would I ask?The compiler and JVM!
Change your code to include a JFrame, compile it, run it. You will soon find out. -
Hi i've create a jForm in netbeans. To this I have added a scrollpane containing a jPanel called PrintPreview. (I have to do this rather than use the automated preview of printUtilities because of some items I need removed from the original jPanel before printing).
I need to set the size of the PrintPreview jPanel as it's instantiated. I have the dimensions created from another class called "Gbl".
In the constructor is the following:
/** Creates new form PrintPreview */
public PrintPreview() {
PreviewPanel.setPreferredSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
PreviewPanel.setMaximumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
PreviewPanel.setMinimumSize(new Dimension(Gbl.previewWidth,Gbl.previewHeight);
Window.pack();
initComponents();
this.setLocationRelativeTo(null);
// ADD CODE - COLLECT DRAWING FROM ARRAY
PreviewPanel.repaint();
I would like the jPanel set to these dimensions however I would also like the scrollPane to remain at it's standard size so I can scroll the diagram as necessary.
Could you please tell me where I am going wrong? The three setSize lines are flagged as erroneous. The dimensions are int and have tried double.
Any advice is good...
ThanksOk I'm going to add onto this thread because it still relates to the original problem. setting size of jPanel.
Some details first:
OS - Ubuntu Gutsy 7.10
Kernel - 2.6.22-14-generic
NB - v5.5.1
Java version - java version "1.5.0" / gij (GNU libgcj) version 4.2.1 (Ubuntu 4.2.1-5ubuntu5)
Research:
I have been trawling the net for days trying to resolve this but I am struggling to find anything specific to my problem. I keep finding general methods using given NB facilities. I've also scoured a couple of my Java books but of course they're not totally relevant to NetBeans. I've practiced using the forum this afternoon to find things but with my lack of knowledge using both forums and java has left me a little bamboozled. I've been working on this problem for a couple of days now and achieved very little.
My specific problem is this:
I have a JFrame GUI. Inside that I have a jTabbedPane containing a jScrollPane containing a jPanel. I would like to have the jPanel display at A4 size relevant to the screen it is displayed on. e.g. I have a separate global class "Gbl" that calculates the dimensions based on current dpi and then creates the necessary measurements to feed to my preferred size function.
I have tried implementing the preferred size method to the constructor and have also tried adding it to all four ways to enter bespoke code to NetBeans' autogenerated code. (Pre-init, Post-init, Pre-creation and Post-creation code) To no avail. Nothing changes on screen.
The code I am trying to enter is as follows:
// Set preferred size of user-drawing-area (jPanel1)
jPanel1.setPreferredSize(new java.awt.Dimension(600,500));
jPanel1.setMaximumSize(new java.awt.Dimension(600,500));
jPanel1.setMinimumSize(new java.awt.Dimension(600,500));
// Set preferred size of jPanel1 container (jScrollPane1)
jScrollPane1.setPreferredSize(new java.awt.Dimension(600,500));
jScrollPane1.setMaximumSize(new java.awt.Dimension(600,500));
jScrollPane1.setMinimumSize(new java.awt.Dimension(600,500));
// Set preferred size of the jScrollPane1 container (mainTabView(Tabbed pane))
mainTabView.setPreferredSize(new java.awt.Dimension(600,500));
mainTabView.setMaximumSize(new java.awt.Dimension(600,500));
mainTabView.setMinimumSize(new java.awt.Dimension(600,500));
I am using absolute values here to omit any error getting the variables from my Global class. If it works I will add them and test again.
Ideally, I would like the jPanel to be set to an A4 size yet have the containers at a smaller more "screen-manageable" size (With scroll bars). Then if the GUI is maximized, then it only expands to the full size of the A4 sized jPanel if possible.
Of course, this may not be possible or there may be a far better method for doing this, however I am really stumped. I've had some good advice this afternoon of whihc has opened may eyes some. Although, I have made no headway so far. I hope the above follows site-rules and gives enough information to resolve this issue. I'm losing hair rapidly!
I'm grateful for any advice given. Thank You -
Hello,
I am wondering if it is possible to update the layout of a JPanel upon response to an event. IE....if i have a JPanel with 2 buttons in it, and i want it to change to a JPanel with only a Text Area in it after a certain event occurs, how do i do this?
i have heard something about revalidate(), but im not sure how it would work. ex...
JPanel myPanel = new JPanel();
JButton bn1 = new JButton("one");
JButton bn2 = new JButton("two");
myPanel.add(bn1);
myPanel.add(bn2);and i want the JPanel to look like this after an event:
JPanel myPanel = new JPanel();
JTextArea TA = new JTextArea();
myPanel.add(TA);How is this accomplished?This is one way. I am sure not the only or best though.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class AfterFrame3 extends JFrame implements ActionListener {
JPanel jp, jp3;
Container cp;
JTextField jTextField;
static AfterFrame3 af2;
public AfterFrame3() {
JButton bt1;
jp = new JPanel();
jp3 = new JPanel();
jTextField = new JTextField("I am a new JTextField");
cp = getContentPane();
bt1 = new JButton("Click Me!");
jp3.setLayout(new BoxLayout(jp3,BoxLayout.Y_AXIS));//Intermediate container
jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));//Holds JButton
jp.add(bt1,BorderLayout.CENTER);//Add JButton
((JButton)jp.getComponent(0)).addActionListener(this);
jp3.add(jp);//Add 1st JPanel to primary Intermediate container
cp.add(jp3);//Add Intermidiate container to frame
public void actionPerformed(ActionEvent e) {
jp3.remove(jp);
jp3.add(jTextField);//Add JTextField
af2.pack();
public static void main(String[] args) {
af2 = new AfterFrame3();
af2.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
af2.pack();
af2.setVisible(true);
}The change in the JPanel display occurs inside of the ActionPerformed Event. -
Dispaly message on JPanel before connecting SQL
Hi,
I have application based on JTabbedPane with 2 Panels. At some point, the application connects to database and I would like to display message or progress bar of connecting try, in that way the user will not think the application is frozen.
I tried JProgressBar (with swingworker) but I got the progress bar gray when refreshing DB connection.
My last try is with thread that I run before connecting to DB (when hit 'refresh' button). The thread gets the panel object and should display "try to connect" message while trying connecting DB, but i get the message only when connection fails....
You may find below excerpt of my code.
-- The message is display only after the message box of JOptionPane is shown.
Any ideas?
Thank you,
Alon
// The messge thread - disPanel --> panel object
public void run()
try
disPanel.add(new JLabel("Connecting to db..."));
disPanel.validate();
disPanel.repaint();
Thread.sleep(5);
catch (InterruptedException ie)
ie.printStackTrace();
// The refresh connection button
else if (evt.getSource()==refreshBt)
ConnectionMsgThread cmt = new ConnectionMsgThread(this);
Thread t = new Thread(cmt);
t.start();
refreshData();
// The refrsh data method connect to DB
try
dbConn = getConnection();
stat = dbConn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
catch(Exception ex)
JOptionPane.showMessageDialog(new JFrame().getContentPane(),"Connection to DB failed, please check settings");
}Thanks for the code sample link. I undersatnd the logic but when I implemented the thread in the JPanel class, I could not get the label text until the connection try finished.
Moreover, I added an IO opertation (attached code) to the sample code (within the "run()" method or after the button actionListner), BUT the label wasn't refreshed and the application was frozen (the printing on screnn was ok).
I know Swing is single threaded and IO methods block the main thread, but how can I create a separte thread to refresh JPanel display during IO operations.
Thanks,
Alon
try
new FileWriter(new File("\\\\192.168.50.50\\folder\\file.txt"));
catch (IOException ie)
ie.printStackTrace();
} -
Need help with search function in my program
Hello all, some of you may remeber me from my previous inventory programs. Well I am finally on my last one and I need to add a search option to the code. Here is the class that will contain that option.
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Inventory2 extends JFrame implements ActionListener {
//Utility class for displaying the picture
//If we are going to use a class/method/variable inside that class only, we declare it private in that class
private class MyPanel extends JPanel {
ImageIcon image = new ImageIcon("Sample.jpg");
int width = image.getIconWidth();
int height = image.getIconHeight();
long angle = 30;
public MyPanel(){
super();
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.rotate (Math.toRadians(angle), 60+width/2, 60+height/2);
g2d.drawImage(image.getImage(), 60, 60, this);
g2d.dispose();
}//end class MyPanel
int currentIndex; //Currently displayed Item
Product[] supplies = new Product[4];
JLabel name ;
JLabel number;
JLabel rating;
JLabel quantity;
JLabel price;
JLabel fee;
JLabel totalValue;
JTextField nameField = new JTextField(20);
JTextField numberField = new JTextField(20);
JTextField ratingField = new JTextField(20);
JTextField quantityField = new JTextField(20);
JTextField priceField = new JTextField(20);
JPanel display;
JPanel displayHolder;
JPanel panel;
boolean locked = false; //Notice how I've used this flag to keep the interface clean
public Inventory2() {
makeTheDataItems();
setSize(700, 500);
setTitle("Inventory Program");
//make the panels
display = new JPanel();
JPanel other = new JPanel();
other.setLayout(new GridLayout(2, 1));
JPanel picture = new MyPanel();
JPanel buttons = new JPanel();
JPanel centerPanel = new JPanel();
displayHolder = new JPanel();
display.setLayout(new GridLayout(7, 1));
//other.setLayout(new GridLayout(1, 1));
//make the labels
name = new JLabel("Name :");
number = new JLabel("Number :");
rating = new JLabel("Rating :");
quantity = new JLabel("Quantity :");
price = new JLabel("Price :");
fee = new JLabel("Restocking Fee (5%) :");
totalValue = new JLabel("Total Value :");
//Use the utility method to make the buttons
JButton first = makeButton("First");
JButton next = makeButton("Next");
JButton previous = makeButton("Previous");
JButton last = makeButton("Last");
JButton search = makeButton("Search");
//Other buttons
JButton add = makeButton("Add");
JButton modify = makeButton("Modify");
JButton delete = makeButton("Delete");
JButton save = makeButton("Save");
JButton exit = makeButton("Exit");
//Add the labels to the display panel
display.add(name);
display.add(number);
display.add(rating);
display.add(quantity);
display.add(price);
display.add(fee);
//add the buttons to the buttonPanel
buttons.add(first);
buttons.add(previous);
buttons.add(next);
buttons.add(last);
buttons.add(search);
//Add the picture panel and display to the centerPanel
displayHolder.add(display);
centerPanel.setLayout(new GridLayout(2, 1));
centerPanel.add(picture);
centerPanel.add(displayHolder);
other.add(buttons);
JPanel forAdd = new JPanel(); // add the other buttons to this panel
forAdd.add(add);
forAdd.add(modify);
forAdd.add(delete);
forAdd.add(save);
forAdd.add(exit);
other.add(forAdd);
//Add the panels to the frame
getContentPane().add(centerPanel, "Center");
getContentPane().add(other, "South");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible(true);
private void makeTheDataItems () {
Product p1 = new DVD("The one", 001, 200, 100, "The one");
Product p2 = new DVD("Once upon a time in China V", 002, 500, 10000, "Once upon a time in China V");
Product p3 = new DVD("Rat Race", 003, 100, 3000, "Rat Race");
Product p4 = new DVD("The Man in the Iron Mask", 004, 3000, 9000, "The Man in the Iron Mask");
supplies[0] = p1;
supplies[1] = p2;
supplies[2] = p3;
supplies[3] = p4;
//Utility method for creating and dressing buttons
private JButton makeButton(String label) {
JButton button = new JButton(label);
button.setPreferredSize(new Dimension(100, 25));
button.setActionCommand(label);
button.addActionListener(this);
return button;
private void addItem() {
panel = new JPanel();
JPanel add = new JPanel();
add.setLayout(new GridLayout(7, 2));
JButton addIt = makeButton("Add Item");
JLabel name = new JLabel("Name :");
JLabel rating = new JLabel("Rating :");
JLabel quantity = new JLabel("Quantity :");
JLabel price = new JLabel("Price :");
add.add(name); add.add(nameField);
add.add(rating); add.add(ratingField);
add.add(quantity); add.add(quantityField);
add.add(price); add.add(priceField);
panel.add(add);
JPanel forAddIt = new JPanel();
forAddIt.add(addIt);
panel.add(forAddIt);
displayHolder.remove(display);
displayHolder.add(panel);
//display = panel;
this.setVisible(true);
public static void main( String args[]) {
new Inventory2().displayFirst(); //The main method should not have too much code
} // end main method
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand(); //This retrieves the command that we set for the button
//Always compare strings using the .equals method and not using ==
if(command.equals("First")) {
if(!locked) {
displayFirst();
else if(command.equals("Next")) {
if(!locked) {
displayNext();
else if(command.equals("Previous")) {
if(!locked) {
displayPrevious();
else if(command.equals("Last")) {
if(!locked) {
displayLast();
else if(command.equals("Exit")) {
this.dispose();
System.exit(0);
else if(command.equals("Add")) {
if(!locked) {
addItem();
locked = true;
else if(command.equals("Add Item")) {
addItemToArray();
else if(command.equals("Modify")) {
if(!locked) {
modify();
locked = true;
else if(command.equals("Update")) {
if(!locked) {
modifyItemInArray();
locked = true;
else if(command.equals("Delete")) {
if(!locked) {
DVD dvd = (DVD)supplies[currentIndex];
int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to delete item "+dvd.getItemNumber());
if(confirm == JOptionPane.YES_OPTION) {
removeItemAt(currentIndex);
displayFirst();
private void modify() {
DVD dvd = (DVD)supplies[currentIndex];
panel = new JPanel();
JPanel add = new JPanel();
add.setLayout(new GridLayout(7, 2));
JButton update = makeButton("Update");
JLabel number = new JLabel("Number :");
JLabel name = new JLabel("Name :");
JLabel rating = new JLabel("Rating :");
JLabel quantity = new JLabel("Quantity :");
JLabel price = new JLabel("Price :");
add.add(number);
numberField.setText(""+dvd.getItemNumber()); numberField.setEditable(false); add.add(numberField);
add.add(name);
nameField.setText(dvd.getItemName()); add.add(nameField);
ratingField.setText(dvd.getRating()); ratingField.setEditable(false);
add.add(rating); add.add(ratingField);
add.add(quantity);
quantityField.setText(""+dvd.getStockQuantity());
add.add(quantityField);
add.add(price);
add.add(priceField); priceField.setText(""+dvd.getItemPrice());
panel.add(add);
JPanel forAddIt = new JPanel();
forAddIt.add(update);
panel.add(forAddIt);
displayHolder.remove(display);
displayHolder.add(panel);
//display = panel;
this.setVisible(true);
private void addItemToArray() {
Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
Double.parseDouble(priceField.getText()), ratingField.getText());
//Extend size of array by one first
Product[] ps = new Product[supplies.length + 1];
for(int i = 0; i < ps.length-1; i++) {
ps[i] = supplies;
ps[supplies.length] = p;
supplies = ps;
displayHolder.remove(panel);
displayHolder.add(display);
displayLast();
this.setVisible(false);
this.setVisible(true);
//Utility method to ease the typing and reuse code
//This method reduces the number of lines of our code
private void displayItemAt(int index) {
DVD product = (DVD)supplies[index];
name.setText("Item Name: "+ product.getItemName());
number.setText("Item Number: "+ product.getItemNumber());
rating.setText("Rating: "+ product.getRating());
quantity.setText("Quantity In Stock: "+ product.getStockQuantity());
price.setText("Item Price: "+ product.getItemPrice());
totalValue.setText("Total: " + product.calculateInventoryValue());
fee.setText("Restocking Fee (5%) :"+product.calculateRestockFee());
locked = false;
this.repaint();
this.setVisible(true);
private void modifyItemInArray() {
Product p = new DVD(nameField.getText(), supplies.length + 1, Long.parseLong(quantityField.getText()),
Double.parseDouble(priceField.getText()), ratingField.getText());
supplies[currentIndex] = p;
displayHolder.remove(panel);
displayHolder.add(display);
displayItemAt(currentIndex);
this.setVisible(false);
this.setVisible(true);
private void removeItemAt(int index) {
Product[] temp = new Product[supplies.length-1];
int counter = 0;
for(int i = 0; i < supplies.length;i++) {
if(i == index) { //skip the item to delete
else {
temp[counter++] = supplies[i];
supplies = temp;
public void displayFirst() {
displayItemAt(0);
currentIndex = 0;
public void displayNext() {
if(currentIndex == supplies.length-1) {
displayFirst();
currentIndex = 0;
else {
displayItemAt(currentIndex + 1);
currentIndex++;
public void displayPrevious() {
if(currentIndex == 0) {
displayLast();
currentIndex = supplies.length-1;
else {
displayItemAt(currentIndex - 1);
currentIndex--;
public void displayLast() {
displayItemAt(supplies.length-1);
currentIndex = supplies.length-1;
}//end class Inventory2
I am not sure where to put it and how to set it up. If you guys need the other two classes let me know. Thanks in advanced.Here are the other two classes:
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Product implements Comparable {
String name;
int number;
long stockQuantity;
double price;
public Product() {
name = "";
number = 0;
stockQuantity = 0L;
price = 0.0;
public Product(String name, int number, long stockQuantity, double price) {
this.name = name;
this.number = number;
this.stockQuantity = stockQuantity;
this.price = price;
public void setItemName(String name) {
this.name = name;
public String getItemName() {
return name;
public void setItemNumber(int number) {
this.number = number;
public int getItemNumber() {
return number;
public void setStockQuantity(long quantity) {
stockQuantity = quantity;
public long getStockQuantity() {
return stockQuantity;
public void setItemPrice(double price) {
this.price = price;
public double getItemPrice() {
return price;
public double calculateInventoryValue() {
return getItemPrice() * getStockQuantity();
public int compareTo (Object o) {
Product p = (Product)o;
return name.compareTo(p.getItemName());
public String toString() {
return "Name :"+getItemName() + "\nNumber"+number+"\nPrice"+price+"\nQuantity"+stockQuantity + "\nValue :"+calculateInventoryValue();
class DVD extends Product implements Comparable {
private String rating;
public DVD() {
super(); //Call the constructor in Product
rating = ""; //Add the additonal attribute
public DVD(String name, int number, long stockQuantity, double price, String rating) {
super(name, number, stockQuantity, price); //Call the constructor in Product
this.rating = rating; //Add the additonal attribute
public void setRating(String rating) {
this.rating = rating;
public String getRating() {
return rating;
public double calculateInventoryValue() {
return getItemPrice() * getStockQuantity() + getItemPrice()*getStockQuantity()*0.05;
public double calculateRestockFee() {
return getItemPrice() * 0.05;
public int compareTo (Object o) {
Product p = (Product)o;
return getItemName().compareTo(p.getItemName());
public String toString() {
return "Name :"+getItemName() + "\nNumber"+getItemNumber()+"\nPrice"+getItemPrice()+"\nQuantity"+getStockQuantity() +"\nRating :"+getRating()+"\nValue"+calculateInventoryValue();
}You should be able to search through these items, and any other items that have been added to the program. -
Creating a splash screen for your app.
Im trying to create a splash screen for my app but im not too sure how it's done.
Im using the following piece of code.
public static void main(String[] args)
JPanel display = new JPanel();
display.setPreferredSize(new Dimension( (300), (200) ));
display.setBackground(Color.white);
// I WILL PUT AN IMAGE ICON ON A JLABEL HERE
display.setVisible(true);
// I WILL NEED A DELAY HERE
test.instance();
}The problem I am having is that the JPanel is not being displayed. I will also need a way to create a delay, I know that I can't just use Thread.sleep(5000); because the JPanel will require the thread to be running in order to display the panel.
Does anyone know how I could get my JPanel to display and somehow insert a delay before test.instance();?
Thanks.I made my own a few days before for a database program. It can be easily done with Threads.
I recommend you create a new class to be used as the spalsh screen , it has to extends JFrame and implements Runnable.
I ll give you an example. I used the spash screen to display the screen and also to laod the main GUI form so that when the spash screen dispose, the main GUI form displays instantly, making the user think that the application loads faster.
public void run ()
try
this.setVisible(true);
Thread.sleep(2000);
// sets the menu visible before disposing
guiMenu.setVisible(true);
// disposes the object and returns the resources to the OS
this.dispose();
catch(InterruptedException exception)
exception.printStackTrace();
// this method must be implement in the class
// that implements Runnable interface
//MAIN
public class Main
public static void main(String[] args)
Menu menu = new Menu();
SplashScreen introScreen = new SplashScreen(menu);
ExecutorService splashExecutor= Executors.newFixedThreadPool(1);
splashExecutor.execute(introScreen);
}ExecutorService is a subinterface of Executor that declares methods for managing the threads. It also has the method execute (that provides the Executor interface) which when invoked calls the method public void run() of the argument class that must implement Runnable.
Executors.newFixedThreadPool(1); creates a poll consisting of a 1 thread which is been used by splashExecutor to execute the Runnable.
Hope i've been of some assistance! -
Calling an array from another class
Ok I have this little program that I created to display values stored in an array. Well, I want my array to automatically be populated with the same values that are in another array that resides in a different class. Here is my code for the class that I want the values to be displayed:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
double[] interest = new double[3];
MemicCSVReader[] interestObjectArray = new MemicCSVReader[3];
interestObjectArray[0] = new MemicCSVReader();
interestObjectArray[1] = new MemicCSVReader();
interestObjectArray[2] = new MemicCSVReader():
for(int x = 0; x < 3; x++)
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setText(interest[0]);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setText(interest[1]);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setText(interest[2]);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public static void main(String[] args)
GUIRead run = new GUIRead();
Here is my code that I want the double[] interest array to pull it's data from:
public class MemicCSVReader
double interestArray[];
MemicCSVReader()
String[] interestString = {"5.5","5.35","5.75"};
for(int x = 0; x < 3; x++)
interestArray[x] = Double.parseDouble(interestString[x]);
}Ok, thanks for your help. Now I have another problem. I can't get the values to display. Here is my code:
This is the program that runs the application:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
MemicCSVReader readCSV = new MemicCSVReader();
double[] interestDouble = readCSV.getInterestArray();
String[] interest;
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public void actionPerformed()
for(int x = 0; x < 3; x++)
interest[x] = Double.toString(interestDouble[x]);
interestText.setText(interest[0]);
interestText2.setText(interest[1]);
interestText3.setText(interest[2]);
public static void main(String[] args)
GUIRead run = new GUIRead();
This is the file that it pulls the array from:
public class MemicCSVReader
private double[] InterestArray = new double[3];
MemicCSVReader()
double[] InterestArray = {5.5,5.35,5.75};
public double[] getInterestArray()
return InterestArray;
} -
Compile error "illegal start of expression"
ok. so i have to make methods for a scrabble calculator applet, and just can't seem to get it right. this is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class scrabbleScore extends JApplet
implements ActionListener
* Make a text box
private JPanel display;
private JTextField word;
private JLabel number;
private JLabel d;
String s = "Type word here, then hit Enter";
String e = "|";
String f, c = " ";
int scr = 0;
String str[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int score[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 3, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
public void init(){
//Make text box
word = new JTextField (
"Type word here, then hit Enter", 20);
word.setBackground(Color.white);
word.setEditable(true);
word.addActionListener(this);
word.selectAll();
word.requestFocus();
//Draw the # box
number = new JLabel("# Appears here");
d = new JLabel("Letter values appear here");
//Draw the pane
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(word);
c.add(d);
c.add(number);
public void actionPerformed(ActionEvent e){
* check if word has text
JTextField word = (JTextField)e.getSource();
String w = word.getText();
w = w.toUpperCase();
w = w.trim();
if (validateData(w) == true) {
JOptionPane.showMessageDialog(this,
"You have not entered a valid word", "Error", JOptionPane.ERROR_MESSAGE);
else {
d.setText(wordValue(w));
number.setText("|| Value = " + computeScore(w) + " ||");
Boolean validateData(String w){
while (w.compareToIgnoreCase(s) != 0) {
return false;
return true;
//Method computeScore(String word)
String computeScore(String w){
*Put word in an array
String wrd[] = new String[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i) + "";
for (int i = 0; i < wrd.length; i++) {
String y = wrd;
int k = y.getValue();
scr += score[k];
public int getValue(String y) {
int num = 0;
String z = str[num];
while (y.compareTo(z) != 0) {
num++;
z = str[num];
return num;
//Return v to set text
String v = scr + "";
scr = 0;
return v;
String wordValue(String w){
char wrd[] = new char[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i);
for (int i = 0; i < wrd.length; i++) {
int value = Character.getNumericValue(wrd[i]);
value -= 10;
String a = " " + wrd[i] + " ";
c = "|" + a + "= " + score[value] + "|";
e = e + c;
f = e + "| ==>";
c = "";
e = "|";
return f;
}and i get an "illegal start or expression" compile error at the line public int getValue(String y). Does anyone know how i could fix this?Just so you guys can see it if you want to, here's my finished code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class scrabbleScore extends JApplet
implements ActionListener
* Make a text box
private JPanel display;
private JTextField word;
private JLabel number;
private JLabel d;
String s = "Type word here, then hit Enter";
String e = "|";
String f, c = " ";
int scr = 0;
String str[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int score[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 3, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
public void init(){
//Make text box
word = new JTextField (
"Type word here, then hit Enter", 20);
word.setBackground(Color.white);
word.setEditable(true);
word.addActionListener(this);
word.selectAll();
word.requestFocus();
//Draw the # box
number = new JLabel("# Appears here");
d = new JLabel("Letter values appear here");
//Draw the pane
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(word);
c.add(d);
c.add(number);
public void actionPerformed(ActionEvent e){
* check if word has text
JTextField word = (JTextField)e.getSource();
String w = word.getText();
w = w.toUpperCase();
w = w.trim();
if (validateData(w) == true) {
JOptionPane.showMessageDialog(this,
"You have not entered a valid word", "Error", JOptionPane.ERROR_MESSAGE);
else {
String[] wrd = makeArray(w);
d.setText(wordValue(w, wrd));
number.setText("|| Value = " + computeScore(w, wrd) + " ||");
resetValues();
Boolean validateData(String w){
while (w.compareToIgnoreCase(s) != 0) {
return false;
return true;
//Method getValue
int getValue(String y) {
int num = 0;
String z = str[num];
while (y.compareTo(z) != 0) {
num++;
z = str[num];
return num;
//Method makeArray
String[] makeArray(String w) {
String wrd[] = new String[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i) + "";
return wrd;
//method makeLetterValues
String makeLetterValues(String[] wrd, int i, int value) {
String a = " " + wrd[i] + " ";
c = "|" + a + "= " + score[value] + "|";
e = e + c;
return e;
//method resetValues
void resetValues() {
c = "";
e = "|";
scr = 0;
//Method computeScore(String word)
String computeScore(String w, String[] wrd){
//get score
for (int i = 0; i < wrd.length; i++) {
String y = wrd;
int k = getValue(y);
scr += score[k];
//Return v to set text
String v = scr + "";
return v;
//method wordValue
String wordValue(String w, String[] wrd){
//make letter value string
for (int i = 0; i < wrd.length; i++) {
int value = getValue(wrd[i]);
String e = makeLetterValues(wrd, i, value);
f = e + "| ==>";
return f; -
Can anyone help me solve my problem trying add GUI to Inventory program?
Here is my code in which I am receiving a couple of errors.
package inventory4;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Inventory4 extends JFrame implements ActionListener {
private class MyPanel extends JPanel {
ImageIcon image = new ImageIcon("Sample.jpg");
int width = image.getIconWidth();
int height = image.getIconHeight();
long angle = 30;
public MyPanel() {
super();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(angle), 60 + width / 2, 60 + height / 2);
g2d.drawImage(image.getImage(), 60, 60, this);
g2d.dispose();
}//end class MyPanel
int currentIndex; //Currently displayed Item
Product[] supplies = new Product[4];
JLabel name;
JLabel number;
JLabel title;
JLabel quantity;
JLabel price;
JLabel fee;
JLabel totalValue;
JTextField nameField = new JTextField(20);
JTextField numberField = new JTextField(20);
JTextField titleField = new JTextField(20);
JTextField quantityField = new JTextField(20);
JTextField priceField = new JTextField(20);
JPanel display;
JPanel displayHolder;
JPanel panel;
public Inventory4() {
setSize(500, 500);
setTitle("Bob's CD Inventory Program");
//make the panels
display = new JPanel();
JPanel other = new JPanel();
JPanel picture = new MyPanel();
JPanel centerPanel = new JPanel();
displayHolder = new JPanel();
display.setLayout(new GridLayout(7, 1));
//other.setLayout(new GridLayout(1, 1));
//make the labels
name = new JLabel("Name :");
number = new JLabel("Number :");
title = new JLabel("Title :");
quantity = new JLabel("Quantity :");
price = new JLabel("Price :");
fee = new JLabel("Restocking Fee :");
totalValue = new JLabel("Total Value :");
//Add the labels to the display panel
display.add(name);
display.add(number);
display.add(title);
display.add(quantity);
display.add(price);
display.add(fee);
//Add the panels to the frame
getContentPane().add(centerPanel, "Center");
getContentPane().add(other, "South");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
class CD extends Product {
String genre;
double restockingFee;
public CD(String genre, double restockingFee, int item, String title, double stockQuantity,
double price) {
//super(title,item, stockQuantity, price);
this.genre = genre;
this.restockingFee = restockingFee;
// TODO Auto-generated constructor stub
//returns the value of the inventory, plus the restocking fee
public double getInventoryValue() {
// TODO Auto-generated method stub
return super.getItemPrice() + restockingFee;
public String toString() {
StringBuffer sb = new StringBuffer("Genre \t").append(genre).append("\n");
sb.append(super.toString());
return sb.toString();
//Inventory4.java
class Product implements Comparable {
private String title; // class variable that stores the item name
private int item; // class variable that stores the item number
private double stockQuantity; // class variable that stores the quantity in stock
private double price; // class variable that stores the item price
private String genre;
public Product() {
title = "";
item = 0;
stockQuantity = 0;
price = 0.0;
genre = "";
public Product(String title, String genre, int item, double stockQuantity, double price) {
this.title = title;
this.item = item;
this.stockQuantity = stockQuantity;
this.price = price;
this.genre = genre;
public void setTitle(String title) {
this.title = title;
public String getTitle() {
return title;
public void setItem(int item) {
this.item = item;
public int getItem() {
return item;
public void setStockQuantity(double quantity) {
stockQuantity = quantity;
public double getStockQuantity() {
return stockQuantity;
public void setItemPrice(double price) {
this.price = price;
public double getItemPrice() {
return price;
public void setGenre(String genre) {
this.genre = genre;
public String getGenre() {
return genre;
public double calculateInventoryValue() {
return price * stockQuantity;
public int compareTo(Object o) {
Product p = null;
try {
p = (Product) o;
} catch (ClassCastException cE) {
cE.printStackTrace();
return title.compareTo(p.getTitle());
public String toString() {
return "CD Title: " + title + "\nGenre: " + genre + "\nItem #: " + item + "\nPrice: $" + price + "\nQuantity: " + stockQuantity + "\nValue with restocking fee: $" + (calculateInventoryValue() + (calculateInventoryValue() * .05));
public class Inventory4 {
Product[] supplies;
public static void main(String[] args) {
Inventory4 inventory = new Inventory4();
inventory.addProduct(new Product("Mozart", "Classical", 1, 54, 11.50));
inventory.addProduct(new Product("Beethoven", "Classical", 2, 65, 12.00));
inventory.addProduct(new Product("Tiny Tim", "Classical", 3, 10, 1.00));
System.out.println("Inventory of CD's:\n\n");
System.out.println();
inventory.showInventory();
System.out.println();
double total = inventory.calculateTotalInventory();
System.out.println("Total Value is: $" + (total + (total * .05)));
public void sortByName() {
for (int i = 1; i < supplies.length; i++) {
int j;
Product val = supplies;
for (j = i - 1; j > -1; j--) {
Product temp = supplies[j];
if (temp.compareTo(val) <= 0) {
break;
supplies[j + 1] = temp;
supplies[j + 1] = val;
//creates a String representation of the array of products
public String toString() {
String s = "";
for (Product p : supplies) {
s = s + p.toString();
s = s + "\n\n";
return s;
//Using an array so adding an item requires us to increase the size of the array first
public void addProduct(Product p1) {
if (supplies == null) {
supplies = new Product[0];
Product[] p = supplies; //Copy all products into p first
Product[] temp = new Product[p.length + 1]; //create bigger array
for (int i = 0; i < p.length; i++) {
temp[i] = p[i];
temp[(temp.length - 1)] = p1; //add the new product at the last position
supplies = temp;
//sorting the array using Bubble Sort
public double calculateTotalInventory() {
double total = 0.0;
for (int i = 0; i < supplies.length; i++) {
total = total + supplies[i].calculateInventoryValue();
return total;
public void showInventory() {
System.out.println(toString()); //call our toString methodI re-entered the package and changed some of the code. I am building successfully, but getting a new msg: init:
deps-jar:
compile:
run:
java.lang.NoClassDefFoundError: Inventory5_5
Caused by: java.lang.ClassNotFoundException: Inventory5_5
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Exception in thread "main"
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds) I may have to go ahead and submit it as is to get it in on time. Thank you very much for your help and your patience. Here is my last effort.package inventory4;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class inventory4 extends JFrame {
private class MyPanel extends JPanel {
ImageIcon image = new ImageIcon("Sample.jpg");
int width = image.getIconWidth();
int height = image.getIconHeight();
long angle = 30;
public MyPanel() {
super();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(angle), 60 + width / 2, 60 + height / 2);
g2d.drawImage(image.getImage(), 60, 60, this);
g2d.dispose();
}//end class MyPanel
int currentIndex; //Currently displayed Item
Product[] supplies = new Product[4];
JLabel name;
JLabel number;
JLabel title;
JLabel quantity;
JLabel price;
JLabel fee;
JLabel totalValue;
JTextField nameField = new JTextField(20);
JTextField numberField = new JTextField(20);
JTextField titleField = new JTextField(20);
JTextField quantityField = new JTextField(20);
JTextField priceField = new JTextField(20);
JPanel display;
JPanel displayHolder;
JPanel panel;
public inventory4() {
setSize(500, 500);
setTitle("Bob's CD Inventory Program");
//make the panels
display = new JPanel();
JPanel other = new JPanel();
JPanel picture = new MyPanel();
JPanel centerPanel = new JPanel();
displayHolder = new JPanel();
display.setLayout(new GridLayout(7, 1));
//other.setLayout(new GridLayout(1, 1));
//make the labels
name = new JLabel("Name :");
number = new JLabel("Number :");
title = new JLabel("Title :");
quantity = new JLabel("Quantity :");
price = new JLabel("Price :");
fee = new JLabel("Restocking Fee :");
totalValue = new JLabel("Total Value :");
//Add the labels to the display panel
display.add(name);
display.add(number);
display.add(title);
display.add(quantity);
display.add(price);
display.add(fee);
//Add the panels to the frame
getContentPane().add(centerPanel, "Center");
getContentPane().add(other, "South");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
class CD extends Product {
String genre;
double restockingFee;
public CD(String genre, double restockingFee, int item, String title, double stockQuantity,
double price) {
//super(title,item, stockQuantity, price);
this.genre = genre;
this.restockingFee = restockingFee;
// TODO Auto-generated constructor stub
//returns the value of the inventory, plus the restocking fee
public double getInventoryValue() {
// TODO Auto-generated method stub
return super.getItemPrice() + restockingFee;
public String toString() {
StringBuffer sb = new StringBuffer("Genre \t").append(genre).append("\n");
sb.append(super.toString());
return sb.toString();
//Inventory4.java
class Product implements Comparable {
private String title; // class variable that stores the item name
private int item; // class variable that stores the item number
private double stockQuantity; // class variable that stores the quantity in stock
private double price; // class variable that stores the item price
private String genre;
public Product() {
title = "";
item = 0;
stockQuantity = 0;
price = 0.0;
genre = "";
public Product(String title, String genre, int item, double stockQuantity, double price) {
this.title = title;
this.item = item;
this.stockQuantity = stockQuantity;
this.price = price;
this.genre = genre;
public void setTitle(String title) {
this.title = title;
public String getTitle() {
return title;
public void setItem(int item) {
this.item = item;
public int getItem() {
return item;
public void setStockQuantity(double quantity) {
stockQuantity = quantity;
public double getStockQuantity() {
return stockQuantity;
public void setItemPrice(double price) {
this.price = price;
public double getItemPrice() {
return price;
public void setGenre(String genre) {
this.genre = genre;
public String getGenre() {
return genre;
public double calculateInventoryValue() {
return price * stockQuantity;
public int compareTo(Object o) {
Product p = null;
try {
p = (Product) o;
} catch (ClassCastException cE) {
cE.printStackTrace();
return title.compareTo(p.getTitle());
public String toString() {
return "CD Title: " + title + "\nGenre: " + genre + "\nItem #: " + item + "\nPrice: $" + price + "\nQuantity: " + stockQuantity + "\nValue with restocking fee: $" + (calculateInventoryValue() + (calculateInventoryValue() * .05));
public class Inventory4 {
Product[] supplies;
public static void main(String[] args) {
Inventory4 inventory = new Inventory4();
inventory.addProduct(new Product("Mozart", "Classical", 1, 54, 11.50));
inventory.addProduct(new Product("Beethoven", "Classical", 2, 65, 12.00));
inventory.addProduct(new Product("Tiny Tim", "Classical", 3, 10, 1.00));
System.out.println("Inventory of CD's:\n\n");
System.out.println();
inventory.showInventory();
System.out.println();
double total = inventory.calculateTotalInventory();
System.out.println("Total Value is: $" + (total + (total * .05)));
public void sortByName() {
for (int i = 1; i < supplies.length; i++) {
int j;
Product val = supplies;
for (j = i - 1; j > -1; j--) {
Product temp = supplies[j];
if (temp.compareTo(val) <= 0) {
break;
supplies[j + 1] = temp;
supplies[j + 1] = val;
//creates a String representation of the array of products
public String toString() {
String s = "";
for (Product p : supplies) {
s = s + p.toString();
s = s + "\n\n";
return s;
//Using an array so adding an item requires us to increase the size of the array first
public void addProduct(Product p1) {
if (supplies == null) {
supplies = new Product[0];
Product[] p = supplies; //Copy all products into p first
Product[] temp = new Product[p.length + 1]; //create bigger array
for (int i = 0; i < p.length; i++) {
temp[i] = p[i];
temp[(temp.length - 1)] = p1; //add the new product at the last position
supplies = temp;
//sorting the array using Bubble Sort
public double calculateTotalInventory() {
double total = 0.0;
for (int i = 0; i < supplies.length; i++) {
total = total + supplies[i].calculateInventoryValue();
return total;
public void showInventory() {
System.out.println(toString()); //call our toString method -
How to append msg from second thread to main GUI thread?
I am facing a problem which I cannot seem to solve.
It involves Swing and threads. I have a main GUI running on swing. And it retrieves database information and displays it. On the same GUI I have a JTextArea box which I need another thread to update as and when that second thread recieves message via a multicast socket.
I managed to create a runnable class of the second thread and successfully ran the second thread with the main thread in tandem. However when I use
display.append(msgreceived);
I get a nullPointerException. It works fine when i use System.out.println(msgreceived);.
What should I have done instead?Here are part of the codes for my admin module.
public class Admin extends JFrame implements ActionListener {
//declares all the global variables
private JTextArea display;
public Admin() {
super("BX Online - Admin Module");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
AdminGUI();
AdminGUI() {
contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel newsbox = new JPanel();
display = new JTextArea(2, 40);
display.setEditable(false);
newsbox.add(display);
contentPane.add(newsbox);
contentPane.add(tabpaneO);
setBounds(70, 50, 300, 500);
pack();
setVisible(true);
// all the methods activated by buttons goes here
static public void main(String[] argv) {
Admin a = new Admin();
News b = new News("test");
The following are part of the codes for my runnable class.
public class News implements Runnable {
protected boolean again = true;
private String name, recieve; //the global variables
private Thread t;
public JTextArea display;
public BXnews(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New Thread: " + t); //visual check to make sure thread is started.
t.start();
private void msg() {
String recieve = ("testing");
System.out.println(recieve);
display.append(recieve);
public void run() {
while (again) //creates a loop so thread does not close
{msg();}
Well thats abt it. I'm not sure if you can compile this but basically the part I left out was the setup link for the News class which I don't see the need to add as what I primarily intend is for the message testing in News class to appear in Admin class thread in JTextArea "display". -
Breadth First Traversal of a Network
I am working on a task that reads from file a list of towns and displays their adjacent towns and distances.
I then have to do a breath first traversal of the network and am encountering problems in my code. Could someone please have a look at my code and see if they can see where I am going wrong.
Thank you
import java.awt.event.*;
import java.awt.*;
import java.util.Stack;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
public class BreadthFirstTraversal extends JFrame implements ActionListener
private Container c;
private JPanel pNorth,pCentre,pSouth;
private JButton btnExit;
private JScrollPane jsp;
private JLabel lblDummy;
private JTextArea display;
private Border border;
BreadthFirstTraversal(Vertex vStart)
c = getContentPane();
pNorth = new JPanel();
lblDummy = new JLabel();
pNorth.add(lblDummy);
pCentre = new JPanel();
display = new JTextArea(20,50);
display.setFont(new Font("Serif",Font.PLAIN,18));
jsp = new JScrollPane(display);
border = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
jsp.setBorder(border);
pCentre.add(jsp,BorderLayout.CENTER);
pSouth = new JPanel();
btnExit = new JButton("Exit");
btnExit.addActionListener(this);
pSouth.add(btnExit);
breadthFirst(vStart);
c.add(pNorth,BorderLayout.NORTH);
c.add(pCentre,BorderLayout.CENTER);
c.add(pSouth,BorderLayout.SOUTH);
private void breadthFirst(Vertex start)
lblDummy.setText("Breadth-First Traversal");
Arc currentArc = new Arc();
String currentTown;
List listStart,listRear,listNext;
listStart=null;listRear=null;listNext=null;
listStart=new List(start.getTown());//create first entry to queue
listRear=listStart;//set the rear to point to start of Queue as well
start.setProcessed(true);//set the town to processed
while(listStart!=null)//while queue is not empty
currentTown=listStart.getTown();//set current town to look at first
display.append(" "+listStart.getTown()+"; ");//append town to display text area
listStart=listStart.getLink();//leave the queue
currentArc=getAdjacentLink(start,currentTown);//get the link to the adjacent towns that need checked
//put adjacent towns on stack if not been processed
while(currentArc!=null)
if(!townIsProcessed(start,currentArc.getTwn()))//it its not processed
if(listStart==null)//if queue is empty
listStart=new List(currentArc.getTwn());//create the start of the queue
listRear=listStart;//set the rear to point at start
else
//Add to Rear of Queue
listNext=new List(currentArc.getTwn());//create next element to add to queue
listRear.setLink(listNext);//set the rear to point at the new item
listRear=listNext;//set the rear to the new item that was added
setProcessed(start, currentArc.getTwn());//set that town to have been processed
currentArc=currentArc.getLink();//move to next Arc
clearStatus(start);//set all prosessed booleans back to false
public Arc getAdjacentLink(Vertex start, String town)
Arc link= new Arc();
while(start!=null)
if(start.getTown().compareTo(town)==0)
link=start.getAdjacentTowns();
start=start.getLink();//move to next vertex
return link;
public void clearStatus(Vertex start)
while(start!=null)
start.setProcessed(false);
start=start.getLink();
public void setProcessed(Vertex start, String twn)
while(start!=null)
if(start.getTown().compareTo(twn)==0)
start.setProcessed(true);
start=start.getLink();
public boolean townIsProcessed(Vertex start,String town)
while(start!=null)
if(start.getTown().compareTo(town)==0)
if(start.isProcessed())
return true;
else
return false;
start=start.getLink();
return false;
public void actionPerformed(ActionEvent e)
}There are no errors in the code itself but when I try to run it I am getting the following messages in the console:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at BreadthFirstTraversal.townIsProcessed(BreadthFirstTraversal.java:130)
at BreadthFirstTraversal.breadthFirst(BreadthFirstTraversal.java:68)
at BreadthFirstTraversal.<init>(BreadthFirstTraversal.java:39)
at NetworkMenu.actionPerformed(NetworkMenu.java:161)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)It's not necessarily town that's causing the
NullPointerException. If start is null, then calling
getTown() on it would throw a NullPointerException.
If whatever getTown() returned was null, then calling
compareTo() on it would throw a NullPointerException.
So there are three places on that line where it could
be thrown.Wrong and, uh, wrong. The stack trace show that
if(start.getTown().compareTo(town)==0)causes a NPE in compareTo's code. If start were null, the NPE would
occur before compareTo could be entered. If getTown() returns
null then again the error occurs before entering compareTo's code.
Therefore, start != null and start.getTown() != null and town == null. -
Layout for editing database record
Hi!
I'm trying to make a JPanel display a database record for editing in a nice way, but I'm kinda stuck. Example:
Id: 10
First name: Peter
Last name: Johnson
Age: 20 and so on. The problem is that I don't know what strategy to use for the layout management, so that it looks good. I use JLabel for all labels and the Id number, since it's not editable, and JTextField s for the other data. I want the labels for the fields right aligned and the textfields left aligned "in their container", so that there is a streight line between the :s. (I hope you understand...)
Any help appreciated!
/JanThanks!
The missing link was the FlowLayout.RIGHT constant. I guess I hadn't done my homework.
Thanks for pointing that out!
/Jan -
Details for last question I post
the original code for last question I post(about the DataInputStream& EOFException) is here, thanks if anyone will bother to read it
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.* ;
public class MasterMindServer
public MasterMindServer()
try{
ServerSocket serverSocket=new ServerSocket(8000);
Socket socket=serverSocket.accept();
HandleAClient thread=new HandleAClient(socket);
thread.start();
}catch(IOException e){System.out.println("Error:"+e.toString());}
public static void main(String args[])
new MasterMindServer();
//inner class
class HandleAClient extends Thread
DataOutputStream out;
DataInputStream in;
BufferedReader fromFile;
private Socket socket;
String line;
public HandleAClient(Socket socket)
this.socket=socket;
public void run()
int x,o;
try{
out=new DataOutputStream(socket.getOutputStream());
in=new DataInputStream(socket.getInputStream());
fromFile=new BufferedReader(new FileReader("colorcode.txt"));
while((line=fromFile.readLine())!=null)
for(int i=0;i<10;i++)
String t=in.readUTF();
x=check_column(t);
System.out.println(x);
o=check_color(t);
System.out.println(o);
out.writeInt(x);
out.writeInt(o);
if(x==6) break;
out.writeUTF(line);
socket.close();
System.out.println("close");
}catch(IOException e){
System.out.println("Error:"+e.toString());}
public int check_column(String s)
String str;
str=s;
int count=0;
for(int i=0;i<6;i++)
if(s.charAt(i)==line.charAt(i))
count++;
return count;
public int check_color(String s)
String str;
str=s;
int count=0;
for(int i=0;i<6;i++)
if((line.indexOf(s.charAt(i))!=-1)&&(line.charAt(i)!=s.charAt(i)))
count++;
return count;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.* ;
public class MasterMindClient extends JFrame implements MouseListener,ActionListener
/** Default constructor */
//keep track of the row (or trial) and column number
int trial_num, col_now ;
Socket socket;
int count[]={5,5,5,5,5,5};
JPanel A[] = new JPanel[10];
JPanel B1[] = new JPanel[10];
JPanel B2[] = new JPanel[10] ;
JPanel notice = new JPanel() ;
JPanel sub_notice = new JPanel();
JPanel D1, D2 ;
static JTextField [][]color = new JTextField[10][6] ;
static JTextField [][]Output = new JTextField[10][2];
static JTextField [][]Answer = new JTextField[1][6] ;
static JButton []ok = new JButton[10];
JLabel L1 = new JLabel("Click the textfield to change color");
JLabel L2 , L3, L4 ;
String colorRange="BCGRYW";
Color colorName[]={Color.black,Color.cyan,Color.green,Color.red,Color.yellow,Color.white};
String temp ;
public MasterMindClient() {
// initialize
trial_num = 0;
col_now = 0;
//sub_notice is Panel where the heading labels are placed
sub_notice.setLayout(new GridLayout(1,3)) ;
L2 = new JLabel(" ") ;
L3 = new JLabel("X");
L3.setHorizontalAlignment(JTextField.CENTER);
L4 = new JLabel("O");
L4.setHorizontalAlignment(JTextField.CENTER);
L3.setToolTipText("matching color and column");
L4.setToolTipText("matching color but not matching column" );
sub_notice.add(L2);
sub_notice.add(L3);
sub_notice.add(L4);
notice.setLayout(new GridLayout(1,2)) ;
notice.add(L1) ;
notice.add(sub_notice) ;
// Get the content pane of the frame
Container c = getContentPane();
// Set GridLayout, 4 rows, 3 columns, and gaps 5 between
// components horizontally and vertically
c.setLayout(new GridLayout(12, 1, 5, 5));
c.add(notice);
JPanel Display = new JPanel() ;
Display.setLayout(new GridLayout(1,2,5,5)) ;
//create a Panel for each row to accept use input
// color[][] textfield is where the user input
// Output[][] is where to display the number of X and O
for (int i = 0; i <= A.length-1 ; i++)
A[i] = new JPanel() ;
A.setLayout(new GridLayout(1, 2,10,10));
B1[i] = new JPanel();
B1[i].setLayout(new GridLayout(1,6,5,5)) ;
B2[i] = new JPanel();
B2[i].setLayout(new GridLayout(1,3,5,5)) ;
for (int j = 0; j <= color[i].length-1 ; j++)
color[i][j] = new JTextField() ;
color[i][j].setHorizontalAlignment(JTextField.CENTER);
if (i == 0)
{color[i][j].setEditable(true) ;
else
{color[i][j].setEditable(false);
color[i][j].addMouseListener(this);
B1[i].add(color[i][j]) ;
} // j loop
ok[i] = new JButton("SEND");
if(i==0)
ok[i].setEnabled(true);
else
ok[i].setEnabled(false);
ok[i].addActionListener(this);
B2[i].add(ok[i]) ;
Output[i][0] = new JTextField();
Output[i][1] = new JTextField();
Output[i][0].setEditable(false);
Output[i][1].setEditable(false);
Output[i][0].setHorizontalAlignment(JTextField.CENTER);
Output[i][1].setHorizontalAlignment(JTextField.CENTER);
B2[i].add(Output[i][0]);
B2[i].add(Output[i][1]);
A[i].add(B1[i]);
A[i].add(B2[i]) ;
c.add(A[i]) ;
} //for i loop
//D panel is where we store the answer[][]
D1 = new JPanel();
D1.setLayout(new GridLayout(1,6)) ;
D2 = new JPanel();
D2.setLayout(new GridLayout(1,2)) ;
for (int j = 0; j <= Answer[0].length-1 ; j++)
Answer[0][j] = new JTextField(0) ;
Answer[0][j].setHorizontalAlignment(JTextField.CENTER);
Answer[0][j].setEditable(false) ;
D1.add(Answer[0][j]) ;
Display.add(D1) ;
Display.add(D2) ;
c.add(Display) ;
public void runClient()
try
{ socket=new Socket("localhost",8000);
DataInputStream in=new DataInputStream(socket.getInputStream());
int x=0;
int o=0;
try{
while(true)
while(trial_num<10)
x=in.readInt();
//System.out.println(x);
Output[trial_num][0].setText(String.valueOf(x));
o=in.readInt();
//System.out.println(o);
Output[trial_num][1].setText(String.valueOf(o));
for(int i=0;i<6;i++)
color[trial_num][i].setEnabled(false);
ok[trial_num].setEnabled(false);
trial_num++;
col_now=0;
if(x==6)
JOptionPane.showMessageDialog( null, "Congratulation, you've won the game !! " );
//ok[trial_num].setEnabled(false);
break;
if(trial_num<10)
{ for(int i=0;i<6;i++)
color[trial_num][i].setEditable(true);
count[i]=5;
ok[trial_num].setEnabled(true);
if(x!=6)
{ JOptionPane.showMessageDialog( null, "sorry you did not win the game");
temp=in.readUTF();
System.out.println(temp);
//temp=in.readUTF();
//System.out.println("can");
for(int i=0;i<6;i++)
System.out.println(i);
char a=temp.charAt(i);
int index=colorRange.indexOf(String.valueOf(a));
Answer[0][i].setBackground(colorName[index]);
trial_num=0;
for(int j=0;j<10;j++)
for(int k=0;k<6;k++)
color[j][k].setBackground(Color.white);
for(int j=0;j<10;j++)
for(int k=0;k<2;k++)
Output[j][k].setText(null);
for(int i=0;i<6;i++)
color[trial_num][i].setEditable(true);
count[i]=5;
ok[0].setEnabled(true);
catch(EOFException em){}
}catch(IOException ex){
System.out.println("Error:"+ex.toString());}
public void mouseClicked(MouseEvent e)
for(int i=0;i<6;i++)
if(e.getComponent()==color[trial_num][i])
{ col_now=i;
break;
count[col_now]=(count[col_now]+1)%6;
color[trial_num][col_now].setBackground(colorName[count[col_now]]);
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mouseReleased(MouseEvent e)
public void mousePressed(MouseEvent e)
public void actionPerformed(ActionEvent e)
try{
send();
}catch(IOException et){System.out.println("Error:"+et);}
public void send()throws IOException
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
char cbuf[]=new char[6];
for(int i=0;i<6;i++)
cbuf[i]=colorRange.charAt(count[i]);
System.out.println(cbuf);
out.writeUTF(new String(cbuf));
/** Main method */
public static void main(String[] args) {
MasterMindClient frame = new MasterMindClient();
frame.setTitle("Master Mind");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(300,300) ;
frame.setSize(450, 450);
frame.setVisible(true);
frame.runClient();
} // end of classI notice that you have several hundred lines of GUI code there. None of them have anything to do with the problem you are trying to solve. So put them all aside and write a SMALL test program that does nothing but the little loop you are having a problem with. Shouldn't be more than 20 lines of code.
Maybe you are looking for
-
When I open one in a few minutes Firefox closes it and opens the other one. It doesn't happen when I use Internet Explorer. It must be something to do with Firefox! Maybe I have some kind of e-mail access plugin that only recognizes one but not the o
-
Trading Parner Not Inherited to Cross Company Balance Sheet Line item
Hi, I posted cross company document using document type that is already untick in field 'inter-company posting' and 'enter tpid'. My accounting entries is as per below: Co1000 Cr Balance Sheet $250 Co1001 Dr Expense $10 Co10
-
Authorization Issue in Visibility of Lead and Opportunity Documents
HI, I have 4 sales Org in my Project. When an user from Sales Org 1 is searching a lead he was able to see all the leads when I tried to change Lead or opportunity of other sales org with my user id, system says that "You have no authorization to exe
-
ExternalInterface on IE?
Hi, I'm trying to use ExternalInterface to expose functions of my as3 code to javascript. It is working very well, following the Flash CS3 help on Firefox and Chrome browsers, however on IE 8 things are getting hard... At my HTML page I used the help
-
Hi guys I hope someone can help me
Hi guys I hope someone can help me I have a problem with Apple compressor 4. Everytime I use Apple clusters it works for the first time. And when I try to use it again it disappears. I have to delete the program and reinstalled it and then I can acti