Basic GUI problem
Okay, Im trying to create a simple input/output menu. I'm trying to get the GUI portion wrapped up but it's kicking my but. The display is suppose to have one side with a text=Enter Weekly Hour, a text entry field and a enter button. The other side will be the display. I have built these and put them in there round about locations but I have two problems.
1. The text "enter weekly hour", text entry field and the enter button are suppose to be one on top of each other.
2. When I resize the screen down or up it cuts off or rearranges the area's different than the way they are suppose to be.
I know I have to bind the heights of the components by placing them into another BorderLayout-managed container. Which I thought I have done. Obviously I am missing something really simple.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14NestedPanels1 extends JFrame {
// Data Members
* Default frame width
private static final int FRAME_WIDTH = 300;
* Default frame height
private static final int FRAME_HEIGHT = 170;
* X coordinate of the frame default origin point
private static final int FRAME_X_ORIGIN = 150;
* Y coordinate of the frame default origin point
private static final int FRAME_Y_ORIGIN = 250;
private JTextField inputEntry, outputDisplay;
private JLabel list, text;
// Main method
public static void main(String[] args) {
Ch14NestedPanels1 frame = new Ch14NestedPanels1();
frame.setVisible(true);
// Constructors
* Default constructor
public Ch14NestedPanels1() {
Container contentPane;
JPanel inputPanel;
JPanel listPanel;
JButton enterButton;
//set the frame properties
setSize (FRAME_WIDTH, FRAME_HEIGHT);
setTitle ("Program Ch14NestedPanels1");
setLocation (FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
contentPane = getContentPane( );
contentPane.setLayout(new BorderLayout(5,5));
//Creates panel for entry items inputEntry,text, and enterButton
inputPanel = new JPanel();
inputPanel.setBorder(BorderFactory.createLoweredBevelBorder());
contentPane.add(inputPanel, BorderLayout.WEST);
//Creates text entry field
inputEntry = new JTextField(10);
inputPanel.add(inputEntry,BorderLayout.CENTER);
//Creates text label
text = new JLabel("Enter weekly hour");
inputPanel.add(text,BorderLayout.NORTH);
//Creates enter button
enterButton = new JButton("Enter");
inputPanel.add(enterButton,BorderLayout.SOUTH);
//Creates panel for list display
listPanel = new JPanel();
listPanel.setBorder(BorderFactory.createLoweredBevelBorder());
listPanel.add(list = new JLabel("This is where the list goes"));
contentPane.add(listPanel,BorderLayout.EAST);
setDefaultCloseOperation( EXIT_ON_CLOSE );
Your basic code is like this:
inputPanel = new JPanel();
inputEntry = new JTextField(10);
inputPanel.add(inputEntry,BorderLayout.CENTER);
text = new JLabel("Enter weekly hour");
inputPanel.add(text,BorderLayout.NORTH);
enterButton = new JButton("Enter");
inputPanel.add(enterButton,BorderLayout.SOUTH);
By default when you create a JPanel it uses a FlowLayout. So when you add a component to the panel the components a layed out Left-to-Right.
Using BorderLayout.CENTER, NORTH, SOUTH is ignored by the FlowLayout manager.
You should be using:
JPanel inputPanel = new JPanel( new BorderLayout() );
Now when yo add component to your panel you can use the BorderLayout constraints.
Similar Messages
-
Hello
I have a JLabel2 which shows the spanish map. The thing is I do wanna draw lines on my spanish map and save it to as an image file in my desktop . I'm able to draw lines and save my JLabel2(spanish map) as an image in my Desktop. The problem is I'm not able to see any lines that I draw before in my image file. I can see those lines when I do click draw button but I can not see them when I save my file as an image to my desktop.Please help me.This problem killed me for two days..you can see how i converted to icon and how i save it as an image file below.Thank you for your helps from now.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
File file3;
int returnVal = fc.showSaveDialog(routemap.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File f3 = fc.getSelectedFile();
ImageIcon icon = (ImageIcon) jLabel2.getIcon();
System.out.println(icon.getIconHeight());
BufferedImage buf = new BufferedImage(icon.getImage().getWidth(
null), icon.getImage().getHeight(null),
BufferedImage.TYPE_INT_RGB);
buf.getGraphics().drawImage(icon.getImage(), 0, 0,
icon.getIconWidth(), icon.getIconHeight(), null);
ImageIO.write(buf, "jpg", new File(f3.getAbsolutePath()
+ ".jpg"));
System.out.println(f3.getAbsolutePath());
} catch (IOException e) {
I have drawn lines by using draw function as you see below and I can not see those lines without any problem..Lines disapper in the image file when I do save it..Here is the draw button..
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
boolean go = true;
if (OneClicked == false && go == true) {
jLabel3.setText(jComboBox1.getSelectedItem() + " to ");
view = jComboBox1.getSelectedItem().toString() + " to ";
String m = jComboBox1.getSelectedItem().toString();
int size1 = City.size();
for (int i = 0; i < size1; i++) {
if (City.get(i).equals(m)) {
Index.add(i);
OneClicked = true;
go = false;
if (OneClicked == true && go == true) {
jLabel3.setText(view + jComboBox1.getSelectedItem());
view = "";
String m = jComboBox1.getSelectedItem().toString();
int size1 = City.size();
for (int i = 0; i < size1; i++) {
if (City.get(i).equals(m)) {
Index.add(i);
Graphics g = jLabel2.getGraphics();
g.setColor(Color.BLUE.darker());
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3));
System.out.println(Index.size());
System.out.println(Index.size() - 2);
int m1 = Integer.parseInt(XCoordinate.get(Index
.get(Index.size() - 2)));
int n1 = Integer.parseInt(YCoordinate.get(Index
.get(Index.size() - 2)));
int m2 = Integer.parseInt(XCoordinate.get(Index
.get(Index.size() - 1)));
int n2 = Integer.parseInt(YCoordinate.get(Index
.get(Index.size() - 1)));
System.out.println(m1 + " " + n1 + " " + m2 + " " + n2);
g2.drawLine(m1, n1, m2, n2);
OneClicked = false;
System.out.println("index im" + Index);
}Cross-post: [java-forums: jlabel-gui-problem|http://www.java-forums.org/java-applets/15472-jlabel-gui-problem.html]
To the original poster, cross-posting can frustrate anyone who tries to help you only to find out later that the same answer was given hours ago in a cross-posted thread. No one likes wasting their time, especially a volunteer. The polite thing to do would be to not do this, but if you feel that you absolutely must, to at least provide links in both cross-posts to each other.
edit: all over the dang place: [javaranch: JLabel-GUI|http://www.coderanch.com/t/428887/Swing-AWT-SWT-JFace/java/JLabel-GUI]
Now this could get folks wanting to not help you ever. Please take care here.
Edited by: Encephalopathic on Jan 31, 2009 6:34 AM -
Hi Vasundhara,
Try grouping the widgets in to a panel.
Thanks,
Madhu
-----Original Message-----
From: vasundhara [mailto:[email protected]]
Sent: Wednesday, April 25, 2001 9:15 AM
To: [email protected]; Joseph Mirwald
Subject: Re: (forte-users) GUI problem with UNIX
Hi Joseph
We are using Forte 3.0 M2 on Solaris 5.8 The problem is with the push
buttons, After we grid the controls and they look intact in the NT
environment, but when we open the same window in SOlaris the controls are
far apart.Do you have any idea about this?
Regards
Vasundhara
----- Original Message -----
From: Joseph Mirwald <mailto:[email protected]>
To: vasundhara <mailto:[email protected]> ;
[email protected] <mailto:[email protected]>
Sent: Wednesday, April 25, 2001 10:13 AM
Subject: Re: (forte-users) GUI problem with UNIX
Hello vashundara,
please say which Version of Forte and which kind/version your UNIX OS is.
There are some problems on AIX V4.3.x (Motif 2.x) and older releasese of
Forte (up to Forte 3.M.x) and so on and it is necessary to look what it is.
Maybe it is possible for you to say which widgets are the problem.
Thanks forward
Joseph Mirwald
At 15:25 23.04.01 +0530, vasundhara wrote:
Hi
We are facing a strange problem when we try to port our application from NT
to UNIX. The problem is that the GUI doesnt come properly. As per my
knowledge gridding all the controls on the GUI shouldnot create this
problem, but inspite of this we are facing it. Did anyone comeacross this
situation?
Thanks in advance
Regards
Vasundhara N.C
Wisor Telecom Pvt Ltd
Bangalore
India -
Hi everyone,
I have been trying to get this GUI built from the ground up and I have encountered a problem with the GridBag(exception error that the fields being added can not be done. Also, my method main seems to be off track, I have a working program which the display fields have been modified to display object and everything else is the same except that I can not get the GUI to run.
The following is the code and any suggestions as to what I can do to get this going will be appreciated. Thank you.
import javax.swing.JLabel; /* displays text and images*/
import javax.swing.SwingConstants; /* common constants used with Swing*/
import javax.swing.Icon; /* interface used to manipulate images*/
import javax.swing.ImageIcon; /* loads images*/
import javax.swing.JOptionPane;
import java.util.*;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.*;
import javax.swing.JFrame;/* provides basic window features*/
import java.util.Arrays;
import javax.swing.ImageIcon.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class FinalInventoryGUI extends JFrame
{//Private variables.
private GridBagLayout layout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
//Private data from main program
private String productName;
private String itmeNumber;
private double unitPrice;
private int unitStock;
private double productValue;
private double inventoryValue;
private double reStkfee;
//Declaration of the JLabels.
private JLabel logoLabel;
private JLabel productNameLabel;
private JLabel itemNumberLabel;
private JLabel unitPriceLabel;
private JLabel unitStockLabel;
private JLabel productValueLabel;
private JLabel InventoryValueLabel;
private JLabel reStkfeeLabel;
//Declaration of the text Fields for data Entry.
private JTextField productNameText;
private JTextField itemNumberText;
private JTextField unitPriceText;
private JTextField unitStockText;
private JTextField productValueText;
private JTextField inventoryValueText;
private JTextField reStkfeeText;
private JTextField titleText;
//Declaration of the JButtons for user interface.
private JButton first;//To move to first element in the array.
private JButton next;//To move to next element in the array.
private JButton previous;//To move to next element in the array.
private JButton lastButton;//To move to the first element in the array.
private JButton addButton;//To add a product to the array.
private JButton modifyButton;//To modify an element in the array.
private JButton deleteButton;//To remove a product from the array.
private JButton saveButton;//To save the array elements to C:\.
private JButton searchButton;//To search for an element in the array.
private Product products[];//Declaration of array product[] for storing entries.
private int NumOfProducts;//Declaration of the variable defining the number of products.
private int Index=0;//Setting the counter index to initiate at "0".
//Constants
private final static int LOGO_WIDTH = 4;
private final static int LOGO_HEIGHT = 4;
private final static int LABEL_WIDTH = 1;
private final static int LABEL_HEIGHT = 1;
private final static int TEXT_WIDTH = LOGO_WIDTH-LABEL_WIDTH;
private final static int TEXT_HEIGHT = 1;
private final static int BUTTON_WIDTH = 1;
private final static int BUTTON_HEIGHT = 1;
private final static int LABEL_START_ROW = LABEL_HEIGHT+LABEL_WIDTH+1;
private final static int LABEL_COLUMN = 0;
private final static int TEXT_START_ROW = LABEL_START_ROW;
private final static int TEXT_COLUMN = LABEL_WIDTH+1;
private final static int BUTTON_START_ROW = LABEL_START_ROW+9*LABEL_HEIGHT;
private final static int BUTTON_COLUMN = LABEL_COLUMN;
private final static int SEARCH_START_ROW = BUTTON_START_ROW+3;
final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new PRODUCT";
//Constructor-New instance of the JLabelTextFieldView.
public FinalInventoryGUI( Product productsIn)
{//Passing the frame title to JFrame, set the IconImage.
super("Welcome To The Inventory Program");
setLayout(layout);
//Copy the input array(products).
setProduct(productsIn);//maybe the title?????
//Start the display with the first element of the array.
index = 0;
//Build the GUI
buildGUI();
//Values
updateAllTextFields();
}//End of the constructor for building the GUI.
//Methods for copying the input of Product array to the GUIs private array
//variable
private void setInventoryArray(Product productsIn[])
products = new Product[productIn.length];
for (int i = 0; i<products.length; i++)
{//Creates A Product array element from the input array.
prodcuts[i] = new Product(productIn);
products[i] = new Product(productIn[i].productName(), productIn[i].itemNumber(),
productIn[i].unitStock(), productIn[i].unitPrice());
//System prints out a ineof the productsIn array to a string.
}//End of the for statment.
}//End for copying the array.
//A method for updating each of the GUIs fields.
private void updateAllTextFields()
if(products.length > 0)//Then update the JTextField display.
{// Update the product name text field.
productNameText.setText(products[index].productName());
//Update the Update the itemNumber text field.
itemNumberText.set(String.format("%d", products[index].itemNumber()));
//Update the title text field.
titleText.setText(dvd[index].title());
//Update the unitStock text field.
unitStockText.setText(String.format("%d",products[index].unitStock()));
//Update the unit price textField.
unitPriceText.setText(String.format("$%.2f",products[index].unitPrice()));
//Update the productValue textField.
productValueText.setText(String.format("$%.2f", products[index].productValue()));
//Update the restocking fee text field.
reStkfeeText.setText(String.format("$%.2f",reStkfee()));
//Update the total value of the inventory text field.
inventoryValueText.setText(String.formtat("$%.2f",Product.productValue(products)));
}//End of the if statement.
else//Put a special message in the fields.
{//Update the productName textField.
productNameText.setText(EMPTY_ARRAY_MESSAGE);
//Update the itemNumber textField
itemNumberText.setText(EMPTY_ARRAY_MESSAGE);
//Update the title textField.
titleText.setText(EMPTY_ARRAY_MESSAGE);
//Update the units in stock textField.
unitStockText.setText(EMPTY_ARRAY_MESSAGE);
//Update the unitPrice textFied.
unitPriceText.setText(EMPTY_ARRAY_MESSAGE);
//Update the productValue textField.
productValueText.setText(EMPTY_ARRAY_MESSAGE);
//Update the restocking fee textField.
reStkfeeText.setText(EMPTY_ARRAY_MESSAGE);
//Update the totatl inventoryValue textField.
inventoryValueText.setText(EMPTY_ARRAY_MESSAGE);
}//End else
}//Set the appropriate fields editable or uneditable.
private void setModifiableTextFieldsEnabled(Boolean state)
{//The fields of the product name, item number, unit price,
// and stock can be editable or non editable.
itemNumber.setEditable(state);
productName.setEditable(state);
unitPrice.setEditable(state);
unitStock.setEditable(state);
}//End setting of the modifiable textFields.
//Methods for the JButton methods.
private class ButtonHandler implements ActionListener
public void actionPerformed(ActionEvent event)
{//This is the first button being pressed by the user.
if(event.getSource()==firstButton)
handleFirstButton();
}//End if
else if(event.getSource()==previousButton)//Button previous is pressed by user.
handlePreviousButton();
}//End else if
else if (event.getSource()==nextButton)//Button next is pressed by user.
handleNextButton();
}//End else if.
else if (event.getSource()==lastButton)//Button last is pressed by the user.
handleLastButton();
}//End else if.
else if(event.getSource()==firstButton)
handleFirstButton();
}//End else if.
}//End metod of actionPeformed.
}//End class ButtonHandler
//Displaying the first element of the Product array
private void handlerFirstButton()
{//Setting the index to the first element in the array.
index = 0;
//Update and disable modification
updateAllFields();
setModifiableTextFieldsEnabled(false);
}//End method for handling the first button.
//Displaying the next element of the products array or wrap to the first.
private void handleNextButton()
{//Incrementation of the index.
index++;
//If the index exceeds the last valid array element, wrap around to the first
//element of the array.
if(index > products.length-1)
index = 0;
}//End if statment.
//Update and disable the modification.
updateAllFields();
setModifiableTextFieldsEnabled(false);
}//End method of handleNextButton.
private void handlePreviousButton()
index--;
if(index < 0)
index = products.length -1;
}//End if statment.
//Update and disabe modification.
updateAllTextFields();
setModifiableTextFieldsEnabled(false);
}//End method of handlePreviousButton.
private void handleLastButton()
index--;
if(index < products.length -1)
index = 2;
}//End if statment.
updateAllTextFields();
setMdifiableTextFieldsEnabled(false);
}//End method for handleLatButton
//The textFieldHandler class - handling the events of the buttonsmethods
private class TextFieldHandler implements ActionListener
public void actionPerformed(ActionEvent event)
{//The user pressed "ENTER" in the JTextField "title" text.
if(event.getSource() == itemNumber)
//HandleItemNumberTextField()is fired.
}//End the if statement.
//The user pressed "ENTER" in the JTextField "title" text.
else if (event.getSource() == titleText)
//HandleTitleTextField() is fired.
}//End the if statement.
//The user pressed "ENTER" in the JTextField "unitStoc" text.
else if(event.getSource() == unitStockText)
//HandleUnitStockTextField() is fired.
}//End the if statment
//The user pressed "ENTER" in the JtextField "unitPrice" text.
else if (event.getSource() == unitPriceText)
//HandleUnitPriceTextField() is fired.
}//End the if statment.
//The user pressed "ENTER" in the JTextField "Search" text.
else if(event.getSource() == searchText)
//HandleSearchTextField() is fired.
}//End the if statment.
}//End the method actionPerformed.
}//End the inner class TextFieldhandler.
//The GUI methods.
//Building the GUI.
private void BuildGUI()
{//Mthod for adding the LOGO.
buildLogo();
//Add the text fields and their labels.
buildLabels();
buildTextFields();
//Add the navigation and other buttons.
buildMainButtons();
//Provide value to the Fields.
updateAllTextFields();
//provide some setup to the frame.
setSize(FRAME_LENGTH, FRAME_WIDTH);
setLocation(FRAME-XLOC, FRAME_YLOC);
setResizable(false);
//PACK(); IS THIS NOT PART OF THE GUI ADDED AT THE END OR IS WHAT
//FOLLOWS THE SAME AS SAYING ".PACK()".
setDefaultCloseOperation(EXIT_ON_CLOSE);//DOES IT MATTER WHERE THIS LINE FALLS?
//WHEN I TRIED TO USE IT IN THE MAIN I RECEIVED AN ERROR AND THE SAME WHEN I
//PLACED IT IN THE CONSTRUCTOR--WHY?.
setVisible(true);
}//End of building the GUI.
//Addin the LOGO to the Frame.
private void buildLogo()
constraints.weightx = 2;
constraints.weigthy = 1;
logoLabel = new JLabel(new ImageIcon("O2K.jpg"));
logoLabel.setText("Products Inventory");
constraints.fill = GridBagConstraints.BOTH;
addToGridbag(logoLabel,2,2,LOGO_WIDTH, LOGO_HEIGHT);
//Creating a vertical space.
addToGridBag(new JLabel(""),LOGO_HEIGHT+1,0, LOGO_WIDTH, LABEL_WIDTH);
}//End the method with building the LOGO.
//Build the panel just containing the text.
private void buildLabels()
{//Set up if for readability).
int rows = 0;
int column = 0;
int width = 0;
int height = 0;
column = LABEL_COLUMN;
width = LABEL_WIDTH;
height = LABEL_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
constraints.fill = GridbagConstraints.Both;
//Create the name labes and name the TextFields.
productNameLabel = new JLabel("Product Name:");
productnamelabel.setLabelfor(productNameField);
productNameLabel.setLabelFor(productNameText);
productNameLabel.setToolTipText("Enter The Product Name Here");
row = Label_START_ROW;
addToGridBag(productNameLabel, row, column, width, height);
//Create the itemNumberLabel and TextField.
itemNumberLabel = new JLabel("Product Id:");
itemNumberLabel.setLabelFor(itemNumberText);
row += LABEL_HEIGHT;
addToGridBag(itemNumber, row, column, width, height);
//Create the title label for the Product and the title text field.
titleLabel = new JLabel("Inventory Of Products:");
titleLabel.setLabelFor(titleText);
row += LABEL_HEIGHT;
addToGridBag(titleLabel,row,column,width,height);
//Create the unitStock label and textField.
unitStockLabel = new JLabel("Units In Stock:");
unitStockLabel.setLabelFor(unitStockLabel);
row += LABEL_HEIGHT;
addToGridBag(unitStocklabel, row, column, height);
//Creat the unitPrice label and textField.
unitPriceLabel = new JLabel("Unit Price");
unitPriceLabel.setLabelFor(unitPriceLabel);
unitPriceLabel.setToolTipText("The Cost Of The Product");
row += LABEL_HEIGHT;
addToGridBag(unitPriceLabel, row, column, height);
//Create the productValue label and textField.
productValueLabel = new JLabel("Total Product Value:");
productValueLabel.setLabelFor(productValueLabel);
row += LABEL_HEIGHT;
addToGridBag(productValue, row, column, height);
//Create the restocking fee of 1.05% Label and textField.
reStkfeeLabel = new JLabel("Product Restock Fee:");
reStkfeeLabel.setLabelFor(reStkfeeLabel);
row+= LABEL_HEIGHT;
addToGridBag(reStkfee, row, column, height);
//Create a vertical space.
row += LABEL_HEIGHT;
//Create the Total Inventory Value label and textField.
inventoryValueLabel = new JLabel("Total Inventory Value:");
inventoryValueLabel.setLabelFor(inventoryValueLabel);
row += LABEL_HEIGHT;
addToGridBag(inventoryValue, row, column, height);
}//End the method for building the labels
//Build the methods for the TextFields.
private void buildTextFields()
{//Defining the variables
int row = 0;
int column = 0;
int width = 0;
int height = 0;
column = TEXT_COLUMN;
width = TEXT_WIDTH;
height = TEXT_HEIGHT;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
TextFieldHandler handler = new TextFieldHandler();
productNameText = new JTextField("Product Name");
productNameText.setEditable(false);
row = TEXT_START_ROW;
addToGridBag(productNameText, row, column, height);
itemNumberText = new JTextField("Product Id");
itemNumberText.setEditable(false);
row = TEXT_START_ROW;
addToGridBag(itemNumberText, row, column, height);
titleText = new JTextField("Title");
titleText.addActionListener(handler);
titleText.setEditable(false);
row += TEXT_HEIGHT;
addToGridBag(titleText, row, column, height);
unitPriceText = new JTextField("Unit Price");
unitPriceText.addActionListener(handler);
unitPrice.setEditable(false);
row += TEXT_START_ROW;
addToGridBag(unitPriceText, row, column, height);
unitStockText = new JTextField("Units In Stock");
unitStockText.addActionListener(handler);
unitStockText.setEditable(false);
row += TEXT_START_ROW;
addToGridBag(unitStockText, row, column, height);
productValueText =new TextField("Product Value");
productValueText.addActionListener(handler);
productValueText.setEditable(false);
row += TEXT_START_ROW;
addToGridBag(productValueText, row, cloumn, height);
reStkfeeText =new JTextField("Restock Fee");
reStkfeeText.addActionListener(handler);
reStkfeeText.setEditable(false);
row += TEXT_START_ROW;
addToGridBag(reStkfeeText, row, cloumn, height);
//Creat vertical space.
row += TEXT_HEIGHT;
addToGridBag(new JLabel(""),row, column, height);
inventoryValueText =new TextField("Inventory Value");
inventoryValueText.addActionListener(handler);
inventoryValueText.setEditable(false);
row += TEXT_START_ROW;
addToGridBag(inventoryValueText, row, cloumn, height);
}//End the methods for building the TextFields.
//Add the main buttons to the frame.
private void buildMainButtons()
{//Declaraing the variables.
int row = 0;
int column = 0;
int width = 0;
int height = 0;
row =BUTTON_START_ROW;
column = BUTTON_COLUMN;
width = BUTTON_WIDTH;
height = BUTTON_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
//The constraints.fill = GridBagConstraints.HORIZONTAL;
ButtonHandler handler = new ButtonHandler();
//Creat a veritical space.
addToGridbag(new JLabel(""), row, column, width, height);
firstButton = new JButton("First");
firstButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(firstButton, row, column, width, height);
previousButton = new JButton("Previous");
previousButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(previousButton, row, column, width, height);
nextButton = new JButton("Next");
nextButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(nextButton, row, column, width, height);
lastButton = new JButton("Last");
lastButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(lastButton, row, column, width, height);
addButton = new JButton("Add");
addButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(addButton, row, column, width, height);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(deleteButton, row, column, width, height);
saveButton = new JButton("Save");
saveButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(saveButton, row, column, width, height);
searchButton = new JButton("Search");
searchButton.addActionListener(handler);
row += LABEL_HEIGHT;
addToGridBage(searchButton, row, column, width, height);
//End methods for building the main butt0ns.
private void addToGridBag(Component component, int row, int column, int width, int height)
{ //Set up the upper-left corner of the component gridx and gridy.
constraints.gridx = column;
constraints.gridy = row;
//Set the numbers of rows and columns the components occupies.
constraints.gridwidth = width;
constraints.gridheight = height;
//set the constraints
Layout.setConstraints(component, constraints);
//Add the component to the JFrame.
add(component);
}//End method for addGridBag.
//End class JLabelTextFieldViewGui.
class Invetnory4
public static void main(String args[])
{ //An array variable.
Product[]inventory;
inventory = new Product[10];
//Create and pass control to the GUI
FinalInventory gui = new FinaInventoryGUI(inventory);
}//End method main
}//End class Inventory4
/*Inventory.java*/
/*Means for importing program packages*/
/*Beginning of the class type Inventory*/Hi Bryan,
I took your advice and decided to take a different approach to the problem I am having, I decided to stay somewhat with the basics with little knowledge I have about coding. I am new to this and I am trying to learn through the fire but it's getting hot so if you don't mind, can you tell me what I need to do to fix the error messages I am getting.
1. "else" without "if',
2. can't load my icon-a JPG
3. exception in thread amin
process complete.
4.Text area for displaying an iteration of the input
the code is not as long as the other one! any help will be appreciated. Also I am attaching the code to the GUI that does work but I can not seem to get the actionListener aspect to work. Thanks again.
//this one works and it serves as a model for what I am //trying to do in the fields. as well as designate a text area //where a each entry per iteration of input is displayed
* @(#)InventoryGUIFrame.java
* @author
* @version 1.00 2008/2/2
package components;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
* FormattedTextFieldDemo.java requires no other files.
* It implements a mortgage calculator that uses four
* JFormattedTextFields.
public class InventoryGUIFrame extends JFrame
String productName;
String itemNumber;
double unitPrice;
double unitStock;
//Labels to identify the fields
private JLabel productNamelabel;
private JLabel itemNumberlabel;
private JLabel unitPricelabel;
private JLabel unitStocklabel;
//Fields for data Entry
private JTextField productNameField;
private JTextField itemNumberField;
private JTextField unitPriceField;
private JTextField unitStockField;
//Adding the JButtons
JButton firstButton;
JButton nextButton;
JButton previousButton;
JButton searchButton;
JButton addButton;
JButton deleteButton;
JButton saveButton;
//Constructor
public InventoryGUIFrame()
super("Welcome To The Inventory Program");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame Frame = new JFrame();
Frame JPanel = new Frame();
JPanel JLabel= new JPanel();
TextArea area = new TextArea();
productNamelabel = new JLabel("PRODUCT NAME");
productNamelabel.setToolTipText("Name of the item you wish to calculate");
add(productNamelabel);
productNameField= new JTextField(8);
add(productNameField);
itemNumberlabel = new JLabel("PRODUCT NUMBER");
itemNumberlabel.setToolTipText("Number identifying the product");
add(itemNumberlabel);
itemNumberField =new JTextField(5);
add(itemNumberField);
unitPricelabel=new JLabel("PRODUCT PRICE");
unitPricelabel.setToolTipText("What is the cost of the product?:");
add(unitPricelabel);
unitPriceField = new JTextField(5);
add(unitPriceField);
unitStocklabel = new JLabel("UNITS IN STOCK");
unitStocklabel.setToolTipText("How many products in inventory?:");
add(unitStocklabel);
unitStockField = new JTextField(5);
add(unitStockField);
firstButton =new JButton("First");
add(firstButton);
nextButton = new JButton("Next");
add(nextButton);
previousButton = new JButton("Previous");
add(previousButton);
addButton = new JButton("Add");
add(addButton);
deleteButton = new JButton("Delete");
add(deleteButton);
saveButton = new JButton("Save");
add(saveButton);
searchButton = new JButton("Search");
add(searchButton);
public static void main(String args[])
InventoryGUIFrame frame = new InventoryGUIFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(740,150);
frame.setVisible(true);
class InventorySystem6
{ /*Declaration of products[] and the maximum storing capacity*/
private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
/*Prompts user to make another selection or exit program*/
private static final String STOP_COMMAND = "stop";
/*parameters defining maximun numbers of products available for storing in */
private static final int MAX_NUM_OF_PRODUCTS = 100;
/*Declaration of the variables */
String name;
String item;
double stock;
double price;
double reStkfee=1.05;
double pValue;
double iValue;
public InventorySystem6()
/*Empty Constructor*/
}/*Beginning of product input by the user*/
public void inputProductInfo()
{ /*Declaration of currency format*/
DecimalFormat Currency = new DecimalFormat();
Scanner input = new Scanner(System.in);
/*Beginning of the Loop*/
JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
JOptionPane.PLAIN_MESSAGE);
for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
name = JOptionPane.showInputDialog( "What is the Product Name? ");
if(name.equalsIgnoreCase("stop"))
break;
String item = JOptionPane.showInputDialog("Enter the products ID");
String priceStr =JOptionPane.showInputDialog("Enter the products price");
double price=Double.parseDouble(priceStr);
String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
double stock = Double.parseDouble(stockStr);
double sum=price*stock;
JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
JOptionPane.PLAIN_MESSAGE);
/* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
,"\n","The Product Id is "+productId,"Product ID"
,"\n","The Unit Price is"+unitPrice,"Unit Price"
,"\n","The Units In Stock is"+unitStock,"UnitStock"
,"\n","The Product Value is"+productValue, "productValue"
,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
,"\n",JOptionPane.PLAIN_MESSAGE);*/
//Product products[] = new Product[100];
products[i] = new Product();
products[i].setitem(item);
products[i].setname(name);
products[i].setprice(price);
products[i].setstock(stock);
products[i].setpValue(sum);
products[i].setreStkfee(reStkfee);
iValue += sum + products[i].getreStkfee();
public void displayProductInfo()
{ /*Initialization of the variable total inventory value*/
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
Product product = products[i];
if(product==null)
System.out.println(products[i]);
break;
System.out.printf("product name: %s\n ", product.getname());
System.out.printf("product ID: %s \n", product.getitem());
System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getprice()));
System.out.printf("units in Stock: %s \n", product.getstock());
System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getpValue()));
System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
System.out.printf("Inventory Value: %s \n", iValue);
}/*Beginning of method main*/
public static void main(String[] args)
{/*Message*/
/*Means for retrieving and storing new data input into inventory program*/
InventorySystem6 JTableImageCreator = new InventorySystem6();
JTableImageCreator.displayProductInfo();
JTableImageCreator.inputProductInfo();
class Product
/*Declaration of and default value of specified variables*/
//private Product products[] = new Product[100];
private String item;
String name;
private double stock;
private double price;
private double pValue;
private double reStkfee;
//private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
private double iValue;
/*method defining the get and set values of each individual variable*/
public String getname()
{/*Mean for storing and retrieving input of name*/
return name;
}/*Means for setting the product name*/
public void setname(String name)
{/*null pointer argument exception defining metod for obtainng product name*/
this.name = name;
}/*Means for getting the units identifcation number inputted by the user*/
public String getitem()
{/*Means for returning the user input*/
return item;
}/*Means for setting the units identifcation */
public void setitem(String item)
{/*null pointer argument exception for setting the product identification number*/
this.item = item;
}/*Means for getting the units value input*/
public double getstock()
{/*Means for returning the variable of the units*/
return stock;
}/*Means for setting the units value*/
public void setstock(double stock)
this.stock = stock;
public double getprice()
{/*Means for returning the dollar value of the price of the unit(s)*/
return price;
}/*Means for setting and requesting user to input + dollar amt*/
public void setprice(double price)
this.price = price ;
}/*Means for setting the value of the total product value*/
public void setpValue(double pValue)
this.pValue = pValue+(price*stock);
}/*Means for getting the value of the product*/
public double getpValue()
{/*Means for returning the value*/
return pValue;
}/*Means for getting the TtlInventoryValue of products entered*/
public void setiValue(double iValue)
{/*Condition Statement*/
this.iValue=iValue;
public double getiValue()
return iValue;
public void setreStkfee(double reStkfee)
this.reStkfee=stock*price*1.05;
/*Means for setting restockin fee of the total products*/
public double getreStkfee()
{/*Means for calculating the restocking fee of each products units nStock*/
return reStkfee;
}/*Method for string the elements in [i] for display*/
public String toString()
{/*Means for returning defined string of elements in [i]*/
return "Product{" +
"item="+ item +
", name="+ name +
", stock="+ stock +
", price="+price +
", pValue="+pValue +
", reStkfee="+ reStkfee +
", iValue="+iValue+
}/*End set and get method*/
}/*End of class Product*/
/*Delcaration of the class type sortproductNames*/
class sortproductNames extends Product
{/*Declaration of the variable productName*/
protected String name;
/*Means for setting and getting values of the variable productName*/
public void setname(String name)
this.name = name;
public String getname()
return name;
public int compareTo(Object object)
{ // for sorting by product name
Product anotherProduct = (Product) object;
return name.compareTo( anotherProduct.name);
g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
else;
g.drawString("O2K", 10,10);
* @(#)InventoryGUIFrame.java
* @author
* @version 1.00 2008/2/2
package components;
import java.io.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.imagio.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
* FormattedTextFieldDemo.java requires no other files.
* It implements a mortgage calculator that uses four
* JFormattedTextFields.
public class InventoryGUIPanelFrameTextArea extends JFrame
String productName;
String itemNumber;
double unitPrice;
double unitStock;
//Labels to identify the fields
private JLabel productNamelabel;
private JLabel itemNumberlabel;
private JLabel unitPricelabel;
private JLabel unitStocklabel;
//Fields for data Entry
private JTextField productNameField;
private JTextField itemNumberField;
private JTextField unitPriceField;
private JTextField unitStockField;
private Product[] products;
private int unitStock;
private int currentIndex=0;
//Adding the JButtons
JButton firstButton;
JButton nextButton;
JButton previousButton;
JButton searchButton;
JButton addButton;
JButton deleteButton;
JButton saveButton;
//Constructor
public InventoryGUIPanelFrameTextArea()
super("Welcome To The Inventory Program");
this.products = products;
this.numOfProducts = products;
JFrame JPanel = new JFrame();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout());
showLogo();
showLabels();
showInputFields();
showButtons();
public void showLogo()
O2K myLogo = new O2K();
this.add(myLogo);
public void showLabels()
JPanel panel = new JPanel();
panel.add(new JLabel("PRODUCT NAME"));
panel.add(new JLabel("ITEM NUMBER"));
panel.add(new JLabel("UNIT PRICE"));
panel.add(new JLabel("UNITS IN STOCK"));
this.add(panel);
public void showInputFields()
itemNumber =new JTextField(5);
itemNumber.setEditable(false);
productName= new JTextField(10);
productName.setEditable(false);
unitPrice= new JTextField(5);
unitPrice.setEditable(false);
unitStock = new JTextField(10);
unitStock.setEditable(false);
panel.setEditable(false);
panel.add(itemNumber);
panel.add(productName);
panel.add(unitPrice);
panel.add(unitStock);
this.add(panel);
public void showButtons()
JPanel panel = new JPanel();
first = new JButton("First");
next = new JButton("Next");
previous = new JButton("Previous");
add = new JButton ("Add");
delete = new JButton ("Delete");
search = new JButton ("Search");
save = new JButton ("Save");
panel.add(first);
panel.add(next);
panel.add(previous);
panel.add(add);
panel.add(delete);
panel.add(search);
panel.add(save);
panel.add(this);
ButtonActionHandler handler = new ButtonActionHandler();
first.addActionListener(handler);
next.addActionListener(handler);
previous.addActionListener(handler);
add.addActionListener(handler);
delete.addActionListener(handler);
search.addActionListener(handler);
save.addActinListener(handler);
this.add(panel);
setFields(0);
protected void paintComponent (Graphics g)
public void setFields(int i)
setItemNumber(i);
setProductName(i);
setUnitPrice(i);
setUnitStock(i);
public void setItemNumber( int i)
itemNumber.setText(products[i].getItemNumber());
public void setProductName(int i)
productname.setText(products[i].getProductName());
public void setUnitPrice( int i)
unitPrice.setText(String.valueOf(products[i].getunitPrice()));
public void setUnitStock(int i)
unitStock.setText(String.valueOf(products[i].getunitStock()));
private class ButtonActionHandler implements ActionListener
public void actionPerformed(ActionEvent event)
if(event.getSource()==first)
currentIndex=0;
setFields(currentIndex);
else if(event.getSource()==next)
currentIndex++;
if(currentIndex==unitStock);
currentIndex--;
setFields(currentIndex);
else if (event.getSource()==previous)
currentIndex--;
if(curentIndex < 0)
currentIndex=0;
setFields(currentIndex);
else if(event.getSource()==last)
currentIndex = unitStock -1;
setFields(currentIndex);
else if(event.getSource()==add)
currentIndex = productName ++;
setFields(currentIndex);
else if(event.getSource()==delete)
currentIndex= productName -1;
setFields(currentIndex);
else if (event.getSource()==search)
currentIndex=productName ++;
setFields(currentIndex);
else if (event.getSource()==save)
currentIndex=productName ++;
setFields(currentIndex);
public static void main(String args[])
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(400,300);
mainFrame.setVisible(true);
class InventorySystem6
{ /*Declaration of products[] and the maximum storing capacity*/
private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
/*Prompts user to make another selection or exit program*/
private static final String STOP_COMMAND = "stop";
/*parameters defining maximun numbers of products available for storing in [i]*/
private static final int MAX_NUM_OF_PRODUCTS = 100;
/*Declaration of the variables */
String name;
String item;
double stock;
double price;
double reStkfee=1.05;
double pValue;
double iValue;
public InventorySystem6()
/*Empty Constructor*/
}/*Beginning of product input by the user*/
public void inputProductInfo()
{ /*Declaration of currency format*/
DecimalFormat Currency = new DecimalFormat();
Scanner input = new Scanner(System.in);
/*Beginning of the Loop*/
JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
JOptionPane.PLAIN_MESSAGE);
for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
name = JOptionPane.showInputDialog( "What is the Product Name? ");
if(name.equalsIgnoreCase("stop"))
break;
String item = JOptionPane.showInputDialog("Enter the products ID");
String priceStr =JOptionPane.showInputDialog("Enter the products price");
double price=Double.parseDouble(priceStr);
String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
double stock = Double.parseDouble(stockStr);
double sum=price*stock;
JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
JOptionPane.PLAIN_MESSAGE);
/* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
,"\n","The Product Id is "+productId,"Product ID"
,"\n","The Unit Price is"+unitPrice,"Unit Price"
,"\n","The Units In Stock is"+unitStock,"UnitStock"
,"\n","The Product Value is"+productValue, "productValue"
,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
,"\n",JOptionPane.PLAIN_MESSAGE);*/
//Product products[] = new Product[100];
products[i] = new Product();
products[i].setItemNumber(itemNumber);
products[i].setPrdocutName(productName);
products[i].setUnitPrice(unitPrice);
products[i].setUnitStock(unitStock);
products[i].setProductValue(sum);
products[i].setReStkfee(reStkfee);
inventoryValue += sum + products[i].getreStkfee();
public void displayProductInfo()
{ /*Initialization of the variable total inventory value*/
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
Product product = products[i];
if(product==null)
System.out.println(products[i]);
break;
System.out.printf("product name: %s\n ", product.getproductName());
System.out.printf("product ID: %s \n", product.getitemNumber());
System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getunitPrice()));
System.out.printf("units in Stock: %s \n", product.getunitStock());
System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getproductValue()));
System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
System.out.printf("Inventory Value: %s \n", inventoryValue);
}/*Beginning of method main*/
public static void main(String[] args)
{/*Message*/
/*Means for retrieving and storing new data input into inventory program*/
InventorySystem6 JTableImageCreator = new InventorySystem6();
JTableImageCreator.displayProductInfo();
JTableImageCreator.inputProductInfo();
class Product
/*Declaration of and default value of specified variables*/
//private Product products[] = new Product[100];
protected String itemNumber;
protected String prodcutname;
protected double unitStock;
protected double unitPrice;
protected double productValue;
protected double reStkfee;
protected double inventoryValue;
//private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
/*method defining the get and set values of each individual variable*/
public String getproductName()
{/*Mean for storing and retrieving input of name*/
return productName;
}/*Means for setting the product name*/
public void setProductName(String productName)
{/*null pointer argument exception defining metod for obtainng product name*/
this.productName = ProductName;
}/*Means for getting the units identifcation number inputted by the user*/
public String getitemNumber()
{/*Means for returning the user input*/
return itemNumber;
}/*Means for setting the units identifcation */
public void setItemNumber(String itemNumber)
{/*null pointer argument exception for setting the product identification number*/
this.itemNumber = itemNumber;
}/*Means for getting the units value input*/
public double getunitStock()
{/*Means for returning the variable of the units*/
return unitStock;
}/*Means for setting the units value*/
public void setUnitStock(double unitStock)
this.unitStock = unitStock;
public double getunitPrice()
{/*Means for returning the dollar value of the price of the unit(s)*/
return unitPrice;
}/*Means for setting and requesting user to input + dollar amt*/
public void setUnitPrice(double unitPrice)
this.unitPrice = unitPrice ;
}/*Means for setting the value of the total product value*/
public void setProductValue(double prodcutValue)
this.prodcutValue = unitPrice*unitStock;
}/*Means for getting the value of the product*/
public double getproductValue()
{/*Means for returning the value*/
return productValue;
}/*Means for getting the TtlInventoryValue of products entered*/
public void setInvetnoryValue(double invetnoryValue)
{/*Condition Statement*/
this.inventoryValue=inventoryValue;
public double getinvetotyValue()
return productValue;
public void setReStkfee(double reStkfee)
this.reStkfee=stock*price*1.05;
/*Means for setting restockin fee of the total products*/
public double getreStkfee()
{/*Means for calculating the restocking fee of each products units nStock*/
return reStkfee;
}/*Method for string the elements in [i] for display*/
public String toString()
{/*Means for returning defined string of elements in [i]*/
return "Product{" +
"itemNumber="+ itemNumber +
", productName="+ productName +
", unitStock="+ unitStock +
", unitPrice="+unitPrice +
", productValue="+prodcutValue +
", reStkfee="+ reStkfee +
", inventoryValue="+inventoryValue+
}/*End set and get method*/
}/*End of class Product*/
/*Delcaration of the class type sortproductNames*/
class sortproductNames extends Product
{/*Declaration of the variable productName*/
protected String name;
/*Means for setting and getting values of the variable productName*/
public void setProdcutName(String productName)
this.productName = productName;
public String getproductName()
return productName;
public int compareTo(Object object)
{ // for sorting by product name
Product anotherProduct = (Product) object;
return productName.compareTo( anotherProduct.productName);
class myGraphics extends component
private BufferedImage image;
private boolean imageFound = true;
public myGraphics()
super();
try
image=ImageIO.read(new File("Logo.jpg"));
catch(IOException x)
x.printStackTrace();
imageFound = false;
public void paint(Graphics g)
g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
else;
g.drawString("O2K", 10,10); -
Hi all,
Well basically I have 3 classes; one is called the loader which has the main function and all it does is call the second class which is the GUI class. This class buils up the GUI. The Third class however is a class which has an infinite loop inside until a button on the GUI is clicked. HOWEVER... due to the infinite loop, the GUI stays inactive until the loop ends which basically is like having a crashed GUI and thus the button can never be clicked!!
What do you suggest? Shall the loader load the third class and the third class loads up the GUI? Or is that not practical?
Thanks allHi again,
I still have a similar problem.
basically whats happening is...
From the GUI I launch a class with an infinite loop !!
Part of the Loop is to await a connection and when connected, a new Class is again launched, it processes and closes itself, and returns back to the infinite loop !!
I would like to know how I can Detach from the infinite loop to keep the GUI working...
thanks all -
Mutlithreading with GUI problem
hey guys,
I was working on some Socket programming assignment and encountered an intersting problem.
i am using Swing for GUI and Threads to communicate with clients.
My server GUi has a JButton("Start Server") to trigger the Server. or we can say.. it starts accepting connection( SocketObj = ServerSocketObj.accept() )
problem:
as soon as i press the only Button(i.e. StartServer Button) on my Server GUI. whole GUI freezes!
but Server is working... all updates on GUI are missing.. cant repaint components, etc. neither WindowClosing event , setDefaultCloseOperation()) is working.
i did some research.. found that swing components are not thread safe,
also found some close answers,, along the lines of.. Event Dispatch Thread, SwingUtilities.invokeLater(Runnable), SwingWorker class , but neither work or maybe i did not implement them properly..
Attachment contains my code for:
Server.java : Server class conatins main()
ServerGUI.java : gui for server.. called from Server Class
ClientHandler.java : Thread for handling clients.. also called from Serve class
Cleint.java : simple client to connect to server at localhost
Any sort of help would be highly obliged.
thanks in advance.
- Ravihere is the code...
Server.java
import java.net.*;
import java.io.*;
public class Server {
private ServerSocket ss;
private Socket sc;
public ServerSocket getSs() {
return ss;
public void setSs(ServerSocket ss) {
this.ss = ss;
public Socket getSc() {
return sc;
public void setSc(Socket sc) {
this.sc = sc;
public Server() {
try{
ss = new ServerSocket(4000);
}catch(IOException e){e.printStackTrace();}
startGUI();
public void startGUI()
new ServerGUI(this);
public void getConnection()
int i = 1;
try {
Socket sc = getSc();
while (true) {
sc = getSs().accept();
Thread t = new Thread(new ClientHandler(sc,i));
t.start();
System.out.println("got client " + i);
i++;
} catch (IOException e) {
e.printStackTrace();
public static void main(String[] args) {
new Server();
}ServerGUI.java
import java.net.*;
import java.io.*;
public class ServerGUI extends javax.swing.JFrame {
private javax.swing.JButton jButton1;
Server m;
public ServerGUI(Server m) {
initComponents();
this.m=m;
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(178, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(147, 147, 147))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(93, 93, 93)
.addComponent(jButton1)
.addContainerGap(184, Short.MAX_VALUE))
pack();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
m.getConnection();
}ClientHandler.java
import java.net.*;
public class ClientHandler implements Runnable {
Socket sock;
int n;
public ClientHandler(Socket s, int n) {
sock = s;
this.n = n;
public void run() {
while (true) {
System.out.println("Client Thread: " + n);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}Client.java
import java.net.*;
import java.io.*;
public class Client {
Socket sc;
public Client() {
try{
sc=new Socket("127.0.0.1",4000);
System.out.println("got server");
}catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
public static void main(String args[])
new Client();
} -
I am new to GUIs and have been working on a project for quite some time now. My problem is that I have a program working perfectly fine when I compile and run it on JGrasp (it's a demo version using just jOptionPanes). I am amking the GUIs in Netbeans. But when I run some of the GUI java files that I make in Netbeans on JGrasp, it gives me package errors. Can someone tell me what I need to "package" or import onto jGrasp in order to get it to work. I really don't know much about packages too much either.
Here's an error sample:
Add.java:141: package org.jdesktop.layout does not exist
org.jdesktop.layout.GroupLayout InputPanelLayout = new org.jdesktop.layout.GroupLayout(InputPanel);
This is from JGrasp, I don't get any errors compiling it in Netbeans...it's really odd.>
Add.java:141: package org.jdesktop.layout does not
exist
org.jdesktop.layout.GroupLayout
InputPanelLayout = new
org.jdesktop.layout.GroupLayout(InputPanel);
This is from JGrasp, I don't get any errors compiling
it in Netbeans...it's really odd.Well, the problem is that in your JGrasp the package org.jdesktop.layout was not found.
check your packages.
=) -
SQL Developer and Java GUI problems
I am having a problem with all the java apps i use, including Oracle SQL Developer. When i load up SQL developer, the top of the "Connections" text is chopped off as well as all the table names in the list when I make a connection. Also the java buttons are rather large. Almost as if they have a carriage return in the text of the button.
Its seems the gui configuration for java has been corrupted, but i cannot find where to modify those settings. I cant find anything on the internet on this. I have checked my video card settings and modified them to see if that is the issue, but it doesnt fix the problem.
Since other java apps do the same thing, I know its a java issue, but Ive uninstalled all the JRE's and JDKs i have and reinstalled them, and I still have the problem.
Im on an Windows XP box and running the JDK and JRE 1.5.0_09 versions. Any help would be appreciated. its very annoying to not be able to read some of the text in the java apps including sql developer due to the tops being cut off.
I have an ATI RADEON 7000 on an DELL optiplex gx620.
any help would be appreciatedThe first thing to try, if you haven't already, is to update your video driver.
-
Hi
I have installed solaris 10 x86 in my pc having lg monitor standard monitor 2.54 celeron processor , installation was smooth with no problem , after booting iam not able to get gui it is out of range frenquency error in the monitor ,but iam able to work in cli
will any body to how resolve it
With rgds
TarunThe trick is to edit your xorg.conf file to only
include the frequencies your monitor can support.
Simply comment out the odd ones you know don't seem
right. To be on the safe side I would set it to
800x600 60hz just to get it up and then adjust as
needed.This is exactly my problem also. However, being a newbie to Unix, I am at a loss for where Xorg.conf resides. I also don't seem to have Xsun at the location in the previous message.
Any ideas? Thanks, Tony -
Hi All,
we are using SAP logon 640. In screen painter we are not getting GUI. we are getting the screen in Alphanumeric mode, But not in Graphical mode. How to resolve this problem.
Thanks in Advance.
Regards,
chandra.
Message was edited by: K Chandra Sekhara ReddyHi k chandra,
1. I supppose, the alphanumeric
screen painter comes up.
2. When it comes up,
UTILITIES------>SETTINGS
3. a new window will come
TICK the chekbox for
'Graphical Layout Editor'
4. Then try, it will work.
5. <b>If still it does not work,
then another problem could be
SAP GUI Installation.
6. When installting sap gui,
we have to select the component for
Screen Painter GUI.</b>
(Probabably it was not selected when
installing on your machine)
7. Then it will come.
regards,
amit m. -
I'm new to CS3. I'm using Dreamweaver, and I want to use the
Spry XML deatail region display. I followed the tutorial for the
Aquo example. When I transfer all of the files to my server, the
spry js effects don't work. No errors, just no function. I checked
the file paths and made sure they matched and that files were in
the right directories on the server. It seems like this must be
something so basic that it's not in the help files. Can anyone
help?"lanfest" <[email protected]> wrote in
message
news:gnulsa$jo9$[email protected]..
> When I transfer
> all of the files to my server, the spry js effects don't
work. No
> errors, just
> no function.
Without seeing your files, any answer is pure guesswork. Post
a URL to
the problem page, and someone should be able to help you.
David Powers
Adobe Community Expert, Dreamweaver
http://foundationphp.com -
Hello!
I want to use visual basic to build a htm which can control labview throght datasocket, i set the switch
as " Swithc until release " in visual basic, the code is
Private Sub CWButton1_Click()
CWDataSocket1.Data = CWButton1.Value
End Sub
but the led of labview can't light on.
is the code problem?
thanks!The problem is most likely because you have the code in the Click() event handler. The click event in VB is a left mouse down AND mouse up over the controls. If you are wanting it to send out the value when you press and hold the button down, change the event handler to the ValueChanged event.
Best Regards,
Chris Matthews
National Instruments -
Hi I am working with jdev10g (120x19dbg)
I have created one query region.this shows simple as well as advanced search.
in advanced search i have 15 criteria, i have mapped them properly and search is also happening.
My problem is related to UI part. In advanced search all 15 criterai comes in one column (which takes away full page from top to botyom) and also prompts are wrapped.
At the same time simple search GUI works perfectly.
I don't why this is happening...
pls help
NaveenAre you getting alignment issue with 4 columns also? Did you try to resize the window and test? Also test with 2-3 different browsers.
--Shiv -
Hi everyone..
i am new to java..i want to know the importance of interfaces in java....
interface A{
public void print();
class B implements A{
public void print()
System.out.println("Please explain me the importance of Interfaces");
the class B can also be defined with out interface as the following...
class B {
public void print()
System.out.println("Please explain me the importance of Interfaces");
Both the classes have the same functionality ... then what the use of declaring an Interface and implementing it...?
PLEASE EXPLAIN BASIC USE OF INTERFACES....?
Note: Ignore any syntax errors in the code that i have written above
thanks in advanceIn Java, mostly we use inheritance for code reuse.
public class Toy{
public class Ball extends Toy{
}Suppose there is another class Type which doesn't related to Toy family.
public class Tyre{
}Now we know that Ball and Tyre are bouncable. So we will have to implement bounce() method in both class which behave differently.
public class Ball extends Toy{
public void bounce() {
}Suppose there is another class Type which doesn't related to Toy family.
public class Tyre{
public void bounce() {
}*If want to collect bouncable things into a single collection, then how can we do that?*
There is way, we can use abstract class:-
public abstract BouncingThings {
public abstract void bounce();
}Now things that are bouncable can extend BouncingThings class and the collection of bounce things will be
BouncingThings [] bouncingThings;
But there is one problem Java doesn't allow multiple class inheritance. So Ball can't extend both Toy and BouncingThings.
We can use interface:-
public interface Bouncable{
void bounce();
public class Ball extends Toy implements Bouncable{
public void bounce(){
public class Tyre implements Bouncable{
public void bounce(){
Bouncable[] bouncableThings = { new Ball().new Tyre() };Edited by: SandipGaikwad on Oct 16, 2007 12:23 PM -
I have an abstract base class that extends JFrame. It's not in a package and is directly in my project.
The base class has some JPanels, JButtons, and JLabels. I create a class and derive from the base class, and the derived class adds a JButton and a few private methods. Everything compiles fine and
the program runs fine.
The problem is when I click F12 to go into designer mode for the derived class to view the GUI, I see a red dialog with the name of the base class in the upper-left corner, and this message in the bottom of the IDE:
Failed to create live instance for variable 'this'. null
Failed to create live visual subcomponent this as BaseFrame(cls); creating a red component in its place
I've tried everything, and have the latest JBuilder8 patch.
Can anyone help with this? I have seen one other person on the web with the same exact problem, but he got zero responses indicating it's probably difficult to solve the issue.I found out why this is happening, but I don't yet know how to fix it. It's a start.
The reason the derived class does not show the JFrame in the Design mode is
that the base class is an abstract class. When I remove the abstract keyword
from the base class, it works and I can view the JFrame in Design mode for the derived class.
Now to figure out how to keep the base class abstract and still have design mode work.
Maybe you are looking for
-
More fun with enumerated dropdowns - Binding to table
Hi All, I'm having some trouble with enumerated dropdowns. My context is as follows: node DATA 1...1 ---> node FLIGHTS 0...N -->CARRID etc from SFLIGHTS --->DDL (element type string) I have successfully tried to add a simple dropdown with the foll
-
I can't get into a development site that colleagues in the office have no difficulty with
-
Integration SAP APO consultant duties
Hi Gurus, can any one let me know what are the duties of integration consultant in SAP APO (DP,SNP,PPDS) ? Please let me know if you guys have any answers Thanks & Regards, Raj kumar
-
Premiere Pro 2.0 HDV problem
I have installed the free version announced for Pr PRO 2.0, using the license number given. Works well for DV clips, but for HDV clips they can't be viewed. Is there a limit on this free version, as it is for the new one's (like CS5 for exemple) wher
-
Hi, we have got the following issues with the build in SAP Transaction iView: If you create a SAP Transaction iView using the iView Wizard the WinGUI is displayed within the portal frameset. The "Create a new session" button is disabled. - Is it poss