Help with a better GUI??
hi everyone!!
i am thinking for a better GUI i have already made..earlier my GUI was not reflecting any changes but with the help and suggestions by many of you i have tried to change it..but i still find it is not reflecting to be a good interface.i really need some help..i am hereby posting the code ..hope to get a good GUI than i have..
Thanks a lot
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class front3 extends JFrame
JRadioButton split,zip,rename,unzip;
ButtonGroup radioGroup;
public front3()
Container c = getContentPane();
c.setLayout(new GridLayout(0,1));
c.setBackground(Color. cyan);
setSize(530,120);
setResizable(false); // to disable the maximize button
ImageIcon ip= new ImageIcon("title.jpg");
JLabel j1=new JLabel("Choose the operation to be done :",ip,JLabel.CENTER);
j1.setBackground(Color.red);
c.add(j1);
ImageIcon ii= new ImageIcon("split.jpg");
split=new JRadioButton("Splitter",ii,false);
split.setBackground(Color.cyan);
ImageIcon ij= new ImageIcon("zip.jpg");
zip=new JRadioButton("Zipper",ij,false);
zip.setBackground(Color.cyan);
ImageIcon ik= new ImageIcon("rename.jpg");
rename=new JRadioButton("Rename all",ik,false);
rename.setBackground(Color.cyan);
ImageIcon il= new ImageIcon("unzip.jpg");
unzip=new JRadioButton("unzip",il,false);
unzip.setBackground(Color.cyan);
c.add (split);
c.add(zip);
c.add(unzip);
c.add(rename);
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add(split );
radioGroup.add( zip);
radioGroup.add(rename );
radioGroup.add( unzip);
// setPosition(250,250);
setTitle("FILE UTILITY SOFTWARE");
setSize(300,500);
setVisible(true);
split.addItemListener(new ItemListener()
public void itemStateChanged(ItemEvent event)
if(split.isSelected())
Gui file = new Gui();
zip.addItemListener(new ItemListener()
public void itemStateChanged(ItemEvent event)
if(zip.isSelected())
zipping file = new zipping();
unzip.addItemListener(new ItemListener()
public void itemStateChanged(ItemEvent event)
if(unzip.isSelected())
decompress file = new decompress();
rename.addItemListener(new ItemListener()
public void itemStateChanged(ItemEvent event)
if(rename.isSelected())
rename file = new rename();
public static void main(String args[])
front3 f=new front3();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
System.exit(0);
}
simply run this code to see the GUI-
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class front33 extends JFrame
JRadioButton split,zip,rename,unzip;
ButtonGroup radioGroup;
public front33()
Container c = getContentPane();
c.setLayout(new GridLayout(0,1));
c.setBackground(Color. cyan);
setSize(530,120);
setResizable(false); // to disable the maximize button
ImageIcon ip= new ImageIcon("title.jpg");
JLabel j1=new JLabel("Choose the operation to be done :",ip,JLabel.CENTER);
j1.setBackground(Color.red);
c.add(j1);
ImageIcon ii= new ImageIcon("split.jpg");
split=new JRadioButton("Splitter",ii,false);
split.setBackground(Color.cyan);
ImageIcon ij= new ImageIcon("zip.jpg");
zip=new JRadioButton("Zipper",ij,false);
zip.setBackground(Color.cyan);
ImageIcon ik= new ImageIcon("rename.jpg");
rename=new JRadioButton("Rename all",ik,false);
rename.setBackground(Color.cyan);
ImageIcon il= new ImageIcon("unzip.jpg");
unzip=new JRadioButton("unzip",il,false);
unzip.setBackground(Color.cyan);
c.add (split);
c.add(zip);
c.add(unzip);
c.add(rename);
// create logical relationship between JRadioButtons
radioGroup = new ButtonGroup();
radioGroup.add(split );
radioGroup.add( zip);
radioGroup.add(rename );
radioGroup.add( unzip);
// setPosition(250,250);
setTitle("FILE UTILITY SOFTWARE");
setSize(300,500);
setVisible(true);
public static void main(String args[])
front33 f=new front33();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e)
System.exit(0);
}
Similar Messages
-
Help with Times Table GUI applet
Hello,
I need help with an applet which inputs an integer from the user and displays the appropiate times table up to times 10 eg; user input 5 - display shows
5 time 1 is 5
5 times 2 is 10
5 times 10 is 50.
I have only managedt o get the display to show one statement eg 5 times 1 - I have tried using a for loop to show the whole table - but unlike a print statement each time the loop goes round it overwrites the data in the display box with the new data - any help would be much appreciated.
Note: it is for a programming course year 1 exercise - so I can only use basic constructs or loops to achieve this. Thanks in advance! Heres what I have so far:
import java.applet.* ;
import java.awt.* ;
import java.awt.event.* ;
public class TimesTableApplet extends Applet implements ActionListener
// Declare the GUI components globally
Label titleLabel, whichTableLabel ;
TextField whichTableBox, resultBox ;
Button showTableButton, clearButton ;
// Declare integer variables for holdind the number input by the user,
// the times number, and the result number
int whichTable, times=1, result ;
// Declare variables to hold string versions of the three integer variables
// above, for placing in the TextFields
String whichTableString, timesString, resultString ;
public void init ()
// Create the Labels
titleLabel = new Label ( "Times Table" ) ;
whichTableLabel = new Label ( "Which Table?" ) ;
// Create the TextFields
whichTableBox = new TextField ( 5 ) ;
resultBox = new TextField ( 30 ) ;
// Create the Buttons
showTableButton = new Button ( "Show Table" ) ;
clearButton = new Button ( "Clear" ) ;
// Add the components to the applet window
add ( titleLabel ) ;
add ( whichTableLabel ) ;
add ( whichTableBox ) ;
whichTableBox.addActionListener ( this ) ;
add ( resultBox ) ;
resultBox.setEditable ( false ) ;
add ( showTableButton ) ;
showTableButton.addActionListener ( this ) ;
add ( clearButton ) ;
clearButton.addActionListener ( this ) ;
} // End of init method
public void actionPerformed ( ActionEvent event )
// Find out which button generated the event
String arg = event.getActionCommand () ;
// If the user clicks the clear button, clear the whichTableBox and
// resultBox
if ( arg.equals ( "Clear" ) )
whichTableBox.setText ( "" ) ;
resultBox.setText ( "" ) ;
else
try
// Try extracting a string from the whichTableBox ( the users input )
// and converting it to an integer
whichTableString = whichTableBox.getText () ;
whichTable = Integer.parseInt ( whichTableString ) ;
// Clear status box
showStatus ( "" ) ;
// If the user clicks the showTableButton, display the appropiate
// times table up to times 10
if ( arg.equals ( "Show Table" ) ) ;
result = whichTable * times ;
timesString = Integer.toString ( times ) ;
resultString = Integer.toString ( result ) ;
resultBox.setText ( whichTableString + " times " + timesString + " is " + resultString ) ;
} // End of try block
catch ( NumberFormatException entry )
// Display error message and clear whichTableBox
showStatus ( "Error: Invalid Input - not an integer!" ) ;
whichTableBox.setText ( "" ) ;
} // End of catch block
} // End of else statement
} // End of actionPerformed method
} // End of classuse this code, please arrange your User interface correctly.
* TimesTableApplet.java
* Created on March 12, 2007, 12:08 PM
* @author cc.woon
import java.applet.* ;
import java.awt.* ;
import java.awt.event.* ;
public class TimesTableApplet extends Applet implements ActionListener
// Declare the GUI components globally
Label titleLabel, whichTableLabel ;
TextField whichTableBox ;
TextArea resultBox;
Button showTableButton, clearButton ;
// Declare integer variables for holdind the number input by the user,
// the times number, and the result number
int whichTable, times=1, result ;
// Declare variables to hold string versions of the three integer variables
// above, for placing in the TextFields
String whichTableString, timesString, resultString ;
public void init ()
// Create the Labels
titleLabel = new Label ( "Times Table" ) ;
whichTableLabel = new Label ( "Which Table?" ) ;
// Create the TextFields
whichTableBox = new TextField ( 5 ) ;
resultBox = new TextArea() ;
// Create the Buttons
showTableButton = new Button ( "Show Table" ) ;
clearButton = new Button ( "Clear" ) ;
// Add the components to the applet window
add ( titleLabel ) ;
add ( whichTableLabel ) ;
add ( whichTableBox ) ;
whichTableBox.addActionListener ( this ) ;
add ( resultBox ) ;
resultBox.setEditable ( false ) ;
add ( showTableButton ) ;
showTableButton.addActionListener ( this ) ;
add ( clearButton ) ;
clearButton.addActionListener ( this ) ;
} // End of init method
public void actionPerformed ( ActionEvent event )
// Find out which button generated the event
String arg = event.getActionCommand () ;
// If the user clicks the clear button, clear the whichTableBox and
// resultBox
if ( arg.equals ( "Clear" ) )
whichTableBox.setText ( "" ) ;
resultBox.setText ( "" ) ;
else
try
// Try extracting a string from the whichTableBox ( the users input )
// and converting it to an integer
whichTableString = whichTableBox.getText () ;
whichTable = Integer.parseInt ( whichTableString ) ;
// Clear status box
showStatus ( "" ) ;
// If the user clicks the showTableButton, display the appropiate
// times table up to times 10
if ( arg.equals ( "Show Table" ) ) ;
result = whichTable * times ;
timesString = Integer.toString ( times ) ;
String output = "";
for(int i =1;i<=10;i++){
output += whichTable +" times "+i + ": "+(i*whichTable)+"\n";
resultString = Integer.toString ( result ) ;
//resultBox.setText ( whichTableString + " times " + timesString + " is " + resultString ) ;
resultBox.setText ( output) ;
} // End of try block
catch ( NumberFormatException entry )
// Display error message and clear whichTableBox
showStatus ( "Error: Invalid Input - not an integer!" ) ;
whichTableBox.setText ( "" ) ;
} // End of catch block
} // End of else statement
} // End of actionPerformed method
} // End of class -
I need to create first, last, next, and previous buttons in my gui. I have them in there (in the code), but only one button shows up (instead of four), and it has "first" overlapped with the "previous" button. The "next" and "last" don't even show up at all.
Can some one guide me please? Can someone tell me what I am doing wrong?? Thank you in advance
Here is my maker.java which houses the navigation panel
package inventorymain;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.NumberFormat;
import javax.swing.border.*;
import java.net.*;
import java.util.StringTokenizer;
class Maker extends Inventory implements ActionListener
{//begins Class Maker
static String manufact[] = new String[10];
static double restockingFee[] = new double[10];
static int i;
static double TotalVal;
static int navItem;
private Container cp = getContentPane();
GridBagConstraints c;
GridBagConstraints cconstraint;
Border titledborder;
JPanel pan;
String labels[] = {"Product Name:", "Manufacturer:", "Product ID Number:", "Units in Stock:",
"Price Per Unit: $", "Restocking Fee: $", "Value of Product in Stock Plus Restocking Fee: $",
"Value of All Merchandise Plus Restocking Fees: $"};
int len1 = labels.length;
JLabel lbl[] = new JLabel[len1];
JTextField txtfield1[] = new JTextField[len1];
String blabels[] = {"First", "Previous", "Next", "Last"};
int blen = blabels.length;
JButton navigate[] = new JButton[blen];
JLabel lblImg;
File file;
public String FileName;
public Maker(int Item_Number, String Item_Name, double Item_Price, int Items_in_Stock, String manufact, double restockingFee)// Constructor for varibles
super(Item_Number, Item_Name, Item_Price, Items_in_Stock);
this.manufact[i] = manufact;
this.restockingFee[i] = restockingFee;
i = i + 1;
public static void setManufact(int k, String value)
manufact[k] = value;
public static double getRestockFee(int val)
return restockingFee[val];
public void ShowInventory()
setLayout(new FlowLayout());
GridBagLayout contlayout = new GridBagLayout();//layout for container
GridBagConstraints cconstraint = new GridBagConstraints();//constraint for container
GridBagLayout gblayout = new GridBagLayout();//layout for panel
GridBagConstraints gbconstraint = new GridBagConstraints();
try
//first panel
pan = new JPanel();
gblayout = new GridBagLayout();
gbconstraint = new GridBagConstraints();
pan.setLayout(gblayout);
for (int i = 0; i < 2; i++)
for (int j = 0; j < len1; j++)
int x = i;
int y = j;
if (x == 0)
lbl[j] = new JLabel(labels[j]);
lbl[j].setHorizontalAlignment(JLabel.LEFT);
lbl[j].setPreferredSize(new Dimension(250, 15));
gbconstraint.insets = new Insets(10, 0, 0, 0);
gbconstraint.gridx = x;
gbconstraint.gridy = y;
pan.add(lbl[j], gbconstraint);
}//end if
else
txtfield1[j] = new JTextField(15);
txtfield1[j].setPreferredSize(new Dimension(300, 15));
txtfield1[j].setHorizontalAlignment(JLabel.LEFT);
txtfield1[j].setEnabled(false);
lbl[j].setLabelFor(txtfield1[j]);
gbconstraint.gridx = x;
gbconstraint.gridy = y;
pan.add(txtfield1[j], gbconstraint);
}//end else
}//end for
}//end for
Border titledborder = BorderFactory.createTitledBorder("Current Inventory Data");
pan.setBorder(titledborder);
//adds panel to container
cconstraint.gridwidth = 1;
cconstraint.gridheight = 1;
cconstraint.gridx = 0;
cconstraint.gridy = 0;
cp.add(pan, cconstraint);
//add icon to display
pan = new JPanel();
gblayout = new GridBagLayout();
gbconstraint = new GridBagConstraints();
pan.setLayout(gblayout);
gbconstraint.gridwidth = 1;
gbconstraint.gridheight = 1;
gbconstraint.gridy = 0;
lblImg = new JLabel((new ImageIcon(getClass().getResource("logo111.jpg"))));
lblImg.setPreferredSize(new Dimension(120, 60));
pan.add(lblImg);
cconstraint.gridwidth = 1;
cconstraint.gridheight = 1;
cconstraint.gridx = 0;
cconstraint.gridy = 1;
cp.add(pan, cconstraint);
//navigation panel
pan = new JPanel();
gblayout = new GridBagLayout();
gbconstraint = new GridBagConstraints();
pan.setLayout(gblayout);
gbconstraint.gridwidth = 1;
gbconstraint.gridheight = 1;
gbconstraint.gridx = 0;
gbconstraint.gridy = 1;
for (int i = 0; i < blen; i++)
navigate[i] = new JButton(blabels);
gbconstraint.gridx = 1;
pan.add(navigate[i], gbconstraint);
navigate[i].addActionListener(this);
}//end for
titledborder = BorderFactory.createTitledBorder("Navigation");
pan.setBorder(titledborder);
//add panel to container
cconstraint.gridwidth = 4;
cconstraint.gridheight = 1;
cconstraint.gridx = 1;
cconstraint.gridy = 1;
cp.add(pan, cconstraint);
ShowInventory(0);
}//end try
catch (Exception e)
e.printStackTrace();
}//end catch
}//end showInventory
public void ShowInventory(int ItemNo)
txtfield1[0].setText(Integer.toString(ItemNo));
txtfield1[0].setText(Inventory.getItemName(ItemNo));
txtfield1[1].setText(manufact[ItemNo]);
txtfield1[2].setText(Integer.toString(Inventory.getItemNum(ItemNo)));
txtfield1[3].setText(Integer.toString(Inventory.getItemUnits(ItemNo)));
txtfield1[4].setText(Double.toString(Inventory.getItemPrice(ItemNo)));
txtfield1[5].setText(String.format("%3.2f",
Products.totalOfRestockFee(Inventory.getItemPrice(ItemNo),
getRestockFee(ItemNo))));
txtfield1[6].setText(String.format("%3.2f",
Products.totalOfInventory(Inventory.getItemPrice(ItemNo),
Inventory.getItemUnits(ItemNo), getRestockFee(ItemNo))));
txtfield1[7].setText(String.format("%3.2f",
GetTotalInvVal()));
}//end ShowInventory(int ItemNo)
public void EnableFields(boolean bflag)
txtfield1[1].setEnabled(bflag);
txtfield1[2].setEnabled(bflag);
txtfield1[3].setEnabled(bflag);
txtfield1[4].setEnabled(bflag);
txtfield1[5].setEnabled(bflag);
}//end EnableFields
public double GetTotalInvVal()
TotalVal = 0;
for(int j = 0; j < Inventory.getCount(); j++)
TotalVal += Products.totalOfInventory(Inventory.getItemPrice(j),
Inventory.getItemUnits(j), getRestockFee(j));
return TotalVal;
}//end GetTotalInvVal
public void actionPerformed(ActionEvent e)//button actions
String btnClicked = ((JButton)e.getSource()).getText();
if (btnClicked.equals("First"))
EnableFields(false);
navItem = 0;
ShowInventory(navItem);
}//end if
if (btnClicked.equals("Next"))
EnableFields(false);
if (navItem == getCount() - 1)
navItem = 0;
}//end if
else
navItem += 1;
}//end else
ShowInventory(navItem);
}//end if
if (btnClicked.equals("Previous"))
EnableFields(false);
if (navItem == 0)
navItem = getCount() - 1;
}//end if
else
navItem = navItem - 1;
}//end else
ShowInventory(navItem);
}//end if
if (btnClicked.equals("Last"))
EnableFields(false);
navItem = getCount() - 1;
ShowInventory(navItem);
}//end if
}//end ActionPerformed
}// end of class Makerfor (int i = 0; i < blen; i++)
navigate[i] = new JButton(blabels);
gbconstraint.gridx = 1; // ---- > You mean for this be = i, No?
// Somehow you need to be resetting the grid x for each button added
pan.add(navigate[i], gbconstraint);
navigate[i].addActionListener(this);
}//end for
Or check out gridx = GridBagConstraints.RELATIVE
Message was edited by:
nantucket -
Help with a simple GUI.
I am totally new to building GUI's. Everything I have picked up I did so online. From what I have learned this should work, but it throws all sorts of exceptions when I run it.
package com.shadowconcept.mcdougal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NavSystemGUI extends JApplet implements ActionListener
String citylist[] = {"Birmingham", "Tuscaloosa", "Atlanta", "Montgomery", "Macon", "Mobile", "Tallahassee", "Ashburn", "Lake City", "Ocala", "Orlando", "Daytona Beach", "Jacksonville", "Savannah"};
NavigationSystem N1 = new NavigationSystem();
JLabel startposition = new JLabel("Starting Position");
JLabel endposition = new JLabel("Ending Posiiton");
JLabel choice = new JLabel("Make a Choice");
JComboBox startselection = new JComboBox(citylist);
JComboBox endselection = new JComboBox(citylist);
ButtonGroup choices = new ButtonGroup();
JRadioButton DFS = new JRadioButton("Depth-First Search");
JRadioButton BFS = new JRadioButton("Breadth-First Search");
JRadioButton shortestpath = new JRadioButton("Find the Shortest Path");
JButton button = new JButton("Execute");
String Start, End;
public void init()
Container con = getContentPane();
con.setLayout(new FlowLayout());
choices.add(DFS);
DFS.setSelected(true);
choices.add(BFS);
choices.add(shortestpath);
con.add(startposition);
//startposition.setLocation(10, 20);
con.add(startselection);
//startselection.setLocation(50, 20);
startselection.addActionListener(this);
con.add(endposition);
//endposition.setLocation(10, 40);
con.add(endselection);
//endselection.setLocation(50, 40);
endselection.addActionListener(this);
con.add(choice);
//choice.setLocation(10, 60);
con.add(DFS);
DFS.addActionListener(this);
con.add(BFS);
BFS.addActionListener(this);
con.add(shortestpath);
shortestpath.addActionListener(this);
con.add(button);
button.addActionListener(this);
startselection.requestFocus();
Start = startselection.getName();
End = endselection.getName();
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button){
if(DFS.isSelected()){
N1.DFS(Start, End);
if(BFS.isSelected()){
N1.BFS(Start, End);
if(shortestpath.isSelected()){
N1.shortestpath(Start, End);
}rhm54 wrote:
I am totally new to building GUI's. Everything I have picked up I did so online. From what I have learned this should work, but it throws all sorts of exceptions when I run it.It compiles and runs fine for me. Perhaps your problems are with the NavigationSystem class? But I agree with Hunter: show your error messages and somehow indicate the lines in your code that cause the errors. I often find that reposting the code with comments indicating the offending lines works best. Good luck. -
Hey,
Just as an experiment, I'm creating a Fake instant messaging application between two computers (one is the host and one is the client). For right now I am having the host read in data from the client, and the host is supposed to display it on its screen. I know the code works, but I am having trouble finding a way to keep the communication line open between the host and the client, without the host 'stalling' and not updating constantly so that it looks like a true application. Here is the code I have:
try
while( true )
String line = input.readLine();
if( line.compareTo("close") == 0 )
break;
else if( line != null )
myGUI.msgTextArea.setText(line);
catch( Exception e )
myGUI.systemLabel.setText("Connection error");
Is there an easy way to update the the GUI without having to stop reading in data from the user? Or do I need to break communication off with the user? Any suggestions? thanks.Use the RMI with the Observer pattern. (The host could fire an event via rmi and the client could listen for the event)
-
I'm trying to activate my buttons "Calculate" and "Exit" for my Box Volume Calculator GUI I created with NetBeans. I get the error message "if without else".
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if (evt.getSource()==btnCalculate)
doCalculate();
else if (evt.getSource()==btnExit)
System.exit(0);
void doCalculate() {
double height;
double width;
double depth;
double volumeCalc;
height =Double.parseDouble(txtHeight.getText());
width =Double.parseDouble(txtWidth.getText());
depth =Double.parseDouble(txtDepth.getText());
volumeCalc =height*width*depth;
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
if (evt.getSource()==btnCalculate)
doCalculate();
else if (evt.getSource()==btnExit)
System.exit(0);
}//GEN-LAST:event_jButton2ActionPerformed
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BoxVolCalc().setVisible(true);
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}}}Where is the error generated? It's perfectly legal to have an if without an else.
As an aside, why would you even put the duplicate if/else blocks in? You have two buttons and two listeners - you'd only need an if/else if you were dumb enough to wire all your listeners to all your buttons. Bizarre. -
I am working in a psych lab and we use a STISIM drive sim to do some research. The problem is that this sim uses a weird proprietary code that scenarios must be written in. Its simple enough, but a huge time suck.
I was hoping there would be some way to develop a GUI with simple fields that could be filled out for each event, and then once all events were in place, the code exported in a simple text format.
I know very little about objective-c and xcode, but I was hoping someone could point me toward the kind of code I should be looking at to accomplish this kind of task. What functions can be used to take a bunch of single field inputs, convert them to another form, and then lump them all together in one big file?Take a look at using AppleScript and Automator.
-
Please Help - Need Help with Buttons for GUI for assignment. URGENT!!
Can someone please help me with the buttons on this program? I cannot figure out how to get them to work.
Thanks!!!
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.JButton;
public class InventoryTAH implements ActionListener
Maker[] proMaker;
JTextField[] fields;
NumberFormat nf;
public void actionPerformed(ActionEvent e)
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
public static void main(String[] args)
try
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e)
System.err.println(e.getClass().getName() + ": " + e.getMessage());
InventoryTAH test = new InventoryTAH();
test.initMakers();
test.showGUI();
test.populateFields(0);
private void initMakers() {
proMaker = new Maker[10];
proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");
int maxNum = 10;
int currentNum = 0;
int currentInv = 0;
Action firstAction = new AbstractAction("First")
public void actionPerformed(ActionEvent evt)
currentInv = 0;
int populateFields;
JButton firstButton = new JButton(firstAction);
Action previousAction = new AbstractAction("Previous")
public void actionPerformed(ActionEvent evt)
currentInv--;
if (currentInv < 0)
currentInv = maxNum - 1;
int populateFields;
JButton previousButton = new JButton(previousAction);
Action nextAction = new AbstractAction("Next")
public void actionPerformed(ActionEvent evt)
currentInv++;
if (currentInv >= currentNum)
currentInv = 0;
int populateFields;
JButton nextButton = new JButton(nextAction);
Action lastAction = new AbstractAction("Last")
public void actionPerformed(ActionEvent evt)
currentInv = currentNum - 1;
int populateFields;
JButton lastButton = new JButton(lastAction);
JPanel buttonPanel = new JPanel( );
private void showGUI() {
JLabel l;
JButton button1;
JButton button2;
fields = new JTextField[8];
JFrame f = new JFrame("Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('h');
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c);
fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c);
fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c);
fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c);
fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c);
fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c);
fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c);
fields[7].setFocusAccelerator('h');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(firstButton);
cp.add(previousButton);
cp.add(nextButton);
cp.add(lastButton);
JComboBox combo = new JComboBox();
for(int j = 0; j < proMaker.length; j++)
combo.addItem(proMaker[j].getName());
combo.addActionListener(this);
cp.add(combo);
cp.add(button1 = new JButton(" "), c);
f.pack();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent evt)
System.exit(0);
f.setVisible(true);
private void populateFields(int index) {
Maker maker = proMaker[index];
fields[0].setText(Long.toString(maker.getNumberCode()));
fields[1].setText(maker.getName());
fields[2].setText(Long.toString(maker.getUnits()));
fields[3].setText(Double.toString(maker.getPrice()));
fields[4].setText(Double.toString(maker.getSum()));
fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
fields[6].setText(maker.getManufact());
fields[7].setText(Double.toString(maker.getSum()*.05));
class Maker {
int itemNumber;
String name;
int units;
double price;
String manufacturer;
public Maker(int n, String name, double price, int units, String manufac) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
manufacturer = manufac;
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getManufact() { return manufacturer; }
public double totalAllInventory(Maker[] makers) {
double total = 0;
for(int j = 0; j < makers.length; j++)
total += makers[j].getSum();
return total;
}}// I have made some modifications. Please try this.
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.JButton;
public class InventoryTAH implements ActionListener
Maker[] proMaker;
JTextField[] fields;
NumberFormat nf;
int currentInv = 0;
public void actionPerformed(ActionEvent e)
currentInv= ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(currentInv);
public static void main(String[] args)
try
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e)
System.err.println(e.getClass().getName() + ": " + e.getMessage());
InventoryTAH test = new InventoryTAH();
test.initMakers();
test.showGUI();
test.populateFields(0);
private void initMakers() {
proMaker = new Maker[10];
proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");
int maxNum = 10;
int currentNum = 0;
Action firstAction = new AbstractAction("First")
public void actionPerformed(ActionEvent evt)
currentInv = 0;
populateFields(currentInv);
JButton firstButton = new JButton(firstAction);
Action previousAction = new AbstractAction("Previous")
public void actionPerformed(ActionEvent evt)
currentInv--;
if (currentInv < 0)
currentInv = maxNum - 1;
populateFields(currentInv);
JButton previousButton = new JButton(previousAction);
Action nextAction = new AbstractAction("Next")
public void actionPerformed(ActionEvent evt)
currentInv++;
if (currentInv >= maxNum)
currentInv = 0;
populateFields(currentInv);
JButton nextButton = new JButton(nextAction);
Action lastAction = new AbstractAction("Last")
public void actionPerformed(ActionEvent evt)
currentInv = maxNum-1;
populateFields(currentInv);
JButton lastButton = new JButton(lastAction);
JPanel buttonPanel = new JPanel( );
private void showGUI() {
JLabel l;
JButton button1;
JButton button2;
fields = new JTextField[8];
JFrame f = new JFrame("Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('h');
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c);
fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c);
fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c);
fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c);
fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c);
fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c);
fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c);
fields[7].setFocusAccelerator('h');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(firstButton);
cp.add(previousButton);
cp.add(nextButton);
cp.add(lastButton);
JComboBox combo = new JComboBox();
for(int j = 0; j < proMaker.length; j++)
combo.addItem(proMaker[j].getName());
combo.addActionListener(this);
cp.add(combo);
cp.add(button1 = new JButton(" "), c);
f.pack();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent evt)
System.exit(0);
f.setVisible(true);
private void populateFields(int index) {
Maker maker = proMaker[index];
fields[0].setText(Long.toString(maker.getNumberCode()));
fields[1].setText(maker.getName());
fields[2].setText(Long.toString(maker.getUnits()));
fields[3].setText(Double.toString(maker.getPrice()));
fields[4].setText(Double.toString(maker.getSum()));
fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
fields[6].setText(maker.getManufact());
fields[7].setText(Double.toString(maker.getSum()*.05));
class Maker {
int itemNumber;
String name;
int units;
double price;
String manufacturer;
public Maker(int n, String name, double price, int units, String manufac) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
manufacturer = manufac;
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getManufact() { return manufacturer; }
public double totalAllInventory(Maker[] makers) {
double total = 0;
for(int j = 0; j < makers.length; j++)
total += makers[j].getSum();
return total;
}} -
Help with implementing Swing GUI within jpg image
Dear Java Experts,
I have a question, is there a way to implement java swing objects (ie jbutton, jcombobox, etc) within an imageicon. Basically, i am trying to juggle between ways of getting JSwing GUI into a background jpg image. Please help me. I thank you all in advance.You've it back to front.
Create an transparent extension of JPanel that paints an image on it's
background before running it's super class paint method.
You'll need to extend this example to stretch, center or tile the image
but otheriwse it's complete.
BTW - you have to pass an argument to this example that is the path of
the image you want on the background of the panel, like:
java -cp <whatever> MyJavaProject1 images/something.gif
Enjoy.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class MyJavaProject1
static class BackgroundPanel
extends JPanel
private ImageIcon mIcon;
public BackgroundPanel(ImageIcon icon) {
mIcon= icon;
super.setOpaque(false);
public void setOpaque(boolean flag) { }
public void paint(Graphics g)
g.drawImage(mIcon.getImage(), 0, 0, null);
super.paint(g);
public static void main(String[] argv)
JFrame frame= new JFrame(argv[0]);
BackgroundPanel panel= new BackgroundPanel(new ImageIcon(argv[0]));
panel.setLayout(new GridLayout(0,2,4,4));
panel.setBorder(new EmptyBorder(4,4,4,4));
panel.add(new JLabel("Name"));
panel.add(new JTextField());
panel.add(new JLabel("Address"));
panel.add(new JTextField());
panel.add(new JLabel("Phone"));
panel.add(new JTextField());
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
} -
Hi guys, i have a project to do and Ive chosen hangman. Ive already made the main program , but i need help with the GUI. I havent been taught about GUI in school, so all i know is what i could understand from a book and what ive read on the internet..
First , heres the code of my basic Hangman class:
import java.io.*;
import java.util.Random;
public class Hangman
public void maingame()throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String movies[]={"THE BOURNE ULTIMATUM","TRANSFORMERS","RUSH HOUR 3","THE INSIDE MAN","THE SIMPSONS MOVIE","THE LORD OF THE RINGS","DIE HARD 4.0"};
Random rand = new Random();
char current[]=(movies[rand.nextInt(movies.length)]).toCharArray(); //Convert a random string from movies array into a char array
char actual[]=new char[current.length]; //Store current state of guessed movie
for (int i=0;i<actual.length;i++)
if (isVowel(Character.toUpperCase(current))==true)
actual[i]=current[i];
else if (isSpecialChar(Character.toUpperCase(current[i]))==true)
actual[i]=current[i];
else if (current[i]==' ')
actual[i]='/';
else
actual[i]='_';
String hangman = "HANGMAN";
int turnsleft=7;
StringBuffer guessed=new StringBuffer();
while (turnsleft!=0)
System.out.println("\n\t\t\t\t"+hangman.substring(0,turnsleft)+"\n");
print(actual);
System.out.println("\nEnter your guess");
String inp = br.readLine();
if (inp.length()>1)
System.out.println("You may only enter one character");
else
char guess = inp.charAt(0); //Convert the entered string to char
if ( (hasBeenGuessed(guess,guessed)) == true )
System.out.println("You have already guessed that\nYou have "+turnsleft+" turns left");
else if (guess >= '0' && guess <= '9')
System.out.println("You cannot guess digits.All digits in a movie will will be filled in automatically");
else
guessed.append(guess);
if (isVowel(guess)!=true)
if (isCorrect(guess,turnsleft,current,actual)==true)
if (hasWon(actual,current)==true)
System.out.println();
print(actual);
System.out.println("\nCongratulations!You won!");
System.exit(0);
else
System.out.println("\nCorrect Guess!\nYou have "+turnsleft+" turns left\n");
else
turnsleft--;
System.out.println("Wrong Guess!\nYou have "+turnsleft+" turns left\n");
else if (isVowel(guess)==true)
System.out.println("You cannot guess vowels\nYou have "+turnsleft+" turns left\n");
else
System.out.println("You have already guessed that\nYou have "+turnsleft+" turns left\n");
print(actual);
if (turnsleft==0)
System.out.println("\nYou lose!\nThe movie was: ");
print(current);
System.exit(0);
private boolean isCorrect(char guess,int turnsleft,char current[],char actual[])
int flag=0;
for (int i=0;i<current.length;i++)
if ( Character.toUpperCase(current[i])==Character.toUpperCase(guess) && actual[i]!=guess ) //Check if guess is correct, and make sure it has not already been entered
actual[i]=guess;
flag=1;
else if (Character.toUpperCase(current[i])!=Character.toUpperCase(guess) && i==current.length-1 && flag==0)
return false;
if (flag!=0)
return true;
else
return false;
private boolean hasWon(char actual[],char current[])
char actualspc[]=new char[actual.length];
for (int i=0;i<actual.length;i++)
if (actual[i]=='/')
actualspc[i]=' ';
else
actualspc[i]=actual[i];
for (int i=0;i<actual.length;i++)
if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i==actual.length-1)
return true;
else if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i!=actual.length-1)
continue;
else
return false;
return false;
private void print(char arr[])
for (int i=0;i<arr.length;i++)
System.out.print(Character.toUpperCase(arr[i])+" ");
private boolean isVowel(char a)
if (a=='a' || a=='A' || a=='e' || a=='E' || a=='i' || a=='I' || a=='o' || a=='O' || a=='u' || a=='U')
return true;
else
return false;
private boolean isSpecialChar(char a)
//if (a>='a' && a<='z')
//return false;
//else if (a>='A' && a<='z')
//return false;
//else if (a==' ')
//return false;
//else if (a>='0' && a<='9')
//return true;
if (isLetter(a)==true)
return false;
else if (isWhiteSpace(a)==true)
return false;
else if (isDigit(a)==true)
return true;
else
return true;
private boolean hasBeenGuessed(char a,StringBuffer guessed)
for (int i=0;i<guessed.length();i++)
if ( Character.toUpperCase(guessed.charAt(i)) == Character.toUpperCase(a))
return true;
return false;
My first 2 questions are here:
a - Why does isLetter not work, it says cannot resolve symbol - method isLetter(char)... Im guessing even isDigit and isWhiteSpace wont work, so why? If i cant use them ill have to use the commented code, its kind of unprofessional..
b- Isnt there any way i can compare chars ignoring cases besides converting both to one case, like im doing now?
Heres the new HangmanGUI class i made, it doesnt necessarily have to be a different class in the final outcome, but i would prefer it if it can.. Ive made what i can figure out.. Ive commented about what i need to do.
Keep in mind i cant use Applets, only Frame/JFrame
import java.awt.*;
import javax.swing.*;
public class HangmanGUI extends JFrame implements ActionListener
Button newGame = new Button("New Game");
Button entGuess = new Button("Submit Guess");
Button giveUp = new Button("Give Up");
TextField input = new TextField("",1);
Label hangman = new Label("HANGMAN");
JPanel play = new JPanel();
JPanel hang = new Jpanel();
GridLayout playLayout = new GridLayout(2,4);
public HangmanGUI()
play.setLayout(playLayout);
play.add(hangman+"\n");
play.add(newGame);
play.add(giveUp);
play.add(input);
play.add(entGuess);
hang.add(hangman);
getContentPane().add(play);
getContentPane().add(hang);
public void ActionPerformed(ActionEvent act)
Object src = act.getSource();
if (src==newGame)
main(); //Calling main to restart program - will that work?
//if (src==entGuess)
//Need to submit the guess, while input is not empty to Hangman class
//if (src==giveUp)
//Need to go into the losing part of Hangman class
}As you can see i need help with:
a - How to complete the other ifs
b - How to really use the data of my Hangman class in this class and combine the GUI and backend to make a nice GUI Hangman app
c - btw, right now if i try to compile HangmanGUI it highlights the implements ActionListener line and says cannot resolve symbol - class ActionListener..
Any help would be greatly appreciatedThanks for the explanation pete...
Anyways, i started implementing my code within abillconsl's code, and im trying to assign a label to a char array using .toString(); but instead of whats in the char array i get [C@<numbers and digits> ..
Whats wrong?
[code]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class HangEmHighGUI extends JFrame implements ActionListener
private Button newGame,
entGuess,
giveUp;
private TextField input;
private Label hangman,
movie;
private JPanel play,
hang;
private GridLayout playLayout;
private FlowLayout labelLayout;
private Container container; // To avoid extra meth calls
String movies[]={"THE/BOURNE/ULTIMATUM","TRANSFORMERS","RUSH HOUR 3","THE INSIDE MAN","THE SIMPSONS MOVIE","THE LORD OF THE RINGS","DIE HARD 4.0"};
Random rand = new Random();
char current[]=(movies[rand.nextInt(movies.length)]).toCharArray(); //Convert a random string from movies array into a char array
char actual[]=new char[current.length]; //Store current state of guessed movie
public HangEmHighGUI()
setUp();
container = this.getContentPane();
play = new JPanel();
hang = new JPanel();
playLayout = new GridLayout(1, 3, 5, 5); // rows, cols, space, space
labelLayout = new FlowLayout(FlowLayout.CENTER);
newGame = new Button("New Game");
entGuess = new Button("Submit Guess");
giveUp = new Button("Give Up");
input = new TextField("",1);
hangman = new Label("HANGMAN");
movie = new Label(actual.toString());
hang.setLayout(labelLayout);
play.setLayout(playLayout);
play.add(newGame);
play.add(giveUp);
play.add(entGuess);
hang.add(hangman);
hang.add(movie);
container.add(hang,BorderLayout.NORTH);
container.add(input,BorderLayout.CENTER);
container.add(play,BorderLayout.SOUTH);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent act)
Object src = act.getSource();
if (src==newGame)
main(new String[] {""}); //Calling main to restart program, this does not work without parameters, is there some other way to restart?
if (src==entGuess)
if (input.getText()=="")
setUp();
//if (src==giveUp)
//Need to go into the losing part of Hangman class
public static void main(String args[])
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HangEmHighGUI();
private void setUp()
for (int i=0;i<actual.length;i++)
if (isVowel(Character.toUpperCase(current)))
actual[i]=current[i];
else if (isSpecialChar(Character.toUpperCase(current[i])))
actual[i]=current[i];
else if (Character.isWhitespace(current[i]))
actual[i]='/';
else
actual[i]='_';
private boolean isVowel(char a)
if (Character.toUpperCase(a)=='A' || Character.toUpperCase(a)=='E' || Character.toUpperCase(a)=='I' || Character.toUpperCase(a)=='O' || Character.toUpperCase(a)=='U')
return true;
else
return false;
private boolean isSpecialChar(char a)
if (Character.isLetter(a))
return false;
else if (Character.isDigit(a))
return true;
else if (Character.isWhitespace(a))
return false;
else
return true;
private boolean isCorrect(char guess,int turnsleft,char current[],char actual[])
int flag=0;
for (int i=0;i<current.length;i++)
if ( Character.toUpperCase(current[i])==Character.toUpperCase(guess) && actual[i]!=guess ) //Check if guess is correct, and make sure it has not already been entered
actual[i]=guess;
flag=1;
else if (Character.toUpperCase(current[i])!=Character.toUpperCase(guess) && i==current.length-1 && flag==0)
return false;
if (flag!=0)
return true;
else
return false;
private boolean hasWon(char actual[],char current[])
char actualspc[]=new char[actual.length];
for (int i=0;i<actual.length;i++)
if (actual[i]=='/')
actualspc[i]=' ';
else
actualspc[i]=actual[i];
for (int i=0;i<actual.length;i++)
if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i==actual.length-1)
return true;
else if ((Character.toUpperCase(current[i]))==(Character.toUpperCase(actualspc[i])) && i!=actual.length-1)
continue;
else
return false;
return false;
private void print(char arr[])
for (int i=0;i<arr.length;i++)
System.out.print(Character.toUpperCase(arr[i])+" ");
private boolean hasBeenGuessed(char a,StringBuffer guessed)
for (int i=0;i<guessed.length();i++)
if ( Character.toUpperCase(guessed.charAt(i)) == Character.toUpperCase(a))
return true;
return false;
Note that the majority of the code has been taken from my old hangman class, i havent adapted it to the GUI yet, so ignore all of that stuff. -
I need help with JcomboBox when I select the Exit in the File box it will open
//inner class
class exitListener implements ActionListener {
I have the part of the parts of statement but I don't know how to assign the Keystoke. here is that part of the code
filemenu.setMnemonic(KeyEvent.VK_X);Here is my code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame {
String[] file = { "New", "Open", "Exit" };//items for file
String[] edit = { "Cut", "Copy", "Paste" };//items for edit
JComboBox filemenu = new JComboBox();
JComboBox editmenu = new JComboBox();
public MyFrame(String title) {
super(title);
this.setSize(250, 250); //sets the size for the frame
this.setLocation(200, 200);//location where frame is at
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setup contents
makeComponents();
initComponents();
buildGUI();
// display
this.setVisible(true);
private void makeComponents() {
JPanel pane = new JPanel();
// file menu section
filemenu = new JComboBox();
JLabel fileLabel = new JLabel();
pane.add(fileLabel);
for (int i = 0; i < file.length; i++)
filemenu.addItem(file);
pane.add(filemenu);
add(pane);
setVisible(true);
//edit menu section
editmenu = new JComboBox();
JLabel editLabel = new JLabel();
pane.add(editLabel);
for (int i = 0; i < edit.length; i++)
editmenu.addItem(edit[i]);
pane.add(editmenu);
add(pane);
setVisible(true);
private void initComponents() {
filemenu.addActionListener(new exitListener());
//inner class
class exitListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
int x = JOptionPane.showOptionDialog(MyFrame.this, "Exit Program?",
"Exit Request", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null,
JOptionPane.NO_OPTION);
if (x == JOptionPane.YES_OPTION) {
MyFrame.this.dispose();
private void buildGUI() {
Container cont = this.getContentPane();// set gui components into the frame
this.setLayout(new FlowLayout(FlowLayout.LEFT));// Comp are added to the frame
cont.add(filemenu);
cont.add(editmenu);
// / inner classes
public class ButtonFrame {
public static void main(String[] args) {
MyFrame f1 = new MyFrame("This is my Project for GUI");
Thanks
SandyR.One way is to
1) pass a reference of the Window object to the USDListener class, and set a local Window variable say call it window, to this reference.
2) Give the Window class a public method that returns a String and allows you to get the text from USDField. Same to allow you to set text on the euroField.
3) Give the Listener class a Converter object. -
Help with getting a better understanding on how APEX submits its pages
Hi,
I have implemented jquery with my app and have just applied the jquery UI plugins.
I have the jquery UI dialog function working which gives the users some options. Now as an example, I have a cancel and a continue button. If the user clicks cancel it simply stops the page from submitting. Which works perfectly however, I cannot get the continue button to carry on with the request.
I gather that I will need to determine what the href was of the link/button that was clicked before the dialog box appears.
I know Apex uses a javascript function call doSumit() which simply submits the page but what does it use for other href like links to other pages?The problem is that you're taking a camcorder format that Premiere Elements is able to work with and converting it to a format that it can NOT work with.
That Canon camcorder produces AVCHD video. You should shoot any video you want to edit in Premiere Elements only in MXP or FXP mode. Then, when you're ready to edit the video in Premiere Elements, you should set up a project for AVCHD 1920x1080 stereo. (Unless you're shooting in 5.1 audio. This cam shoots in a number of formats.)
DO NOT CONVERT YOUR VIDEO BEFORE YOU PUT IT IN PREMIERE ELEMENTS.
You can then use these specs to output high-quality video for YouTube.
http://forums.adobe.com/thread/623549?tstart=0
If you need some basic help with the program, be sure to check out my free 8-part Basic Training tutorial series at Premiere Elements support site Muvipix.com.
http://forums.adobe.com/thread/537685?tstart=0 -
Help with encapsulation and a specific case of design
Hello all. I have been playing with Java (my first real language and first OOP language) for a couple months now. Right now I am trying to write my first real application, but I want to design it right and I am smashing my head against the wall with my data structure, specifically with encapsulation.
I go into detail about my app below, but it gets long so for those who don't want to read that far, let me just put these two questions up front:
1) How do principles of encapsulation change when members are complex objects rather than primitives? If the member objects themselves have only primitive members and show good encapsulation, does it make sense to pass a reference to them? Or does good encapsulation demand that I deep-clone all the way to the bottom of my data structure and pass only cloned objects through my top level accessors? Does the analysis change when the structure gets three or four levels deep? Don't DOM structures built of walkable nodes violate basic principles of encapsulation?
2) "Encapsulation" is sometimes used to mean no public members, othertimes to mean no public members AND no setter methods. The reasons for the first are obvious, but why go to the extreme of the latter? More importantly HOW do you go to the extreme of the latter? Would an "updatePrices" method that updates encapsulated member prices based on calculations, taking a single argument of say the time of year be considered a "setter" method that violates the stricter vision of encapsulation?
Even help with just those two questions would be great. For the masochistic, on to my app... The present code is at
http://www.immortalcoil.org/drake/Code.zip
The most basic form of the application is statistics driven flash card software for Japanese Kanji (Chinese characters). For those who do not know, these are ideographic characters that represent concepts rather than sounds. There are a few thousand. In abstract terms, my data structure needs to represent the following.
- There are a bunch of kanji.
Each kanji is defined by:
- a single character (the kanji itself); and
- multiple readings which fall into two categories of "on" and "kun".
Each reading is defined by:
- A string of hiragana or katakana (Japanese phoenetic characters); and
- Statistics that I keep to represent knowledge of that reading/kanji pair.Ideally the structure should be extensible. Later I might want to add statistics associated with the character itself rather than individual readings, for example. Right now I am thinking of building a data structure like so:
- A Vector that holds:
- custom KanjiEntry objects that each hold
- a kanji in a primitive char value; and
- two (on, kun) arrays or Vectors of custom Reading objects that hold
- the reading in a String; and
- statistics of some sort, probably in primitive valuesFirst of all, is this approach sensible in the rough outlines?
Now, I need to be able to do the obvious things... save to and load from file, generate tables and views, and edit values. The quesiton of editting values raises the questions I identified above as (1) and (2). Say I want to pull up a reading, quiz the user on it, and update its statistics based on whether the user got it right or wrong. I could do all this through the KanjiEntry object with a setter method that takes a zillion arguments like:
theKanjiEntry.setStatistic(
"on", // which set of readings
2, // which element in that array or Vector
"score", // which statistic
98); // the valueOr I could pass a clone of the Reading object out, work with that, then tell the KanjiEntry to replace the original with my modified clone.
My instincts balk at the first approach, and a little at the second. Doesn't it make more sense to work with a reference to the Reading object? Or is that bad encapsulation?
A second point. When running flash cards, I do not care about the subtlties of the structure, like whether a reading is an on or a kun (although this is important when browsing a table representing the entire structure). All I really care about is kanij/reading pairings. And I should be able to quickly poll the Reading objects to see which ones need quizzing the most, based on their statistics. I was thinking of making a nice neat Hashtable with the keys being the kanji characters in Strings (not the KanjiEntry objects) and the values being the Reading objects. The result would be two indeces to the Reading objects... the basic structure and my ad hoc hashtable for runninq quizzes. Then I would just make sure that they stay in sync in terms of the higher level structure (like if a whole new KanjiEntry got added). Is this bad form, or even downright dangerous?
Apart from good form, the other consideration bouncing around in my head is that if I get all crazy with deep cloning and filling the bottom level guys with instance methods then this puppy is going to get bloated or lag when there are several thousand kanji in memory at once.
Any help would be appreciated.
DrakeUsually by better design. Move methods that use the
getters inside the class that actually has the data....
As a basic rule of thumb:
The one who has the data is the one using it. If
another class needs that data, wonder what for and
consider moving that operation away from that class.
Or move from pull to push: instead of A getting
something from B, have B give it to A as a method
call argument.Thanks for the response. I think I see what you are saying.. in my case it is something like this.
Solution 1 (disfavored):
public class kanjiDrill{ // a chunk of Swing GUI or something
public void runDrill(Vector kanjiEntries){
KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
char theKanji = currentKanjiEntry.getKanji();
String theReading = currentKanjiEntry.getReading();
// build and show a flashcard based on theKanji and theReading
// use a setter to change currentKanji's data based on whether the user answers correctly;
}Solution 2 (favored):
public class kanjiDrill{ // a chunk of Swing GUI or something
public void runDrill(Vector kanjiEntries){
KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
currentKanji.buildAndShowFlashcard(); // method includes updating stats
}I can definitely see the advantages to this, but two potential reasons to think hard about it occur to me right away. First, if this process is carried out to a sufficient extreme the objects that hold my data end up sucking in all the functionality of my program and my objects stop resembling natural concepts.
In your shopping example, say you want to generate price tags for the items. The price tags can be generated with ONLY the raw price, because we do not want the VAT on them. They are simple GIF graphics that have the price printed on a an irregular polygon. Should all that graphics generating code really go into the item objects, or should we just get the price out of the object with a simple getter method and then make the tags?
My second concern is that the more instance methods I put into my bottom level data objects the bigger they get, and I intend to have thousands of these things in memory. Is there a balance to strike at some point?
It's not really a setter. Outsiders are not setting
the items price - it's rather updating its own price
given an argument. This is exactly how it should be,
see my above point. A breach of encapsulation would
be: another object gets the item price, re-calculates
it using a date it knows, and sets the price again.
You can see yourself that pushing the date into the
item's method is much beter than breaching
encapsulation and getting and setting the price.So the point is not "don't allow access to the members" (which after all you are still doing, albeit less directly) so much as "make sure that any functionality implicated in working with the members is handled within the object," right? Take your shopping example. Say we live in a country where there is no VAT and the app will never be used internationally. Then we would resort to a simple setter/getter scheme, right? Or is the answer that if the object really is pure data are almost so, then it should be turned into a standard java.util collection instead of a custom class?
Thanks for the help.
Drake -
New Mac user looking for help with Finder, Preview, Keyboard, & Dock
So about a month ago I switched over from a lifelong Windows user to a brand new MacBook Pro, and while I am adjusting pretty well, there are still some things that I haven't quite figured out.
First up on the list is Finder! I like my files to be arranged just like how they are in Windows Explorer--folders first alphabetically, then files alphabetically. I've managed to acquire this setting by messing around with the "clean up by" and "arrange by" functions but I don't really know the specific combination. Most of the time these preferences are saved and set as the defaults under "View Options" but every once in a while it resets and I have to tinker around with the settings all over again. Does anyone know of a way to fix this? It's only happened twice so far, but I'd rather not have it happen again. Also, occasionally when I delete an item, there is a blank space left where the icon was instead of all the files following it bumping up a space. Any quick fixes for this bug?
Next up is Preview. Again, I like the Windows Way and I like to be able to browse between the files in a folder while using Preview/Windows Photo Viewer. I know that there is a way to browse between files if you select the whole folder and stick it in Preview, but is there a way to achieve the same result without having to do that? An app or "extension" of some sort that adds arrows in to browse between photos? I've had no luck finding anything other than the aforementioned option. Is there a good free alternative to Preview that will function similarly with the browse between photos option?
One of my favorite things about my new Mac is the backlit keyboard function. My old laptop didn't have it and as someone who is online more often at night it is super helpful. But is there a way to turn it off during the day/in bright settings? A way to put it on a timer? In System Preferences I selected the option "Adjust keyboard brightness in low light", which I assumed to mean would have the keyboard NOT very bright when there IS light, but it continues to light up just the same. Any apps or extensions to help with this one?
And finally, the dock! This question is more about aesthetics than functionality but help is appreciated all the same. Currently, my dock looks like this: http://i42.tinypic.com/35ktxlz.png It is rather opaque and the indicator lights can barely be seen. However, in a lot of tutorial videos I've been watching, many people have docks that look like this: http://i.i.cbsi.com/cnwk.1d/i/tim/2011/07/19/Lion_LaunchPad.png It is a darker shade of gray, the divider is dashed rather than a straight line, and the indicator lights are clearly visible. Does anybody know how to get this look for the dock? I've looked in the dock preferences but there's not really anything in there other than magnification/size/effects.
That about sums things up! I'm sorry if any of these seem like "silly" questions but they are all things I have been unable to find answers for. Any and all tips, tricks, and help is appreciated! Thanks in advance for all your help!!congratulations on coming over from the dark side.
Seems like you are interested in column view, which would show you the hierarchy of folders and files: Column View in Mac OS X Mountain Lion - For Dummies Not sure what's going on if your finder settings don't stay put. May be a corrupted preferences file, which is easy to fix, but is perhaps a topic for another discussion.
What I'd suggest is to have an open mind and try to see what the mac can do, rather than force it to look like your windows machine. I mean, if you just want it to look like windows, then why bother switching? If you give it a little time, you'll start to appreciate the mac way of doing things, and see how it is infinitely more awesome, powerful, creative, intuitive, and better designed (and the software way better written) than what you left behind. But that's your call.
There are some threads on this forum with complaints about the backlight. Keyboard backlight settings query...: Apple Support Communities Evidently it depends on the angle of the screen and the light sensor relative to the light. Some suggest that a SMC reset may help: Intel-based Macs: Resetting the System Management Controller (SMC) This is not an issue for me, I just adjust the brightness with the keyboard buttons if I want. Real men shift their own gears, drink their coffee black, and adjust their own keyboard brightness. I am not aware of any software to exert more control over this feature but a search of macupdate Download Apple Mac Software & iPhone Software : MacUpdate may help. I mean, it's up to you what is important. I can waste a lot of time playing around with the GUI and with unnecessary software, or I can just get my work (and play) done.
You might prefer the no-glass dock, that removes the shelf, and makes the indicator lights like more discrete orbs. You can do this with the terminal. Using the terminal is also, perhaps, a topic for another discussion.I like the 2D dock much better. If you want I'll give you some directions for how to do it. Otherwise, here's a reference: 2D Dock - MacRumors Forums -
Need some help with threads...
Hello all,
I am working on a project at work, and I am not the best programmer in the world. I have been trying to get my head around this for a couple of days and just cannot get it to work.
I am writing an instrumentation control program that will have three threads. One is the GUI, one will receive control information and set up the hardware, and one will check the hardware status and report it to the GUI periodically. I plan on using the invokeLater() method to communicate the status to the GUI and change the status display in the GUI. Communication from the GUI to the controller thread and from the status thread to the controller thread I had planned on being piped input/output stream as appropriate. I have a control class and a status class that need to be communicated over these piped streams. In some trial code I have been unable to wrap the piped input/output streams with object input/output streams. I really need some help with this. Here is the main thread code:
package playingwiththreads1;
import java.io.*;*
*public class PlayingWithThreads1 {*
public static void main(String[] args) {*
* PipedOutputStream outputPipe = new PipedOutputStream();*
* ObjectOutputStream oos = null;*
* ReceiverThread rt = new ReceiverThread(outputPipe);*
// Start the thread -- First try*
* Thread t = new Thread(rt);*
t.start();*
// Wrap the output pipe with an ObjectOutputStream*
try*
oos = new ObjectOutputStream(outputPipe);*
catch (IOException e)*
System.out.println(e);*
// Start the thread -- Second try*
//Thread t = new Thread(rt);*
//t.start();*
/** Send an object over the pipe. In reality this object will be a
class that contains control or status information */
try
if (!oos.equals(null))
oos.writeObject(new String ("Test"));
catch (IOException e)
try
Thread.sleep(5000);
catch (InterruptedException e)
I read somewhere that it matters where you start the thread relative to where you wrap piped streams with the object streams. So, I tried the two places I felt were obvious to start the thread. These are noted in the comments. Here is the code for the thread.
package playingwiththreads1;
import java.io.*;
public class ReceiverThread implements Runnable {
private PipedInputStream inputPipe = new PipedInputStream();
private ObjectInputStream inputObject;
ReceiverThread (PipedOutputStream outputPipe)
System.out.println("Thread initialization - start");
try
inputPipe.connect(outputPipe);
inputObject = new ObjectInputStream(inputPipe);
catch (IOException e)
System.out.println(e);
System.out.println("Thread initialization - complete");
public void run()
System.out.println("Thread started");
try
if (inputObject.available() > 0)
System.out.println(inputObject.read());
catch (IOException e)
System.out.println(e);
Through testing I have determined that no matter where I start the thread, the thread never gets past the "inputObject = new ObjectInputStream(inputPipe);" assignment.
Could someone please help me with this? There are other ways for me to write this program, but this is the one that I would like to make work.
Many thanks in advance,
Rob Hix
Edited by: RobertHix on Oct 6, 2009 3:54 AMThanks for the help, but that did not work. I tried flushing the ObjectOutputStream and it is still hanging when initializing the thread.
Here is a better look at the code since I was helped to figure out how to insert it:
The main method:
package playingwiththreads1;
import java.io.*;
public class PlayingWithThreads1 {
public static void main(String[] args) {
PipedOutputStream outputPipe = new PipedOutputStream();
ObjectOutputStream oos = null;
ReceiverThread rt = new ReceiverThread(outputPipe);
// Start the thread -- First try
//Thread t = new Thread(rt);
//t.start();
// Wrap the output pipe with an ObjectOutputStream
try
oos = new ObjectOutputStream(outputPipe);
oos.flush();
catch (IOException e)
System.out.println(e);
// Start the thread -- Second try
Thread t = new Thread(rt);
t.start();
/* Send an object over the pipe. In reality this object will be a
* class that contains control or status information */
try
if (!oos.equals(null))
oos.writeObject(new String ("Test"));
oos.flush();
catch (IOException e)
System.out.pringln(e);
try
Thread.sleep(5000);
catch (InterruptedException e)
}The thread code:
package playingwiththreads1;
import java.io.*;
public class ReceiverThread implements Runnable {
private PipedInputStream inputPipe = new PipedInputStream();
private ObjectInputStream inputObject;
ReceiverThread (PipedOutputStream outputPipe)
System.out.println("Thread initialization - start");
try
inputPipe.connect(outputPipe);
inputObject = new ObjectInputStream(inputPipe);
catch (IOException e)
System.out.println(e);
System.out.println("Thread initialization - complete");
public void run()
System.out.println("Thread started");
try
if (inputObject.available() > 0)
System.out.println(inputObject.read());
catch (IOException e)
System.out.println(e);
}Does anyone else have and ideas?
Maybe you are looking for
-
How can I get the Menu Bar in P/S Ele. 9 to show in the organizer?
The Menu bar IS in Edit. Problem occured when I updated from XP to new computer w/ Windows 7. There is a small rectangle where the menu bar usually is. I can click on it and the menu bar opens vertically. The rectangle can not be seen unless you
-
Web Based Messageboard (JSP, XML, XSLT) - Just Looking For Advice Please!
I have a general question - I am not looking for any code, just some advice if possible. I am studying on a Masters course and I have been given an assignment to do which I am having difficult getting started. I have worked a lot with Java up until n
-
Images off colour and overexposed when printing
Hi folks I'm new to the site. I have been using adobe software for a good few years at this point, and i have been trying to solve a problem with my friends Photoshop and illustrator. every time she prints out work, its all off colour and over expose
-
I bought 2 different versions of an album and i only want one. How do i get a refund?
I Got a clean and dirty version of d12 world and i want the dirty version of it. How do i get a refund?
-
Does af:tree set iterator as table with taleSelectOne in facet selection
Is it a way the selected node in a af:tree set the corresponding iterators automatically when a user click on the node ? If yes, are all iterators automatically setted corresponding to each branch level ?