How to run Java Applet program from windows cmd? - java

I have a Java program below which should ask the user to input a number in the applet window and process further on the basis of given. But the problem is that i am not able to run this java code through cmd
i know my main method is empty but i dont know what to put in it?
CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Table extends Applet {
private Label msg;
TextField number;
public void init()
{
setLayout(new FlowLayout());
Label heading = new Label("Multiplication Table");
number = new TextField(10);
Button button = new Button(" Press ");
msg = new Label("");
add(heading);
add(number);
add(button);
add(msg);
button.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str=" ";
int n = Integer.parseInt(number.getText());
if(n%2==0 && n>=11 && n<=90)
{
for(int i=1;i<=10;i++){
str = str+ n*i+" ";
}
}
else {
str = "Try Again! Number must be even and between 11-90";
}
msg.setText(str);
}
}
public static void main(String[] args) { }
}

Related

How to use a boolean outside the scope of a key listener

I created a shop cart login JFrame and I added a "shopkeeperToggle" so that when it's pressed the user logs in to the shopkeeper's JFrame and otherwise to a shopper's jframe. the problem is I don't know how to implement it, I tried to set a boolean "pressed" to false whenever the key is released in the "shopkeeperToggle" key listener, and apparently I'm unable to use the value of pressed inside the sign-in button.
Here's the code for the toggle:
shopkeeperToggle = new JToggleButton("Shopkeeper");
shopkeeperToggle.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
});
and this is what I'm trying to do in the sign in button:
signinButton = new JButton("Sign in ");
signinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
// select the users that have the inputted credentials from the database
String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernamelogin.getText());
ps.setString(2, emaillogin.getText());
ps.setString(3,passwordlogin.getText());
ResultSet rs = ps.executeQuery();
// if query executed and
if (rs.next()) {
// if login succ show window log succ, and go to home shopping page
JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
if (pressed) {
OwnerHomePage ownerhome = new OwnerHomePage();
ownerhome.setVisible(true);
setVisible(false);
} else {
UserHomePage home = new UserHomePage();
home.setVisible(true);
setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
}
This may offer some help in fixing your issue. It is a fully compilable demo. The following changes were made.
Used Actions in lieu of KeyListener. A little more involved to setup but they can be configured to monitor only certain keys.
Used a JButton in lieu of a JToggleButton. No specific reason and can be changed.
Created separate inner classes for the listeners. Tends to reduce clutter and is usually more readable.
Changed the name of the button depending on the mode.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMapAndButtons {
JFrame frame = new JFrame("Demo");
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new ActionMapAndButtons().start());
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyClass cls = new MyClass();
frame.add(cls);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyClass extends JPanel {
JButton button = new JButton("Shopper Sign in");
boolean pause = false;
public MyClass() {
setPreferredSize(new Dimension(300, 300));
button.addActionListener(new ButtonListener());
add(button);
InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
for (int i = 0; i < 256; i++) {
map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
}
getActionMap().put("anyKey", new MyAction());
setFocusable(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj instanceof JButton) {
JButton b = (JButton) obj;
pause = !pause;
if (pause) {
b.setText("Shopkeeper Sign in");
} else {
b.setText("Shopper Sign in");
}
}
}
}
private class MyAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (pause) {
System.out.println("Shopkeeper - " + cmd);
} else {
System.out.println("Shopper - " + cmd);
}
}
}
}
Inner (or nested) classes and action maps are covered in The Java Tutorials
You can define pressed as a static value;
class c {
static boolean pressed = true;
...
}
and you can access anywhere;
c.pressed; //will return true if you don't change

how do I filter what I entered in the JTextField and display the filtered result?

package javaisnotbannana;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Javaisnotbannana{
public static void main(String[] args) {
window();
}
////////////////////////////////////////////////////
public static void window()
{
JFrame window= new JFrame();
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(30);
JButton jb = new JButton("Enter");
window.setTitle("ThisisTitleofWindow");
window.setVisible(true);
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//textfield
jp.add(jt);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String inoutt = jt.getText();
jl.setText(inoutt);
}
});
Why dose this lower section have the problem "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range:(how ever many characters i entered)".str is receiving what is typed in the Jtextfield and im trying to filter the input to give a different output. With out a filter it works fine like above just press enter,but when i try to press the button i and filter i get an error.
//button
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str = jt.getText();
String text="";
int A=0;
int B=1;
int C=2;
for(int num=0;num<=str.length()/3;num++)
{
if (str.charAt(A) == 'T'&&str.charAt(B) == 'A'&&str.charAt(C)=='S')
{
text+="smell tasty";
}
else if(str.charAt(A) == 'B'&&str.charAt(B) == 'A'&&str.charAt(C)=='N')
{
text+="bannanas";
}
A+=3;
B+=3;
C+=3;
}
jl.setText(text);
}
});
jp.add(jl);
window.add(jp);
}
}
your index is overshooting use this instead
for(int num=0;num<str.length()/3;num++)
just < not <=
The problem seems to the fact that you are overthinking the it. Remember, Java Strings are zero indexed so num<=str.length()/3 should be something more like num < str.length()/3
But, having said that, the whole thing seems woefully inefficient (not to mention confusing)
You could use something like...
for (int num = 0; num + 3 < str.length(); num++) {
String test = str.substring(num, 3);
if ("tas".equalsIgnoreCase(test)) {
text = "smell tasty";
break;
} else if ("ban".equalsIgnoreCase(test)) {
text = "bannanas";
break;
}
}
But even that's a long way around an otherwise simple problem.
Instead, you could simply use something like...
String str = "tas";
String text = "";
if (str.toLowerCase().contains("tas")) {
text = "smell tasty";
} else if (str.toLowerCase().contains("ban")) {
text = "bannanas";
}

Why is my output null every time?

Hello I have a class that opens a JFrame and takes in a text. But when I try getting the text it says its null.
Everytime I click the button I want the System.out to print the text I entered in the textArea.
This is my first class :
public class FileReader {
FileBrowser x = new FileBrowser();
private String filePath = x.filePath;
public String getFilePath(){
return this.filePath;
}
public static void main(String[] args) {
FileReader x = new FileReader();
if(x.getFilePath() == null){
System.out.println("String is null.");
}
else
{
System.out.println(x.getFilePath());
}
}
}
This is a JFrame that takes in the input and stores it in a static String.
/*
* This class is used to read the location
* of the file that the user.
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.event.*;
import javax.swing.*;
public class FileBrowser extends JFrame{
private JTextArea textArea;
private JButton button;
public static String filePath;
public FileBrowser(){
super("Enter file path to add");
setLayout(new BorderLayout());
this.textArea = new JTextArea();
this.button = new JButton("Add file");
add(this.textArea, BorderLayout.CENTER);
add(this.button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
System.exit(0);
}
});
}
}
But everytime I run these programs I get
String is null.
You are mistaken by the way how JFrames work. A JFrame does not stall the execution of the code until it is closed. So, basically, your code creates a JFrame and then grabs the filePath variable in that object, before the user could have possibly specified a file.
So, to solve this, move the code that outputs the filepath to stdout to the ActionListener you have. Get rid of the System.exit() call, and use dispose() instead.
Update: You should have this code for the ActionListener:
this.button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
filePath = new String(textArea.getText());
if(filePath == null){
System.out.println("String is null.");
}
else
{
System.out.println(filePath);
}
dispose();
}
});
And as main method:
public static void main(String[] args)
{
FileBrowser x = new FileBrowser();
}
Your main does not wait until the user has specified a text in the textArea. You could prevent this behaviour by looping until the text in the textArea is set or you could place the logic of the main function into the ActionListener to handle the event.
Following the second way the main function only creates a new FileBrowser object.

Java JTextField information access from another class

I am using a gui with JTextFields to collect some information and then a JButton that takes that infomration and writes it to a file, sets the gui visibility to false, and then uses Runnable to create an instance of another JFrame from a different class to display a slideshow.
I would like to access some of the information for the JTextFields from the new JFrame slideshow. I have tried creating an object of the previous class with accessor methods, but the values keep coming back null (I know that I have done this correctly).
I'm worried that when the accessor methods go to check what the variables equal the JTextFields appear null to the new JFrame.
Below is the sscce that shows this problem.
package accessmain;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class AccessMain extends JFrame implements ActionListener
{
private static final int FRAMEWIDTH = 800;
private static final int FRAMEHEIGHT = 300;
private JPanel mainPanel;
private PrintWriter outputStream = null;
private JTextField subjectNumberText;
private String subjectNumberString;
public static void main(String[] args)
{
AccessMain gui = new AccessMain();
gui.setVisible(true);
}
public AccessMain()
{
super("Self Paced Slideshow");
setSize(FRAMEWIDTH, FRAMEHEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
//Begin Main Content Panel
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(0,10,0,10));
mainPanel.setLayout(new GridLayout(7, 2));
mainPanel.setBackground(Color.WHITE);
add(mainPanel, BorderLayout.CENTER);
mainPanel.add(new JLabel("Subject Number: "));
subjectNumberText = new JTextField(30);
mainPanel.add(subjectNumberText);
mainPanel.add(new JLabel(""));
JButton launch = new JButton("Begin Slideshow");
launch.addActionListener(this);
mainPanel.add(launch);
//End Main Content Panel
}
#Override
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Begin Slideshow"))
{
subjectNumberString = subjectNumberText.getText();
if(!(subjectNumberString.equals("")))
{
System.out.println(getSubjectNumber());
this.setVisible(false);
writeFile();
outputStream.println("Subject Number:\t" + subjectNumberString);
outputStream.close();
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass();
testClass.setVisible(true);
}
});
}
else
{
//Add warning dialogue here later
}
}
}
private void writeFile()
{
try
{
outputStream = new PrintWriter(new FileOutputStream(subjectNumberString + ".txt", false));
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + subjectNumberString + ".txt or it could not be opened.");
System.exit(0);
}
}
public String getSubjectNumber()
{
return subjectNumberString;
}
}
And then creating a barebones class to show the loss of data:
package accessmain;
import javax.swing.*;
import java.awt.*;
public class AccessClass extends JFrame
{
AccessMain experiment = new AccessMain();
String subjectNumber = experiment.getSubjectNumber();
public AccessClass()
{
System.out.println(subjectNumber);
}
}
Hardcoding the accessor method with "test" like this:
public String getSubjectNumber()
{
return "test";
}
Running this method as below in the new JFrame:
SelfPaceMain experiment = new SelfPaceMain();
private String subjectNumber = experiment.getSubjectNumber();
System.out.println(subjectNumber);
Does cause the system to print "test". So the accessor methods seem to be working. However, trying to access the values from the JTextFields doesn't seem to work.
I would read the information from the file I create, but without being able to pass the subjectNumber (which is used as the name of the file), I can't tell the new class what file to open.
Is there a good way to pass data from JTextFields to other classes?
pass the argument 'AccessMain' or 'JTextField' to the second class:
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
AccessClass testClass = new AccessClass(AccessMain.this); //fixed this
testClass.setVisible(true);
}
});
Then reading the value of 'subjectNumber'(JTextField value) from the 'AccessMain' or 'JTextField' in the second class:
public class AccessClass extends JFrame
{
final AccessMain experiment;
public AccessClass(AccessMain experiment)
{
this.experiment = experiment;
}
public String getSubjectNumber(){
return experiment.getSubjectNumber();
}
}
Also, you should try Observer pattern.
A simple demo of Observalbe and Observer
Observable and Observer Objects

Mysterious one time Casting Exception

I am trying to use the PropertyChangeSupport of JComponent class.
But when I am executing the following code, Clicking on the menu button first time gives Runtime casting Exception, but then it runs fine always.
FrameListener.java
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
public class FrameListener extends JFrame implements ActionListener, PropertyChangeListener
{
JLabel lblMessage;
JMenuItem changeFont;
FontSource fe = new FontSource(this,"Font Editor");
public FrameListener(){
super("Hello World");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
increaseReadability() ;
changeFont.addActionListener(this);
fe.addPropertyChangeListener(this);
setSize(400,200);
setVisible(true);
}
private void increaseReadability(){
JPanel panel = new JPanel();
Font f = new Font("Times New Roman",Font.BOLD,24);
lblMessage = new JLabel("HELLO WORLD",SwingConstants.CENTER);
lblMessage.setFont(f);
panel.add(lblMessage);
JMenuBar actionBar = new JMenuBar();
JMenu edit = new JMenu("Edit");
changeFont = new JMenuItem("Font");
actionBar.add(edit);
edit.add(changeFont);
add(actionBar,BorderLayout.NORTH);
add(panel,BorderLayout.CENTER);
}
public void propertyChange(PropertyChangeEvent pcevent){
Object obj = pcevent.getNewValue() ;
System.out.println(obj.getClass()) ;
//Statement occuring problem 1st time
Font newFt = (Font)obj;
lblMessage.setFont(newFt);
}
public void actionPerformed(ActionEvent evt){
fe.setVisible(true);
}
public static void main(String argv[]) {
new FrameListener();
}
}
FontSource.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.beans.*;
public class FontSource extends JDialog implements ActionListener {
private Font newFont = new Font("Times New Roman",Font.BOLD,12);
JComboBox cbfType,cbfStyle,cbfSize;
JButton btnOk,btnCancel;
//protected PropertyChangeSupport changes = new PropertyChangeSupport(this);
public Font getNewFont(){
return newFont;
}
public void setNewFont(Font f){
Font old = newFont;
try{
//this statement calls the propertyChange() of FrameListener
//if u are removing comments, replace the following statement with
// changes.firePropertyChange("Font Changed",old,f);
firePropertyChange("Font Changed",old,f);
newFont = f;
}
catch(Exception e){
System.out.println(e);
}
}
public FontSource(Frame fr,String title){
super(fr,title);
// getting font family from the graphics environment.
GraphicsEnvironment gf = GraphicsEnvironment.getLocalGraphicsEnvironment();
String myfont[] = gf.getAvailableFontFamilyNames();
cbfType = new JComboBox(myfont);
add(cbfType);
String fontStyle[] = {"PLAIN","ITALIC","BOLD",};
cbfStyle = new JComboBox(fontStyle);
add(cbfStyle);
String fontSize[] = {"10","12","14","16","18","20","24","26","28","36","48","72"};
cbfSize = new JComboBox(fontSize);
add(cbfSize);
btnOk =new JButton("OK");
btnCancel =new JButton("Cancel");
add(btnOk);
add(btnCancel);
// adding action listener
btnOk.addActionListener(this);
btnCancel.addActionListener(this);
// setting layout and size for the dialog
setLayout(new FlowLayout());
setSize(170,170);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==btnOk){
String type = (String) cbfType.getSelectedItem();
String style = (String)cbfStyle.getSelectedItem();
int s = 0;
int size = Integer.parseInt((String)cbfSize.getSelectedItem());
if(style=="PLAIN")
s= Font.PLAIN;
else {
if(style =="BOLD")
s= Font.BOLD;
else
s= Font.ITALIC;
}
Font f = new Font(type,s,size);
setNewFont(f);
}
else{
this.setVisible(false);
}
}
/*
public void addPropertyChangeListener(PropertyChangeListener l){
System.out.println("attachement done...");
changes.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l){
changes.removePropertyChangeListener(l);
}
*/
}
But If i use my own PropertyChangeSupport (remove the comments in FontSource.java), then it's working perfectly.
I tried my best, but not getting this.
Thnx in advance :--)
If you implement PropertyListener, you will receive all of the property changes for the component(s) with which you register. There can be many types, whose values will be determined by the type of property change.
The implementation of Component method of setFont will fire a property change with the name of "font". If you test for that name, you should be fine:
public void propertyChange(PropertyChangeEvent pcevent){
Object obj = pcevent.getNewValue() ;
System.out.println(obj.getClass()) ;
//Problem should not occur with this call.
if (pcevent.getPropertyName().equals("font")){
Font newFt = (Font)obj;
lblMessage.setFont(newFt);
}
}
My guess...
The property change listening is not distinguishing by property name. Since you are listening to all of the properties of FontSource then you will undoubtedly see things that are not a Font.
In propertyChange() you can print the property name in the event to be sure that's the problem.
Solution is to register for just the property in which you are interested or to check the property name in the propertyChange() method.
Finally i got it.
The answer is displayed, when u compile and execute the following files.
FontSource.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.beans.*;
public class FontSource extends JDialog{
public FontSource(Frame fr,String title){
super(fr,title);
setSize(600, 400) ;
JTextArea area = new JTextArea() ;
area.setEditable(false) ;
add(new JScrollPane(area)) ;
String str = "If u look at the command prompt, then it is very clear," + "\n" +
"that, only on your first click on JMenuItem (font)," + "\n" +
"u get an output on cmd, for next future clicks on JMenuItem (font), u get no output on cmd." + "\n\n" +
"Reason : On first click, ActionListener attached to JMenuItem (font) invokes," + "\n" +
"fe.setVisible(true), which internally calls setBackground method of Component class only once." + "\n" +
"Now, setBackground method calls firePropertyChange(\"background\", oldValue, newValue)," + "\n" +
"which in turn also gets executed once." + "\n\n" +
"Now, solution to this is clearly mentioned in the reply" + "\n" +
"provided by akf for my question asked on stackoverflow. cheers :-)" ;
area.setText(str) ;
}
}
FrameListener.java
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
public class FrameListener extends JFrame implements ActionListener, PropertyChangeListener
{
JLabel lblMessage;
JMenuItem changeFont;
FontSource fe = new FontSource(this,"Font Editor");
public FrameListener(){
super("Hello World");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
increaseReadability() ;
changeFont.addActionListener(this);
fe.addPropertyChangeListener(this);
setSize(400,200);
setVisible(true);
}
private void increaseReadability(){
JMenuBar actionBar = new JMenuBar();
JMenu edit = new JMenu("Edit");
changeFont = new JMenuItem("Font");
actionBar.add(edit);
edit.add(changeFont);
add(actionBar,BorderLayout.NORTH);
}
public void propertyChange(PropertyChangeEvent pcevent){
Object obj = pcevent.getNewValue() ;
System.out.println(obj.getClass() + ", " + pcevent.getPropertyName()) ;
}
public void actionPerformed(ActionEvent evt){
fe.setVisible(true);
}
public static void main(String argv[]) {
new FrameListener();
}
}

Categories