Size of a JApplet

Hello everyone,
I made an applet but when I display it in a browser, it doesn't react on the HTML tag for width and heigth. It remains pretty small, no matter what i enter as heigth and width. Can any1 help me with this?
Regards,
Frans

Do you have to implement this as an applet? What about a stand-alone Swing application? Then you can use JFrame's pack method to give the frame its preferred size:
import java.awt.*;
import javax.swing.*;
public class FrameExample {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable(){
            public void run() {
                launchGUI();
    static void launchGUI() {
        JPanel cp = new JPanel(new BorderLayout());
        JToolBar tb = new JToolBar();
        tb.add(new JButton("button 0"));
        tb.add(new JButton("button 1"));
        tb.add(new JButton("button 2"));
        cp.add(tb, BorderLayout.NORTH);
        JScrollPane sp = new JScrollPane(new JTextArea(40,80));
        sp.setPreferredSize(new Dimension(400, 300));
        cp.add(sp, BorderLayout.CENTER);
        JFrame f = new JFrame("FrameExample");
        f.setContentPane(cp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
}

Similar Messages

  • Jframe is flickering -- Urgent help please!

    Basically i want to resize the window when i click some button say, NEW or EDIT and making some components visible.
    I am using setSize() method to resize the Jframe/window and setVisible() method.
    Do i need to use other methods. If you need some other details let me know as soon as possible.
    Below is the code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.Insets;
    import java.awt.GridBagLayout;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import com.symantec.itools.javax.swing.borders.LineBorder;
    import com.symantec.itools.javax.swing.borders.EtchedBorder;
    import com.symantec.itools.javax.swing.borders.BevelBorder;
    import com.symantec.itools.javax.swing.borders.CompoundBorder;
    import com.symantec.itools.javax.swing.borders.EmptyBorder;
    public class psRulesEditQ extends JFrame implements WindowListener
    public boolean inDebugMode = false;
    DBClient mydb;
    String SchemaID;
    int flagQ;
    int flagA;     
    DefaultListModel QuestionsModel = new DefaultListModel();
    DefaultListModel AnswersModel = new DefaultListModel();
    YesNoDialog alert;
    public psRulesEditQ (String title, DBClient mydb, String SchemaID)
    super(title);
    this.mydb = mydb;
    this.SchemaID = SchemaID;
    init();
    getQuestions();
    setTitle("Edit Questions for Domain: " + UserAttributes.getCurrentDomainName());
         public void init()
              // Take out this line if you don't use symantec.itools.net.RelativeURL or symantec.itools.awt.util.StatusScroller
              //symantec.itools.lang.Context.setApplet(this);
              // This line prevents the "Swing: checked access to system event queue" message seen in some browsers.
              getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
              // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              getContentPane().setLayout(null);
              setSize(660,330);
              //setBounds(50,50,660,330);
              EditQuestionsPanel.setLayout(null);
              getContentPane().add(EditQuestionsPanel);
              EditQuestionsPanel.setBounds(0,0,660,520);
              QuestionsPane.setOpaque(true);
              EditQuestionsPanel.add(QuestionsPane);
              QuestionsPane.setBounds(12,48,396,144);
              QuestionsPane.getViewport().add(QuestionsList);
              QuestionsList.setBounds(0,0,393,141);
              AnswersPane.setOpaque(true);
              EditQuestionsPanel.add(AnswersPane);
              AnswersPane.setBounds(444,48,192,144);
              AnswersPane.getViewport().add(AnswersList);
              AnswersList.setBounds(0,0,189,141);
              EditQuestionsPane.setOpaque(true);
              EditQuestionsPanel.add(EditQuestionsPane);
              EditQuestionsPane.setBounds(12,324,360,120);
              EditQuestionsPane.setVisible(false);
              EditQuestionsPane.getViewport().add(EditQuestionsTextArea);
              EditQuestionsTextArea.setBounds(0,0,357,117);
              EditQuestionsPanel.add(EditAnswersTextField);
              EditAnswersTextField.setBounds(444,324,134,25);
              EditAnswersTextField.setVisible(false);
              DeleteQuestionButton.setText("Delete");
              DeleteQuestionButton.setActionCommand("Delete");
              EditQuestionsPanel.add(DeleteQuestionButton);
              DeleteQuestionButton.setBounds(12,204,70,24);
              EditQuestionButton.setText("Edit");
              EditQuestionButton.setActionCommand("Edit");
              EditQuestionsPanel.add(EditQuestionButton);
              EditQuestionButton.setBounds(96,204,70,24);
              NewQuestionButton.setText("New");
              NewQuestionButton.setActionCommand("New");
              EditQuestionsPanel.add(NewQuestionButton);
              NewQuestionButton.setBounds(180,204,70,24);
              DeleteAnswerButton.setText("Delete");
              DeleteAnswerButton.setActionCommand("Delete");
              EditQuestionsPanel.add(DeleteAnswerButton);
              DeleteAnswerButton.setBounds(444,204,70,24);
              EditAnswerButton.setText("Edit");
              EditAnswerButton.setActionCommand("Edit");
              EditQuestionsPanel.add(EditAnswerButton);
              EditAnswerButton.setBounds(515,204,60,24);
              NewAnswerButton.setText("New");
              NewAnswerButton.setActionCommand("New");
              EditQuestionsPanel.add(NewAnswerButton);
              NewAnswerButton.setBounds(576,204,60,24);
              OkButton.setText("Ok");
              OkButton.setActionCommand("Ok");
              EditQuestionsPanel.add(OkButton);
              OkButton.setBounds(12,456,60,24);
              OkButton.setVisible(false);
              OkButton1.setText("Ok");
              OkButton1.setActionCommand("Ok");
              EditQuestionsPanel.add(OkButton1);
              OkButton1.setBounds(444,360,60,24);
              OkButton1.setVisible(false);
              CancelButton.setText("Cancel");
              CancelButton.setActionCommand("Cancel");
              EditQuestionsPanel.add(CancelButton);
              CancelButton.setBounds(84,456,73,24);
              CancelButton.setVisible(false);
              CancelButton1.setText("Cancel");
              CancelButton1.setActionCommand("Cancel");
              EditQuestionsPanel.add(CancelButton1);
              CancelButton1.setBounds(504,360,73,24);
              CancelButton1.setVisible(false);
              ShowRulesButton.setText("Show Rules");
              ShowRulesButton.setActionCommand("Show Rules");
              EditQuestionsPanel.add(ShowRulesButton);
              ShowRulesButton.setBounds(444,240,108,24);
              CloseButton.setText("Close");
              CloseButton.setActionCommand("Close");
              EditQuestionsPanel.add(CloseButton);
              CloseButton.setBounds(564,240,72,24);
              QuestionsLabel.setText("Questions");
              EditQuestionsPanel.add(QuestionsLabel);
              QuestionsLabel.setBounds(12,18,72,24);
              AnswersLabel.setText("Answers");
              EditQuestionsPanel.add(AnswersLabel);
              AnswersLabel.setBounds(444,12,60,36);
              EditQuestionsLabel.setText("Edit Questions");
              EditQuestionsPanel.add(EditQuestionsLabel);
              EditQuestionsLabel.setBackground(new java.awt.Color(204,204,204));
              EditQuestionsLabel.setBounds(12,276,90,48);
              EditQuestionsLabel.setVisible(false);
              NewQuestionsLabel.setText("New Questions");
              EditQuestionsPanel.add(NewQuestionsLabel);
              NewQuestionsLabel.setBounds(12,276,90,48);
              NewQuestionsLabel.setVisible(false);
              NewAnswersLabel.setText("New Answers");
              EditQuestionsPanel.add(NewAnswersLabel);
              NewAnswersLabel.setBounds(444,276,80,48);
              NewAnswersLabel.setVisible(false);
              EditAnswersLabel.setText("Edit Answers");
              EditQuestionsPanel.add(EditAnswersLabel);
              EditAnswersLabel.setBounds(444,276,80,48);
              EditAnswersLabel.setVisible(false);
              BorderLabel1.setBorder(etchedBorder1);
              EditQuestionsPanel.add(BorderLabel1);
              BorderLabel1.setBounds(5,12,643,264);
              BorderLabel2.setBorder(etchedBorder2);
              EditQuestionsPanel.add(BorderLabel2);
              BorderLabel2.setBounds(5,274,643,216);
              BorderLabel2.setVisible(false);
              //$$ etchedBorder1.move(0,540);
              //$$ etchedBorder2.move(24,540);
         QuestionsList.setModel(QuestionsModel);
         AnswersList.setModel(AnswersModel);
    //add all the listeners
    LAction LAction1 = new LAction();
         LSelector LSelector1 = new LSelector();
         //buttons
    CloseButton.addActionListener(LAction1);
    OkButton.addActionListener(LAction1);
    OkButton1.addActionListener(LAction1);
    DeleteAnswerButton.addActionListener(LAction1);
    DeleteQuestionButton.addActionListener(LAction1);
    NewAnswerButton.addActionListener(LAction1);
    NewQuestionButton.addActionListener(LAction1);
         EditQuestionButton.addActionListener(LAction1);
         EditAnswerButton.addActionListener(LAction1);
         CancelButton.addActionListener(LAction1);
         CancelButton1.addActionListener(LAction1);
    //ShowRulesButton.addActionListener(LAction1);
    //lists
         QuestionsList.addListSelectionListener(LSelector1);
         AnswersList.addListSelectionListener(LSelector1);
    //window
    this.addWindowListener(this);
         //{{DECLARE_CONTROLS
         javax.swing.JPanel EditQuestionsPanel = new javax.swing.JPanel();
         javax.swing.JScrollPane QuestionsPane = new javax.swing.JScrollPane();
         javax.swing.JList QuestionsList = new javax.swing.JList();
         javax.swing.JScrollPane AnswersPane = new javax.swing.JScrollPane();
         javax.swing.JList AnswersList = new javax.swing.JList();
         javax.swing.JScrollPane EditQuestionsPane = new javax.swing.JScrollPane();
         javax.swing.JTextArea EditQuestionsTextArea = new javax.swing.JTextArea();
         javax.swing.JTextField EditAnswersTextField = new javax.swing.JTextField();
         javax.swing.JButton DeleteQuestionButton = new javax.swing.JButton();
         javax.swing.JButton EditQuestionButton = new javax.swing.JButton();
         javax.swing.JButton NewQuestionButton = new javax.swing.JButton();
         javax.swing.JButton DeleteAnswerButton = new javax.swing.JButton();
         javax.swing.JButton EditAnswerButton = new javax.swing.JButton();
         javax.swing.JButton NewAnswerButton = new javax.swing.JButton();
         javax.swing.JButton OkButton = new javax.swing.JButton();
         javax.swing.JButton OkButton1 = new javax.swing.JButton();
         javax.swing.JButton CancelButton = new javax.swing.JButton();
         javax.swing.JButton CancelButton1 = new javax.swing.JButton();
         javax.swing.JButton ShowRulesButton = new javax.swing.JButton();
         javax.swing.JButton CloseButton = new javax.swing.JButton();
         javax.swing.JLabel QuestionsLabel = new javax.swing.JLabel();
         javax.swing.JLabel AnswersLabel = new javax.swing.JLabel();
         javax.swing.JLabel EditQuestionsLabel = new javax.swing.JLabel();
         javax.swing.JLabel NewQuestionsLabel = new javax.swing.JLabel();
         javax.swing.JLabel NewAnswersLabel = new javax.swing.JLabel();
         javax.swing.JLabel EditAnswersLabel = new javax.swing.JLabel();
         javax.swing.JLabel BorderLabel1 = new javax.swing.JLabel();
         javax.swing.JLabel BorderLabel2 = new javax.swing.JLabel();
         javax.swing.JOptionPane JOptionPane1 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane2 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane3 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane4 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane5 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane6 = new javax.swing.JOptionPane();
         javax.swing.JOptionPane JOptionPane7 = new javax.swing.JOptionPane();
         com.symantec.itools.javax.swing.borders.EtchedBorder etchedBorder1 = new com.symantec.itools.javax.swing.borders.EtchedBorder();
         com.symantec.itools.javax.swing.borders.EtchedBorder etchedBorder2 = new com.symantec.itools.javax.swing.borders.EtchedBorder();
    public void getQuestionInfo()
    String SQL, line, QuestionID, info="";
    QuestionID = parseID(QuestionsList.getSelectedValue().toString());
    SQL = "SELECT Additional FROM ps_questions WHERE QuestionID = " + QuestionID;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    info = mydb.getColumn(0);
    line = mydb.getRow();
    YesNoDialog d = new YesNoDialog(this, "Additional Information for Question " + QuestionID, info, "OK", null, null);
    if (d.getAnswer() == d.YES)
    d.dispose();
    public void getAnswerInfo()
    String SQL, line, AnswerID, info="";
    AnswerID = parseID(AnswersList.getSelectedValue().toString());
    SQL = "SELECT Additional FROM ps_answers WHERE AnswerID = " + AnswerID;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    info = mydb.getColumn(0);
    line = mydb.getRow();
    YesNoDialog d = new YesNoDialog(this, "Additional Information for Answer " + AnswerID, info, "OK", null, null);
    if (d.getAnswer() == d.YES)
    d.dispose();
    public void getQuestions()
    String SQL, line;
    SQL = "SELECT QuestionID, QuestionText FROM tps_questions WHERE SchemaID = " + SchemaID + " ORDER BY QuestionID ASC";
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    QuestionsModel.addElement("Q" + mydb.getColumn(0) + ": " + mydb.getColumn(1));
    line = mydb.getRow();
    public String parseID(String str)
    return str.substring(1, str.indexOf(":"));
    public void getAnswers()
    String SQL, line, QuestionID;
    String Question = QuestionsList.getSelectedValue().toString();
    AnswersModel.removeAllElements();
    QuestionID = parseID(Question);
    SQL = "SELECT AnswerID, AnswerText FROM tps_answers WHERE QuestionID = " + QuestionID;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    AnswersModel.addElement("A" + mydb.getColumn(0) + ": " + mydb.getColumn(1));
    line = mydb.getRow();
    public void setQuestion()
         EditAnswersTextField.setText("");
    String q = QuestionsList.getSelectedValue().toString();
    EditQuestionsTextArea.setText(q.substring(q.indexOf(":")+2, q.length()));
    public void setAnswer()
    String q = AnswersList.getSelectedValue().toString();
    EditAnswersTextField.setText(q.substring(q.indexOf(":")+2, q.length()));
    public String getNewID(String tableName, String fieldName)
    String SQL, line, newID;
    SQL = "";
    if (tableName.equals("tps_answers"))
    SQL = "SELECT MAX(AnswerID) FROM " + tableName;
    else if (tableName.equals("tps_questions"))
    SQL = "SELECT MAX(QuestionID) FROM " + tableName;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    int n = Integer.parseInt(mydb.getColumn(0).trim());
    n++;
    newID = n + "";
    return newID;
    public void addNewQuestion()
    //add to db and list
    int index;
    String q, QuestionID;
    q = EditQuestionsTextArea.getText();
    QuestionID = getNewID("tps_questions", "QuestionID");
    if (!(q.substring(q.length()-1, q.length())).equals("?"))
    q = q + "?";
    QuestionsModel.addElement("Q" + QuestionID + ": " + q);
    mydb.addRow("tps_questions");
    mydb.setColumn("QuestionID", QuestionID);
    mydb.setColumn("SchemaID", SchemaID);
    mydb.setColumn("QuestionText", "'" + q + "'");
    mydb.setColumn("Additional", "'null'");
    mydb.update();
         EditQuestionsTextArea.setText("");
         AnswersModel.removeAllElements();
         index = QuestionsModel.getSize();
         QuestionsList.setSelectedIndex(index-1);
    public void addEditQuestion()
         int i = QuestionsModel.indexOf(QuestionsList.getSelectedValue());
         String QuestionID = parseID(QuestionsList.getSelectedValue().toString());
         String q = EditQuestionsTextArea.getText();
              if (!(q.substring(q.length()-1, q.length())).equals("?"))
    q = q + "?";
         QuestionsModel.set(i, "Q" + QuestionID + ": " + q);
         mydb.editRow("tps_questions","QuestionID = " + QuestionID);
         mydb.setColumn("QuestionID", QuestionID);
    mydb.setColumn("SchemaID", SchemaID);
    mydb.setColumn("QuestionText", "'" + q + "'");
    mydb.setColumn("Additional", "'null'");
    mydb.update();
    public void addEditAnswer()
         String a, AnswerID, QuestionID;
    String q = QuestionsList.getSelectedValue().toString();
    a = EditAnswersTextField.getText();
    if (inDebugMode) System.err.println("a = " + a);
    QuestionID = parseID(q);
         int i = AnswersModel.indexOf(AnswersList.getSelectedValue());
    AnswerID = parseID(AnswersList.getSelectedValue().toString());
    AnswersModel.set(i, "A" + AnswerID + ": " + a);
    mydb.editRow("tps_answers","AnswerID = " + AnswerID);
    mydb.setColumn("QuestionID", QuestionID);
    mydb.setColumn("AnswerID", AnswerID);
    mydb.setColumn("SchemaId", SchemaID);
    mydb.setColumn("AnswerText", "'" + a + "'");
    mydb.setColumn("Additional", "'null'");
    mydb.update();
    // EditAnswersTextField.setText("");
    public void addNewAnswer()
    //getItems() method in List
    String a, AnswerID, QuestionID;
    String q = QuestionsList.getSelectedValue().toString();
    a = EditAnswersTextField.getText();
    if (inDebugMode) System.err.println("a = " + a);
    QuestionID = parseID(q);
    AnswerID = getNewID("tps_answers", "AnswerID");
    mydb.addRow("tps_answers");
    mydb.setColumn("QuestionID", QuestionID);
    mydb.setColumn("AnswerID", AnswerID);
    mydb.setColumn("SchemaId", SchemaID);
    mydb.setColumn("AnswerText", "'" + a + "'");
    mydb.setColumn("Additional", "'null'");
    mydb.update();
    AnswersModel.addElement("A" + AnswerID + ": " + a);
    EditAnswersTextField.setText("");
    //added 9-2-97 lmc - deletes an answer
    public void deleteAnswer(String answer)
    String msg;
    //getRulesA(answer);
    String Answer = AnswersList.getSelectedValue().toString();
    String AnswerID = answer.substring(1, answer.indexOf(":"));
    msg = "Are you sure you want to delete the answer:\n";
    msg += " \n";
    msg += AnswersList.getSelectedValue().toString() + " \n";
    msg += " \nThe following rules also use this question as a precondition.\n";
    //for (int i=0; i<rules.getLastVisibleIndex(); i++)
    // rules.setSelectedIndex(i);
    // msg += " \n rule " + rules.getSelectedIndex();
    msg += " \n \nDeleting the answer will affect these rules.";
    YesNoDialog confirm = new YesNoDialog(this, "Delete Answer " + AnswerID, msg, "Delete", "Cancel", null);
    if (confirm.getAnswer() == confirm.YES)
    mydb.deleteRow("tps_answers", "AnswerID=" + AnswerID);
    mydb.deleteRow("tps_preconditions", "AnswerID=" + AnswerID);
    AnswersModel.removeElementAt(AnswersList.getSelectedIndex());
    else System.err.println("did not delete");
    public void deleteQuestion(String question)
    String msg, SQL, line;
    String QuestionID = question.substring(1, question.indexOf(":"));
    //getRulesQ(question);
    msg = "Are you sure you want to delete the question:\n";
    msg += " \n";
    msg += QuestionsList.getSelectedValue().toString() + " \n";
    msg += " \nThe following rules also use this question as a precondition.\n";
    //for (int i=0; i<rules.getLastVisibleIndex(); i++)
    // rules.setSelectedIndex(i);
    // msg += " \n rule " + rules.getSelectedIndex();
    msg += " \n \nDeleting the question will affect these rules.";
    YesNoDialog confirm = new YesNoDialog(this, "Delete Question " + QuestionID, msg, "Delete", "Cancel", null);
    if (confirm.getAnswer() == confirm.YES)
    mydb.deleteRow("tps_questions", "QuestionID=" + QuestionID);
    SQL = "SELECT QuestionID FROM tps_answers WHERE QuestionID=" + QuestionID;
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    mydb.deleteRow("tps_answers", "QuestionID=" + QuestionID);
    line = mydb.getRow();
    QuestionsModel.removeElementAt(QuestionsList.getSelectedIndex());
    AnswersModel.removeAllElements();
         EditQuestionsTextArea.setText("");          
    else System.err.println("did not delete");
    public void showRules(String question)
    ListFrame allRules;
    String QuestionID = question.substring(1, question.indexOf(":"));
    allRules = new ListFrame("All the Rules that Contain Question " + QuestionID, "Q", question, rules);
    allRules.show();
    /* //added 2/18/01 srh to make the "Show Rules" button work
    public void showRules(String question, String answer)
    ListFrame allRules;
    java.awt.List matchingRules = new java.awt.List();
    String listId, type="", SQL, line;
    if (question != null)
    {  listId = question.substring(1, question.indexOf(":"));
    type = "Quesiton";
    else if (answer != null)
    {  listId = answer.substring(1, question.indexOf(":"));
    type = "Answer";
    else
    {  //AppletGlobals.eval("alert('You must choose a quesiton or answer to display.')");
    alert = new YesNoDialog(this, "Add Answer ...", "You must choose a quesiton or answer to display.", "OK", null, null);
    return;
    SQL = "SELECT RuleID FROM tps_preconditions WHERE PreQuestionId = "+ listId;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    matchingRules.add(mydb.getColumn(0));
    line = mydb.getRow();
    allRules = new ListFrame("All the Rules that Contain "+type+" " + listId, "P", question, matchingRules);
    allRules.show();
    public void getRulesQ(String question)
    String SQL, line;
    String QuestionID;
         rules = new javax.swing.Jlist();
    QuestionID = question.substring(1, question.indexOf(":"));
    SQL = "SELECT RuleID FROM tps_preconditions WHERE PreQuestionID=" + QuestionID;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    rules.add(mydb.getColumn(0));
    line = mydb.getRow();
    public void getRulesA(String answer)
    String SQL, line;
    String AnswerID;
    rules = new javax.swing.Jlist();
    AnswerID = answer.substring(1, answer.indexOf(":"));
    SQL = "SELECT RuleID FROM tps_preconditions WHERE AnswerID=" + AnswerID;
    mydb.closeSQL();
    mydb.sendSQL(SQL);
    line = mydb.getRow();
    while (mydb.more())
    rules.add(mydb.getColumn(0));
    line = mydb.getRow();
         //ActionListener method
         class LAction implements java.awt.event.ActionListener
    public void actionPerformed(java.awt.event.ActionEvent event)
         Object object = event.getSource();
              if (object == CloseButton)
              dispose();
              else if (object == NewQuestionButton)
                        flagQ = 0;
                        setSize(660,550);
                        psRulesEditQ.this.setVisible(true);
                        //QuestionsList.setEnabled(false);
                        EditQuestionsLabel.setVisible(false);
                        NewAnswersLabel.setVisible(false);
                        EditAnswersLabel.setVisible(false);
                        EditAnswersTextField.setVisible(false);
              OkButton1.setVisible(false);
                        CancelButton1.setVisible(false);
                        BorderLabel2.setVisible(true);
                        CancelButton.setVisible(true);
                        NewQuestionsLabel.setVisible(true);
                        EditQuestionsPane.setVisible(true);
              EditQuestionsTextArea.setText("");
                        OkButton.setVisible(true);
                        //setSize(670,551);
                        //psRulesEditQ.this.getContentPane().setSize(670,551);
                        //EditQuestionsPane.repaint();
              else if (object == NewAnswerButton)
                        flagA = 0;
                        EditAnswersLabel.setVisible(false);          
                        NewQuestionsLabel.setVisible(false);
                        EditQuestionsLabel.setVisible(false);
                        EditQuestionsPane.setVisible(false);
                        OkButton.setVisible(false);
                        CancelButton.setVisible(false);
                             if (QuestionsList.isSelectionEmpty())
                             JOptionPane5.showMessageDialog(psRulesEditQ.this, "Select the question first!","Message",JOptionPane.PLAIN_MESSAGE);
                             else
                             setSize(660,550);
                             psRulesEditQ.this.setVisible(true);
                             BorderLabel2.setVisible(true);
                             //QuestionsList.setEnabled(true);
                             NewAnswersLabel.setVisible(true);
                             EditAnswersTextField.setVisible(true);
                   EditAnswersTextField.setText("");
                             OkButton1.setVisible(true);
                             CancelButton1.setVisible(true);
                   else if (object == EditQuestionButton)
                        flagQ = 1;
                        //QuestionsList.setEnabled(true);
                        NewQuestionsLabel.setVisible(false);
                        NewAnswersLabel.setVisible(false);
                        EditAnswersLabel.setVisible(false);
                        EditAnswersTextField.setVisible(false);
              OkButton1.setVisible(false);
                        CancelButton1.setVisible(false);
                        EditQuestionsLabel.setVisible(true);
                             if (QuestionsList.isSelectionEmpty())
                             JOptionPane2.showMessageDialog(psRulesEditQ.this, "Select a question to edit!","Message",JOptionPane.PLAIN_MESSAGE);
                             else
                             setSize(660,550);
                             psRulesEditQ.this.setVisible(true);
                             BorderLabel2.setVisible(true);
                             EditQuestionsPane.setVisible(true);     
                             OkButton.setVisible(true);
                             CancelButton.setVisible(true);
                             setQuestion();
                   else if (object == EditAnswerButton)
                        flagA = 1;
                        NewQuestionsLabel.setVisible(false);
                        NewAnswersLabel.setVisible(false);
                        EditQuestionsLabel.setVisible(false);
                        EditQuestionsPane.setVisible(false);
                        OkButton.setVisible(false);
                        CancelButton.setVisible(false);
                        EditAnswersLabel.setVisible(true);
                             if (AnswersList.isSelectionEmpty())
                             JOptionPane3.showMessageDialog(psRulesEditQ.this, "Select an answer to edit!","Message",JOptionPane.PLAIN_MESSAGE);
                             else
                             setSize(660,550);
                             psRulesEditQ.this.setVisible(true);
                             BorderLabel2.setVisible(true);
                             EditAnswersTextField.setVisible(true);
                             OkButton1.setVisible(true);
                             CancelButton1.setVisible(true);
                             setAnswer();
              else if (object == OkButton)
                   if (flagQ == 0)
                                  String x = EditQuestionsTextArea.getText();
                                  if (x.equals(""))
                                  JOptionPane6.showMessageDialog(psRulesEditQ.this, "You must type in a question first!","Message",JOptionPane.PLAIN_MESSAGE);
                                  else
                                  addNewQuestion();
                                  QuestionsList.setEnabled(true);
                             else if (flagQ == 1)
                             addEditQuestion();
                             setSize(660,330);
                             BorderLabel2.setVisible(false);
                             NewQuestionsLabel.setVisible(false);
                             EditQuestionsLabel.setVisible(false);
                             EditQuestionsPane.setVisible(false);
                             OkButton.setVisible(false);
                             CancelButton.setVisible(false);
              else if (object == OkButton1)
                             if (flagA == 0)
                                  String y = EditAnswersTextField.getText();
                                  if (y.equals(""))
                                  JOptionPane7.showMessageDialog(psRulesEditQ.this, "You must type in an answer first!","Message",JOptionPane.PLAIN_MESSAGE);
                                  else
                                  addNewAnswer();     
                             else if (flagA == 1)
                             addEditAnswer();
                             setSize(660,330);
                             BorderLabel2.setVisible(false);
                             NewAnswersLabel.setVisible(false);
                             EditAnswersLabel.setVisible(false);
                             EditAnswersTextField.setVisible(false);
                   OkButton1.setVisible(false);
                             CancelButton1.setVisible(false);
              else if (object == DeleteQuestionButton)
                             if (QuestionsList.isSelectionEmpty())
                             JOptionPane1.showMessageDialog(psRulesEditQ.this, "Select a question to delete!","Message",JOptionPane.PLAIN_MESSAGE);
              BorderLabel2.setVisible(false);
                        NewQuestionsLabel.setVisible(false);
                        EditQuestionsLabel.setVisible(false);
                        EditQuestionsPane.setVisible(false);
                        OkButton.setVisible(false);
                        CancelButton.setVisible(false);
                        CancelButton1.setVisible(false);
                        NewAnswersLabel.setVisible(false);
                        EditAnswersLabel.setVisible(false);
                        EditAnswersTextField.setVisible(false);
              OkButton1.setVisible(false);
                        deleteQuestion(QuestionsList.getSelectedValue().toString());
              else if (object == DeleteAnswerButton)
                   if (AnswersList.isSelectionEmpty())
                             JOptionPane4.showMessageDialog(psRulesEditQ.this, "Select an answer to delete!","Message",JOptionPane.PLAIN_MESSAGE);
                        BorderLabel2.setVisible(false);
                        NewQuestionsLabel.setVisible(false);
              EditQuestionsLabel.setVisible(false);
                        EditQuestionsPane.setVisible(false);
                        OkButton.setVisible(false);
                        CancelButton.setVisible(false);
                        CancelButton1.setVisible(false);
                        NewAnswersLabel.setVisible(false);
                        EditAnswersLabel.setVisible(false);
                        EditAnswersTextField.setVisi

    Hi,
    I have a JApplet with JComponents. When the size of the JApplet is larger than the browser, scrollbar of the browser is used. Flickering is very worse when scrolled. Any help in this regard is appreciated.
    Kiru

  • Swing layout/size problem with JFrame and JApplet.

    I have a class that extends a JFrame, the classes layout is BorderLayout. I then have a class that extend JApplet, this classes layout is GridBagLayout (this class has a JTabbedPane - which contains JPanels). The problem I'm having is no matter how big I make the size of the applet or frame (using setSize), the applet/frame stays the same size - no matter how large I make it.
    Can anyone please help?
    Thanks,
    dosteov

    Here is the basic code:
    Thanks in advance,
    dosteov
    public class EADAdm extends JApplet
    EADAdmFrame theFrame = new EADAdmFrame(this);
         public void init()
              // Take out this line if you don't use symantec.itools.net.RelativeURL or symantec.itools.awt.util.StatusScroller
    //          symantec.itools.lang.Context.setApplet(this);
              // This line prevents the "Swing: checked access to system event queue" message seen in some browsers.
              getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
              // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              getContentPane().setLayout(new GridBagLayout());
              setEnabled(false);
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(800,800);
              getContentPane().add(AdmTab, new com.symantec.itools.awt.GridBagConstraintsD(0,1,2,1,0.5,0.5,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.HORIZONTAL,new Insets(3,12,4,14),120,120));
              AdmTab.setFont(new Font("Dialog", Font.PLAIN, 12));
              titleLbl.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
              titleLbl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
              titleLbl.setText("EAD Administration");
              getContentPane().add(titleLbl, new com.symantec.itools.awt.GridBagConstraintsD(0,0,1,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(12,36,0,0),307,15));
              titleLbl.setForeground(java.awt.Color.blue);
              titleLbl.setFont(new Font("Dialog", Font.BOLD, 15));
              exitBtn.setText("Exit EAD Administration");
              exitBtn.setActionCommand("Exit EAD Administration");
              getContentPane().add(exitBtn, new com.symantec.itools.awt.GridBagConstraintsD(0,2,2,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(6,371,10,14),66,8));
              exitBtn.setFont(new Font("Dialog", Font.PLAIN, 12));
         //theFrame.setVisible(false);
         login();
         AdmTab.addTab("Administration", new LogoPanel() );
         userPanel = createUserPanel();
         AdmTab.addTab("Edit Users", userPanel );
         fpoPanel = createFPOPanel();
         AdmTab.addTab("Edit FPO", fpoPanel );
         regulationPanel = createRegulationPanel();
         AdmTab.addTab("Edit Regulations", regulationPanel );
         rolloverPanel = createRolloverPanel();
         AdmTab.addTab("Rollover", rolloverPanel );           
              //{{REGISTER_LISTENERS
         SymMouse aSymMouse = new SymMouse();
              this.addMouseListener(aSymMouse);
              SymAction lSymAction = new SymAction();
              exitBtn.addActionListener(lSymAction);
              SymKey aSymKey = new SymKey();
              this.addKeyListener(aSymKey);
         theFrame.getContentPane().add(this);
    public class EADAdmFrame extends JFrame
    EADAdm theApplet;
    public EADAdmFrame(EADAdm theMainApplet)
              //{{INIT_CONTROLS
         //     theApplet = theMainApplet;
         //     this.getContentPane().add(theApplet);
              getContentPane().setLayout(new BorderLayout(0,0));
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(1000,1000);
              setVisible(false);
         theApplet = theMainApplet;
              //{{REGISTER_LISTENERS
              SymWindow aSymWindow = new SymWindow();
              this.addWindowListener(aSymWindow);
              SymComponent aSymComponent = new SymComponent();
              this.addComponentListener(aSymComponent);

  • Preserve aspect ratio of JPanel size within JApplet

    Hi, currently, I have a JPanel component, which will be placed at the center of JApplet (This JApplet is BorderLayout).
    I wish to preserve the aspect ratio of the JPanel to square (width equal to height) even when the JApplet size is changed.
    I overriden the getPreferredSize, getMinimumSize and getMaximumSize of JPanel as follow:
    import java.awt.*;
    * @author  yccheok
    public class NewJPanel extends javax.swing.JPanel {
        /** Creates new form NewJPanel */
        public NewJPanel() {
            initComponents();
            this.setBackground(Color.RED);
        public Dimension getMinimumSize() {
            Dimension dimension;
            dimension = super.getMinimumSize();
            Dimension newDimension;
            if(dimension.getWidth() < dimension.getHeight()) {
                newDimension = new Dimension((int)dimension.getWidth(), (int)dimension.getWidth());
            else {
                newDimension = new Dimension((int)dimension.getHeight(), (int)dimension.getHeight());
            System.out.println("newDimension="+newDimension);
            return newDimension;
        public Dimension getMaximumSize() {
            return getMinimumSize();
        public Dimension getPreferredSize() {
            return getMinimumSize();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            setLayout(new java.awt.BorderLayout());
        // </editor-fold>                       
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }whereas my JApplet code is as follow:
    import java.awt.*;
    import javax.swing.*;
    * @author yccheok
    public class NewJApplet extends javax.swing.JApplet {
        /** Creates a new instance of NewJApplet */
        public NewJApplet() {
        public void init()
            this.getContentPane().setLayout(new BorderLayout());
            this.getContentPane().add(new NewJPanel(), BorderLayout.CENTER);
    }However, I realize none of the JPanel's getPreferredSize, getMinimumSize or getMaximumSize is called. Am I doing something wrong?
    Thank you very much!

    You probably should create your own layout manager

  • JButtons in JToolbar don't work with JApplet- why?

    I made a JApplet which has a toolbar, populated with burrons that manipulate data from text files. The programs works perfectly when it is not a JApplet. However, once I converted it to a JApplet it does nothing. The code was exactly the same, but, pressing buttons does nothing when it is an applet. here is the complete code;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7    1 = 6...
                    public JButton getToolBarButton(String s)
                        String imgLoc = "TBar Icons/" +s +".gif";
                        java.net.URL imgURL = CSE.class.getResource(imgLoc);
                        JButton button = new JButton();
                        button.setActionCommand(s);
                        button.setToolTipText(s);
                        button.addActionListener(this);
                        if(imgURL != null)
                            button.setIcon(new ImageIcon(imgURL, s));
                        else
                            button.setText(s);
                            System.err.println("Couldn't find; " +imgLoc);
                        return button;
                        public CSE()
                                   // super("Test CSE");
                                    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                    for(int x=0; x<materialNames.length; x++)
                                        materials = getToolBarButton(materialNames[x]);
                                        mainSelect.add(materials);
                                    //checkBoxes
                                    dataToShow.add(weeklySelect);
                                    dataToShow.add(dailySelect);
                                    weeklySelect.addItemListener(this);
                                    dailySelect.addItemListener(this);
                                    // sizes
                                    setSize(850, 850);
                                    //colors and fonts
                                    weeklyGraph.setBackground(new Color(250, 30, 40));
                                    dailyGraph.setBackground(new Color(100, 40, 200));
                                    //text Manip.
                                    prediction.setLineWrap(true);
                                    priceUpdate.setLineWrap(true);
                                    //scrolling
                                    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    //main splitpane config.
                                    mainConsoleBackdrop.setOneTouchExpandable(true);
                                    mainConsoleBackdrop.setResizeWeight(.85);
                                    //placement and Layout
                                    //GraphLayout
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(dailyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(weeklyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    dataOut.setRightComponent(predictionScroll);
                                    //consoleData layout
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalBuy);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalSell);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(buySell);
                                    finalPricesLay.add(finalPricesLabels);
                                    finalPricesLay.add(Box.createVerticalStrut(10));
                                    finalPricesLay.add(weeklySelect);
                                    finalPricesLay.add(dailySelect);
                                    finalPricesLay.add(priceUScroll);
                                    dataOut.setLeftComponent(finalPricesLay);
                                    mainConsoleBackdrop.setTopComponent(graphs);
                                    mainConsoleBackdrop.setBottomComponent(dataOut);
                                    getContentPane().add(mainConsoleBackdrop);
                                    getContentPane().add(mainSelect, BorderLayout.NORTH);
                                    //visibility
                                   // CSEFrame.setVisible(true);
                                    //return(CSEFrame);
                                        public void actionPerformed(ActionEvent e)
                                            getMonth();
                                            inputS = e.getActionCommand();
                                            FileReader newRead = null;
                                                    try {
                                                           newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
                                                           proceed = true;
                                                        catch(FileNotFoundException f)
                                                           System.out.println("File not found");
                                                           proceed = false;
                                          if(proceed)
                                          BufferedReader bufferedReader = new BufferedReader(newRead);
                                          scanner  = new Scanner(bufferedReader);
                                          scanner.useDelimiter("\n");
                                         //starts daily analysis
                                          getPrice(scanner);
                                        //starts weekly analysis
                                          weekly(inputS);
                                    public void itemStateChanged(ItemEvent e)
                                        if(weeklySelect.isSelected())
                                        priceUpdateWeekly.setText("");
                                        finalPricesLay.remove(priceUScroll);
                                        finalPricesLay.add(priceUScrollW);
                                        finalPrices.updateUI();
                                        else
                                            priceUpdate.setText("");
                                            finalPricesLay.remove(priceUScrollW);
                                            finalPricesLay.add(priceUScroll);
                                            finalPrices.updateUI();
                                    public void weekly(String inputS)
                                        weekly = true;
                                        for(int x = 0; x < 7; x++)
                                           dateToUse(month, day, year, (x+1));
                                            try
                                                    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
                                                    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
                                                    week[x] = new Scanner(weeklyBuffer);
                                                    week[x].useDelimiter("\n");
                                                    getPrice(week[x]);
                                             catch(FileNotFoundException f)
                                                JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
                                        weekly = false;
                                        dateReset();
                                    public void getPrice(Scanner scanner)
                                        while(scanner.hasNextLine())
                                            //puts into string the next scan token
                                            String s = scanner.next();
                                            //takes the scan toke above and puts it into an editable enviroment
                                            String [] data = s.split("\\s");
                                            for(position = 0; position < data.length; position++)
                                                        //Scanner test to make sure loop can finish, otherwise "no such line" error
                                                        if(scanner.hasNextLine()==false)
                                                        scanner.close();
                                                        break;
                                                           /*Starts data orignazation by reading from each perspective field
                                                            * 1 = day
                                                            * 2 = day of month
                                                            * 3 = month
                                                            * 4 = year
                                                           if(position == 0 && weekly == false)
                                                               String dayFromFile = data[position];
                                                                int dayNum = Integer.parseInt(dayFromFile);
                                                              priceUpdate.append(days[dayNum-1] +" ");
                                                           else if(position == 1  && weekly == false )
                                                              priceUpdate.append(data[position] + "/");
                                                           else if(position == 2 && weekly == false)
                                                              priceUpdate.append(data[position] + "/");
                                                            else if(position == 3 && weekly == false)
                                                                priceUpdate.append(data[position] +"\n");
                                                           //if it is in [buy] area, it prints and computes
                                                            else if(position == 7)
                                                                //obtains string for buy price and stores it, then prints it
                                                                String buy = data[position];
                                                            if(weekly == false)
                                                            priceUpdate.append("Buy: " +buy +"\n" );
                                                             //converts buy to string
                                                            currentBuyPrice = Integer.parseInt(buy);
                                                            //eliminates problems caused by no data from server- makes the price 0
                                                            if(currentBuyPrice < 0)
                                                                currentBuyPrice = 0;
                                                            //if it is greater it adds
                                                            if(currentBuyPrice > buyPrice)
                                                                     buyPrice += currentBuyPrice;
                                                            //if it is equal [there is no change] then it does nothing    
                                                            if(currentBuyPrice == buyPrice)
                                                                buyPrice +=0;
                                                            //if there is a drop, it subtracts
                                                               else
                                                                   buyPrice -= currentBuyPrice;
                                                            //if it is in [sell] area, it prints, and resets the position to zero because line is over
                                                            else if(position == 8)
                                                                //puts sell data into string and prints it
                                                                String sell = data[position];
                                                                if(weekly == false)
                                                                priceUpdate.append("Sell: " + sell +"\n");
                                                                //turns sell data into int.
                                                              currentSellPrice = Integer.valueOf(sell).intValue();;
                                                            //gets rid of problems caused by no data on server side- makes it 0 
                                                            if(currentSellPrice < 0)
                                                                currentSellPrice = 0;
                                                            //adds if there is an increase
                                                            if(currentSellPrice > sellPrice)
                                                                     sellPrice += currentSellPrice;
                                                            //does nothing if it is the same    
                                                            if(currentSellPrice == sellPrice)
                                                                sellPrice +=0;
                                                            //subtracts if there is drop
                                                               else
                                                                   sellPrice -= currentSellPrice;
                                                                //further protection against "No such line" and moves it down
                                                               if(scanner.hasNextLine() == true)
                                                                scanner.nextLine();
                                                                //if scanner is finished, prints out all lines
                                                               if(scanner.hasNextLine() == false && weekly == false)
                                                                finalBuy.setText("Net Buy Price Change: "+buyPrice);
                                                                finalSell.setText("Net Sell Price Change: " +sellPrice);
                                                                buyPrice = 0;
                                                                sellPrice = 0;
                                                                position = data.length;
                                                               else if(scanner.hasNextLine() == false && weekly == true)
                                                                   priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
                                                                   buyPrice = 0;
                                                                   sellPrice = 0;
                                                                   position = data.length;
                                                                   dayOfWeek++;
                                                                   if(dayOfWeek > 6)
                                                                   dayOfWeek = 0;
                                public void getMonth()
                                    for(int x=0; x < monthCheck.length; x++)
                                        if(month == monthCheck[x])
                                              monthS = (x+1);
                                              x = monthCheck.length;
                                 public void dateToUse(int month, int day, int year, int increment)
                                 //set day of source
                                  dayS = (day - increment);
                                //if day of source is less then O then we have moved to another month 
                                if(dayS <= 0)
                                        //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
                                        int incrementDay = increment - day;
                                        //decrements month
                                        monthS--;
                                        //if month is less then zero, then we have moved into another year and month has become 12
                                        if(monthS <= 0)
                                            yearS--;
                                            monthS = 12;
                                        //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
                                           if(month == 3)
                                               dayS = 28 - incrementDay;
                                           else if(month == 5 || month == 7)
                                               dayS = 29 - incrementDay;
                                           else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
                                               dayS = 31 - incrementDay;
                                            else
                                                dayS = 30 - incrementDay;
                               //resets the source date to the current date once data from the week has been reached
                                public void dateReset()
                                    dayS = day;
                                    monthS = month;
                                    yearS = year;
                     public void init()
                         //JFrame frame = new CSEFrameSet();
                        // this.setContentPane(CSEFrameSet());
                        CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }I have tried uploading it to a server, running it from appletviewer, and locally using the .HTML file. The GUI works fine, everything is there, however, pressing the buttons does nothing.
    Can you not use the Scanners and such with JApplets?
    Yes, the directories are good.
    EDIT EDIT EDIT; OK, it works with appletviewer, but still doesn't work when it is published.
    Message wa

    I can't seem to edit the post anymore, here it is again;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7 1 = 6...
    public JButton getToolBarButton(String s)
    String imgLoc = "TBar Icons/" +s +".gif";
    java.net.URL imgURL = CSE.class.getResource(imgLoc);
    JButton button = new JButton();
    button.setActionCommand(s);
    button.setToolTipText(s);
    button.addActionListener(this);
    if(imgURL != null)
    button.setIcon(new ImageIcon(imgURL, s));
    else
    button.setText(s);
    System.err.println("Couldn't find; " +imgLoc);
    return button;
    public CSE()
    // super("Test CSE");
    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    for(int x=0; x<materialNames.length; x++)
    materials = getToolBarButton(materialNames[x]);
    mainSelect.add(materials);
    //checkBoxes
    dataToShow.add(weeklySelect);
    dataToShow.add(dailySelect);
    weeklySelect.addItemListener(this);
    dailySelect.addItemListener(this);
    // sizes
    setSize(850, 850);
    //colors and fonts
    weeklyGraph.setBackground(new Color(250, 30, 40));
    dailyGraph.setBackground(new Color(100, 40, 200));
    //text Manip.
    prediction.setLineWrap(true);
    priceUpdate.setLineWrap(true);
    //scrolling
    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //main splitpane config.
    mainConsoleBackdrop.setOneTouchExpandable(true);
    mainConsoleBackdrop.setResizeWeight(.85);
    //placement and Layout
    //GraphLayout
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(dailyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(weeklyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    dataOut.setRightComponent(predictionScroll);
    //consoleData layout
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalBuy);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalSell);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(buySell);
    finalPricesLay.add(finalPricesLabels);
    finalPricesLay.add(Box.createVerticalStrut(10));
    finalPricesLay.add(weeklySelect);
    finalPricesLay.add(dailySelect);
    finalPricesLay.add(priceUScroll);
    dataOut.setLeftComponent(finalPricesLay);
    mainConsoleBackdrop.setTopComponent(graphs);
    mainConsoleBackdrop.setBottomComponent(dataOut);
    getContentPane().add(mainConsoleBackdrop);
    getContentPane().add(mainSelect, BorderLayout.NORTH);
    //visibility
    // CSEFrame.setVisible(true);
    //return(CSEFrame);
    public void actionPerformed(ActionEvent e)
    getMonth();
    inputS = e.getActionCommand();
    FileReader newRead = null;
    try {
    newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
    proceed = true;
    catch(FileNotFoundException f)
    System.out.println("File not found");
    proceed = false;
    if(proceed)
    BufferedReader bufferedReader = new BufferedReader(newRead);
    scanner = new Scanner(bufferedReader);
    scanner.useDelimiter("\n");
    //starts daily analysis
    getPrice(scanner);
    //starts weekly analysis
    weekly(inputS);
    public void itemStateChanged(ItemEvent e)
    if(weeklySelect.isSelected())
    priceUpdateWeekly.setText("");
    finalPricesLay.remove(priceUScroll);
    finalPricesLay.add(priceUScrollW);
    finalPrices.updateUI();
    else
    priceUpdate.setText("");
    finalPricesLay.remove(priceUScrollW);
    finalPricesLay.add(priceUScroll);
    finalPrices.updateUI();
    public void weekly(String inputS)
    weekly = true;
    for(int x = 0; x >< 7; x++)
    dateToUse(month, day, year, (x+1));
    try
    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
    week[x] = new Scanner(weeklyBuffer);
    week[x].useDelimiter("\n");
    getPrice(week[x]);
    catch(FileNotFoundException f)
    JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
    weekly = false;
    dateReset();
    public void getPrice(Scanner scanner)
    while(scanner.hasNextLine())
    //puts into string the next scan token
    String s = scanner.next();
    //takes the scan toke above and puts it into an editable enviroment
    String [] data = s.split("\\s");
    for(position = 0; position < data.length; position++)
    //Scanner test to make sure loop can finish, otherwise "no such line" error
    if(scanner.hasNextLine()==false)
    scanner.close();
    break;
    /*Starts data orignazation by reading from each perspective field
    * 1 = day
    * 2 = day of month
    * 3 = month
    * 4 = year
    if(position == 0 && weekly == false)
    String dayFromFile = data[position];
    int dayNum = Integer.parseInt(dayFromFile);
    priceUpdate.append(days[dayNum-1] +" ");
    else if(position == 1 && weekly == false )
    priceUpdate.append(data[position] + "/");
    else if(position == 2 && weekly == false)
    priceUpdate.append(data[position] + "/");
    else if(position == 3 && weekly == false)
    priceUpdate.append(data[position] +"\n");
    //if it is in [buy] area, it prints and computes
    else if(position == 7)
    //obtains string for buy price and stores it, then prints it
    String buy = data[position];
    if(weekly == false)
    priceUpdate.append("Buy: " +buy +"\n" );
    //converts buy to string
    currentBuyPrice = Integer.parseInt(buy);
    //eliminates problems caused by no data from server- makes the price 0
    if(currentBuyPrice < 0)
    currentBuyPrice = 0;
    //if it is greater it adds
    if(currentBuyPrice > buyPrice)
    buyPrice += currentBuyPrice;
    //if it is equal [there is no change] then it does nothing
    if(currentBuyPrice == buyPrice)
    buyPrice +=0;
    //if there is a drop, it subtracts
    else
    buyPrice -= currentBuyPrice;
    //if it is in [sell] area, it prints, and resets the position to zero because line is over
    else if(position == 8)
    //puts sell data into string and prints it
    String sell = data[position];
    if(weekly == false)
    priceUpdate.append("Sell: " + sell +"\n");
    //turns sell data into int.
    currentSellPrice = Integer.valueOf(sell).intValue();;
    //gets rid of problems caused by no data on server side- makes it 0
    if(currentSellPrice < 0)
    currentSellPrice = 0;
    //adds if there is an increase
    if(currentSellPrice > sellPrice)
    sellPrice += currentSellPrice;
    //does nothing if it is the same
    if(currentSellPrice == sellPrice)
    sellPrice +=0;
    //subtracts if there is drop
    else
    sellPrice -= currentSellPrice;
    //further protection against "No such line" and moves it down
    if(scanner.hasNextLine() == true)
    scanner.nextLine();
    //if scanner is finished, prints out all lines
    if(scanner.hasNextLine() == false && weekly == false)
    finalBuy.setText("Net Buy Price Change: "+buyPrice);
    finalSell.setText("Net Sell Price Change: " +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    else if(scanner.hasNextLine() == false && weekly == true)
    priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    dayOfWeek++;
    if(dayOfWeek > 6)
    dayOfWeek = 0;
    public void getMonth()
    for(int x=0; x < monthCheck.length; x++)
    if(month == monthCheck[x])
    monthS = (x+1);
    x = monthCheck.length;
    public void dateToUse(int month, int day, int year, int increment)
    //set day of source
    dayS = (day - increment);
    //if day of source is less then O then we have moved to another month
    if(dayS <= 0)
    //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
    int incrementDay = increment - day;
    //decrements month
    monthS--;
    //if month is less then zero, then we have moved into another year and month has become 12
    if(monthS <= 0)
    yearS--;
    monthS = 12;
    //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
    if(month == 3)
    dayS = 28 - incrementDay;
    else if(month == 5 || month == 7)
    dayS = 29 - incrementDay;
    else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
    dayS = 31 - incrementDay;
    else
    dayS = 30 - incrementDay;
    //resets the source date to the current date once data from the week has been reached
    public void dateReset()
    dayS = day;
    monthS = month;
    yearS = year;
    public void init()
    //JFrame frame = new CSEFrameSet();
    // this.setContentPane(CSEFrameSet());
    CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }Message was edited by:
    Cybergasm

  • Help please, not able to load images in a subclass of a japplet

    I've created this board for a project, but now I am stuck, I cannot seem to get images to appear, instead they come up as a nullpointerexception:
    public class Board extends JLayeredPane implements MouseListener, MouseMotionListener{
         private Container contentPane;
         private JLayeredPane jlp;     
         private boolean pieceSelected;
         private timepanel time;
         Image bimage;
         ImageIcon board;
         JLabel brd;
         Image pimage;
         ImageIcon piece;
         JLabel pce;
         private Graphics g;
         private pieceLayout pieces;
         private String piecename;
         private JLabel jl;
         boolean selected;
         private int offset;
         boolean changepos;
         boolean moving;
         private int brdwidth;
         private int brdheight;
         private Timer countdown;
         private updateTimer ut;
         private String cb;
         private clientinterface ci;
         private JFrame j;
         private int playerturn;
         public Board(clientinterface ci, JFrame j, Hashtable images, ArrayList names,
         ImageIcon brdicon, URL cb)
              j.setSize(500,450);
              countdown = new Timer();
              selected = false;
              jlp = this;
              jlp.setPreferredSize(new Dimension(500, 450));
              changepos = false;
              //contentPane = getContentPane();
              //this.setPreferredSize(new Dimension(500,400));
              jlp.setBounds(0,0,500,450);
              jlp.setLocation(0,0);
              jlp.setOpaque(true);
              jlp.setLayout(null);
              System.out.println(this.getSize() + "(((())))" );
              if(j.getWidth() > 400)
                   offset = j.getWidth() - 400;
              else
                   offset = 0;
              System.out.println("Width is: " +  j.getWidth() + " height: " + j.getHeight());     
              brdwidth = j.getWidth()-offset;
              brdheight = j.getHeight();
              System.out.println(images.size());     
              System.out.println(j.getWidth() + " " + j.getHeight() + " " + offset);
              brd = new JLabel(brdicon);
              brd.setBounds(0,0,j.getWidth()-offset, j.getHeight());
              brd.setSize(new Dimension(400,400));
              brd.setLocation(0,0);
              brd.setOpaque(true);
              jlp.add(brd, new Integer(-5));
              jlp.setBounds(0,0,j.getWidth(), j.getHeight());
              jlp.setVisible(true);
              time = new timepanel(jlp);
              time.setLocation(j.getWidth()-offset, 0);
              System.out.println(images.toString() + "++++++++");
              pieces = new pieceLayout(jlp, j.getWidth()-offset, names, cb);
              pieces.setLocation(0,0);
              pieces.setPreferredSize(new Dimension(400,400));
              pieces.setBounds(0,0,400,400);
              pieces.setVisible(true);
              time.setBounds(400,0, 100, 400);
              time.setVisible(true);
              ut = new updateTimer(time);
              jlp.add(pieces, new Integer(2));
              jlp.add(time, new Integer(2));
              //this.add(jlp);
              j.setLayeredPane(jlp);
              addMouseMotionListener(this);
              addMouseListener(this);
              //j.getContentPane().add(jlp);
              //j.setContentPane(this);
              j.validate();
              //j.getContentPane().setLayout(null);
              //j.setContentPane(this);
              j.paintAll(j.getGraphics());
         public void run()
              //this.repaint();
              this.paintAll(this.getGraphics());
              time.repaint();
         public void mouseDragged(MouseEvent e)
              JLabel temp;
              moving = true;
              //pce.setLocation(e.getX(), e.getY());
              //pieces.getPiece(pieces.translatecoords(e.getX(),e.getY())).setLocation(e.getX(),e.getY());
              int piecepos = pieces.translatecoords(e.getX(), e.getY());
              /*if(pieces.hasPiece(piecepos) && moving)
                   pieces.setSelected(piecepos);
                   temp = pieces.getPiece(piecepos);
                   //pieces.movePiece(e.getX(), e.getY());
                   temp.setLocation(e.getX(), e.getY());
              //this.repaint();
         public void mouseClicked(MouseEvent e)
              Point xpoin;
              System.out.println("Hello, clicked");
              /*pce.setLocation(e.getX(), e.getY());
              Point p = pce.getLocation();
              System.out.println(p.toString());*/
              System.out.println("\n" + e.getX() + " " + e.getY());
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mouseReleased(MouseEvent e)
              if(selected)
                   Point xp;
                   int x = e.getX();
                   int y = e.getY();
                   int bp = pieces.translatecoords(x,y);
                   xp = pieces.posToPoint(bp);
                   pieces.snapToSquare(xp.x, xp.y, bp);
                   selected = false;
                   moving = false;
                   //pieces.updateBoard(bp, piecename);
         public void mouseMoved(MouseEvent e)
         public void mousePressed(MouseEvent e)
              Point xpoin;
              int pos = pieces.translatecoords(e.getX(),e.getY());
              System.out.println("\n" + pieces.translatecoords(e.getX(),e.getY()));
              if(pieces.hasPiece(pos, e.getX(), e.getY()))
                        piecename = pieces.getName(pos);
                        System.out.println("Found a piece!");
                        pieces.setSelected(pos);
                        xpoin = pieces.posToPoint(pos);
                        selected = true;
         public void paintComponent(Graphics g)
              //super.paintComponents(g);
              //System.out.println("Painting");
              time.repaint();
         public void start()
              countdown.schedule(ut, 0, 1000);
         public void setupBoard()
                   //setSize(getSize().width < 400 ? 400 : getSize().width,
                   //getSize().height < 400 ? 400 : getSize().height);
                   //getLayeredPane().add(brd, new Integer(-5));
         public void sendInfo(String info)
              //parse information
         public class pieceLayout extends JLayeredPane
              JLabel pce1;
              private JLabel selected;
              private Hashtable pieceList;
              private ArrayList names;
              private int width;
              private Hashtable piecesOnBoard;
              private char boardstate[]= {'R','N','B','Q','K','B','N','R',
                                                 'P','P','P','P','P','P','P','P',
                                                 'p','p','p','p','p','p','p','p',
                                                 'r','n','b','q','k','b','n','r'
              private String posnm[]       = {
                                                       "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
                                                       "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
                                                       "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
                                                       "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
                                                       "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
                                                       "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
                                                       "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
                                                       "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"
              JLayeredPane thePane;
              private Hashtable ht;
              private Hashtable board;
              private Hashtable b2p;
              private Hashtable p2b;
              private Hashtable piecePos;
              private Hashtable objToName;
              private Hashtable posnames;
              private URL codebase;
              public pieceLayout(JLayeredPane p, int twidth, ArrayList pnames, URL cb)
                   pieceList = new Hashtable(20);
                   codebase = cb;
                   names = pnames;
                   selected = new JLabel();
                   piecesOnBoard = new Hashtable(32);
                   ht = new Hashtable(6);
                   board = new Hashtable(64);
                   b2p = new Hashtable(64);
                   p2b = new Hashtable(64);
                   piecePos = new Hashtable(64);
                   objToName = new Hashtable(32);
                   posnames = new Hashtable(64);
                   fillnames();
                   getImages();
                   setImages();
                   width = twidth;
                   thePane = p;
                   System.out.println(piecesOnBoard.size());
                   showBoard();
              private void fillnames()
                   int size = posnm.length;
                   for(int i = 0; i < size; i++ )
                        posnames.put(new Integer(i), new String(posnm));
                   showPos();
              private void getImages()
                   Pattern p = Pattern.compile(".+\\.GIF");
                   Pattern p1 = Pattern.compile(".+\\.gif");
                   Pattern p2 = Pattern.compile("board.+");
                   Pattern p3 = Pattern.compile(".+board.+");
                   for(int i = 0; i < names.size(); i++)
                        Matcher m = p.matcher((String)names.get(i));
                        Matcher m1 = p1.matcher((String)names.get(i));
                        Matcher m2 = p2.matcher((String)names.get(i));
                        Matcher m3 = p3.matcher((String)names.get(i));
                        if(m.matches() || m1.matches())
                             //System.out.println("Files are: " + dirs[i].getName());
                             if(!m2.matches() && !m3.matches())
                                  String piecename = new String((String)names.get(i));
                                  //     System.out.println("Files were: " + dirs[i].getName());
                                  Image tpimage = Toolkit.getDefaultToolkit().createImage(piecename);
                                  Image pimage = tpimage.getScaledInstance(35,35, Image.SCALE_DEFAULT);
                                  //ImageIcon piece = new ImageIcon(pimage);
                                  pieceList.put(new String(piecename), pimage);
                   System.out.println(pieceList.toString());
                   System.out.println(pieceList.size() + "((**))(())");
              private void setImages()
                   int listsize = names.size();
                   if(!pieceList.isEmpty())
                        int index = 0;
                        for(int i = 0; i < listsize; i++)
                             String pieceName = (String)names.get(index);
                             String hKey = getHashKey(pieceName);
                             System.out.println(hKey);
                             if((hKey.compareTo("blackking") == 0) || (hKey.compareTo("blackqueen") == 0) ||
                             (hKey.compareTo("whiteking") == 0) || (hKey.compareTo("whitequeen") == 0))
                                  Image tpiece = (Image)pieceList.get(new String(hKey));
                                  ImageIcon piece = new ImageIcon(tpiece);
                                  pce1 = new JLabel(piece);
                                  piecesOnBoard.put(new String(hKey), pce1);
                             else
                                  System.out.println("multiples " + hKey);
                                  createMultiples(hKey, pieceName);
                             if(i == listsize-1)
                                  index = 0;
                             else
                                  index++;
                             System.out.println(pieceName + " " + hKey + "1234567890");
              private void createMultiples(String key, String hname)
                   JLabel piecet;
                   String name;
                   if(key == "blackpawn" || key == "whitepawn")
                        name = key;
                        for(int i = 0; i < 8; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                   else if(key == "blackknight" || key == "whiteknight")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackbishop" || key == "whitebishop")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             System.out.println(piece.toString());
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackrook" || key == "whiterook")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
    Hopefully this will format alright, but my question is, is that why is it giving me this error... it happens in the create multiples function(the last function in this code block) this is a jlayeredpane which is called by a JApplet. Any ideas on the loading? Its in the getImages() fuction.

    These are the lines it dies on.... the System.out.println(piece.toString()); precisely. I don't know if I am not getting the images from the directory right... or if I need to make sure this is in a JAR file or not.
    {                    name = key;                    for(int i = 0; i < 2; i++)                    {                         System.out.println(name+i);                         String tempname = name+i;                         Image piece = (Image)pieceList.get(new String(name));                         System.out.println(piece.toString());                         ImageIcon pieces = new ImageIcon(piece);                         piecet = new JLabel(pieces);                         piecesOnBoard.put(new String(tempname), piecet);                    }                    if(!ht.containsKey(new String(key)))                    {                         ht.put(new String(key+0), new Integer(0));                    }                    

  • Please help me...Why the buttons size change?

    Hi!!!
    I have a doubt with respect the buttons size, because with the following code i show 2 buttons that comprise the whole panel in a row:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class x1 extends JApplet {
    public void init() {
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel jp= new JPanel();
    jp.setBorder(new EmptyBorder(10,10,10,10));
    jp.setLayout(new GridLayout(1,2,5,5));
    JButton b1= new JButton("Button 1");
    jp.add(b1);
    JButton b2= new JButton("Button 2");
    jp.add(b2);
    contentPane.add(jp,BorderLayout.NORTH);
    But when i do other separated class with the buttons creation, my buttons appear in the center without comprising the whole panel in a rengl�n.....why happen it?.....i would like to obtain the same effect like the first code....how can i reach that?.....
    This is the applet code when i do the separated class with the buttons creation applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class x2 extends JApplet {
    public void init() {
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(new jbuttons(),BorderLayout.NORTH);
    class jbuttons extends JPanel {
    public jbuttons() {
    JPanel jp= new JPanel();
    jp.setBorder(new EmptyBorder(10,10,10,10));
    jp.setLayout(new GridLayout(1,2,5,5));
    JButton b1= new JButton("Button 1");
    jp.add(b1);
    JButton b2= new JButton("Button 2");
    jp.add(b2);
    add(jp);
    Could somebody help me please?.....Thanks in advance....
    Mary

    Mary,
    Your second class (jbuttons) actually contains TWO panels: "this" as well as the jp panel. The jp panel is in this case unnecessary.
    Although the sizing of the jp panel is set correctly, the "this" panel is still set to "flow" layout and will not give you the desired result.
    Try rewriting your second class this way:
    class jbuttons extends JPanel {
    public jbuttons() {
    this.setBorder(new EmptyBorder(10,10,10,10));
    this.setLayout(new GridLayout(1,2,5,5));
    JButton b1= new JButton("Button 1");
    this.add(b1);
    JButton b2= new JButton("Button 2");
    this.add(b2);
    Hope this helps!
    Steve

  • How to set the size of a textPane

    I have the following text pane:
         private JTextPane objTPOutput = new JTextPane ();
    /* Output information to the Text Area */
                   objTPOutput.setText("Student Name = " + name +
                                            "\nClass Name = " + className +
                                            "\nCampus Name = " + campusName +
                                            "\nClass Start = " + start +
                                            "\nClass End = " + end +
                                            "\nNumber of Credits = " + numCredit +
                                            "\nCost Per Credit = " + cost +
                                            "\nCost of Class = " + (cost * numCredit));And I want to make it so that I can set it's size so that all the text fits in the panel. For instance, be able to set it's height to a static number.
    How would I go about doing this?

    It is actually in an applet, and JPanel. Let me show you my code so that you can see it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
         Class: MetroClass
    public class MetroClass extends JApplet{
         /* Create Applet Controls used */
         private JTextField objTFName = new JTextField();
         private JComboBox objCBClass = new JComboBox();
         private JComboBox objCBCampus = new JComboBox();
         private JTextField objTFStart = new JTextField();
         private JTextField objTFEnd = new JTextField();
         private JTextField objTFCost = new JTextField();
         private JTextField objTFNumCredit = new JTextField();
         private JButton objBtnCalculate = new JButton("Calculate");
         private JTextPane objTPOutput = new JTextPane ();
              Method: init()
              Initializes all controls on the applet.
         public void init(){
              /* Create Panel to store all controls */
              JPanel objPanel = new JPanel(new GridLayout(10,2));
              /* Add Items to Drop Down List */
              objCBClass.addItem("ICS 140");
              objCBClass.addItem("ICS 141");
              objCBClass.addItem("ICS 240");
              objCBClass.addItem("ICS 340");
              /* Add Items to Drop Down List */
              objCBCampus.addItem("St. Paul");
              objCBCampus.addItem("Midway");
              objCBCampus.addItem("Minneapolis");
              /* Set the Text Alignment to Left*/
              objTFName.setHorizontalAlignment(JTextField.LEFT);
              objTFStart.setHorizontalAlignment(JTextField.LEFT);
              objTFEnd.setHorizontalAlignment(JTextField.LEFT);
              objTFCost.setHorizontalAlignment(JTextField.LEFT);
              objTFNumCredit.setHorizontalAlignment(JTextField.LEFT);
              /* Add all the controls to the panel*/
              objPanel.add(new JLabel("Enter your Name"));
              objPanel.add(objTFName);
              objPanel.add(new JLabel("Select the class"));
              objPanel.add(objCBClass);
              objPanel.add(new JLabel("Select the Campus"));
              objPanel.add(objCBCampus);
              objPanel.add(new JLabel("Class Start"));
              objPanel.add(objTFStart);
              objPanel.add(new JLabel("Class End"));
              objPanel.add(objTFEnd);
              objPanel.add(new JLabel("What is the cost per Credit"));
              objPanel.add(objTFCost);
              objPanel.add(new JLabel("How many credits"));
              objPanel.add(objTFNumCredit);
              objPanel.add(new JLabel(""));
              objPanel.add(objBtnCalculate);
              objPanel.add(new JLabel(""));
              objPanel.add(objTPOutput);
              /* Add the panel to the applet */
              add(objPanel,BorderLayout.CENTER);
              /* Add a event handler to listen for the button press*/
              objBtnCalculate.addActionListener(new ButtonListener());
              Class: ButtonListener
         private class ButtonListener implements ActionListener {
                   Method: actionPerformed()
                   This method listens for a button click.  Upon a button click
                   the values in the text boxes and drop down list are acquired,
                   and displayed in a text area.
              public void actionPerformed(ActionEvent e){
                   /* Method Variables*/
                   int numCredit = 0;
                   double cost = 0.0;
                   String name = "";
                   String start = "";
                   String end = "";
                   String className = "";
                   String campusName = "";
                   /* Get the control values */
                   numCredit = Integer.parseInt(objTFNumCredit.getText());
                   cost = Double.parseDouble(objTFCost.getText());
                   name = objTFName.getText();
                   start = objTFStart.getText();
                   end = objTFEnd.getText();
                   className = objCBClass.getSelectedItem().toString();
                   campusName = objCBCampus.getSelectedItem().toString();
                   objTPOutput.pane.setPreferredSize(new Dimension(40, 40));
                   /* Outut information to the Text Area */
                   objTPOutput.setText("Student Name = " + name +
                                            "\nClass Name = " + className +
                                            "\nCampus Name = " + campusName +
                                            "\nClass Start = " + start +
                                            "\nClass End = " + end +
                                            "\nNumber of Credits = " + numCredit +
                                            "\nCost Per Credit = " + cost +
                                            "\nCost of Class = " + (cost * numCredit));
    }

  • Applet size to 100% of frame

    We have a Swing JApplet containing a JTree in a JScrollPane that's part of an HTML frameset. The applet needs to fill 100% of its frame on loading and then resize with the frame. I figured then the best way to do this would be to set width and height to 100% so the browser could handle it. This works great for Netscape, but IE seems to either add a vertical scrollbar or leave whitespace for it to the right of the applet and not fill the frame completely.
    Is there some way around this or some better way to make JApplet size and resize correctly?
    Thanks!

    Sure! FYI, we use JavaScript document.write() calls to output the HTML for the frameset, but I removed so it would fit here better. The code in question is part of navigation.jsp (see below):
    <FRAMESET id="MainFrameLayout" name="MainFrameLayout" rows="60,*" border="0" frameborder="0">
    <FRAME name="banner" id="banner" src="banner_ae.html" scrolling="no" frameborder="0" marginheight="0" marginwidth="0">
    <FRAMESET id="FrameLayout" name="FrameLayout" border="0" frameborder="0" cols="180,*">
    <FRAME name="menu" id="menu" src="navigation.jsp" frameborder="0" marginheight="0" marginwidth="0" style="border: 1px solid #acacac;">
    <FRAMESET id="RtFrameLayout" name="RtFrameLayout" rows="0,0,*" border="0" frameborder="0">
    <FRAME name="ssh" id="ssh" src="/blank.html" scrolling="auto" frameborder="0" marginheight="0" marginwidth="0">
    <FRAME name="wiz" id="wiz" src="/blank.html" scrolling="auto" frameborder="0" marginheight="0" marginwidth="0">
    <FRAME name="text" id="text" src="action/homePage" scrolling="auto" frameborder="0" marginheight="0" marginwidth="0">
    </FRAMESET>
    </FRAMESET>
    </FRAMESET>

  • JApplet does not resize correctly

    Hello,
    I'm trying to practice with JLayeredPane in JApplet.
    The problem is that when i resize the applet JButton b3 is painted "as a background", and still works as a JButton.
    Why doesn't it resize correctly as the other JComponent do?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JLayeredPaneDemo extends JApplet {
         public void paint(Graphics g) {
              final JLabel l1 = new JLabel("LABEL 1",JLabel.CENTER);
              final JLabel l2 = new JLabel("LABEL 2",JLabel.CENTER);
              final JLabel l3 = new JLabel("LABEL 3",JLabel.CENTER);
              resize(400,300);
              l1.setOpaque(true);
              l1.setBackground(Color.blue);
              l1.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l2.setOpaque(true);
              l2.setBackground(Color.green);
              l2.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l3.setOpaque(true);
              l3.setBackground(Color.yellow);
              l3.setBorder(BorderFactory.createLineBorder(Color.black,2));
              l1.setBounds(0,0,100,100);
              l2.setBounds(30,30,100,100);
              l3.setBounds(60,60,100,100);
              getLayeredPane().add(l1,new Integer(1));
              getLayeredPane().add(l2,new Integer(2));
              getLayeredPane().add(l3,new Integer(3));
              JButton b1 = new JButton("LABEL 1 ON TOP");
              JButton b2 = new JButton("LABEL 2 ON TOP");
              JButton b3 = new JButton("LABEL 3 ON TOP");
              b1.setBounds(220,0,150,40);
              b2.setBounds(220,40,150,40);
              b3.setBounds(220,80,150,40);
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l2)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l2)+1));
                        else
                             getLayeredPane().setLayer(l1,new Integer(getLayeredPane().getLayer(l3)+1));
              b2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l3))
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l2,new Integer(getLayeredPane().getLayer(l3)+1));
              b3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(getLayeredPane().getLayer(l1)>getLayeredPane().getLayer(l2))
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l1)+1));
                        else
                             getLayeredPane().setLayer(l3,new Integer(getLayeredPane().getLayer(l2)+1));
              add(b1);
              add(b2);
              add(b3);
    }If i use the init() method instead of the paint(Graphics g) method JButton b3 is painted as large as possible since the beginning.
    thanx in advance :)

    Swing related questions should be posted in the Swing forum.
    If i use the init() method instead of the paint(Graphics g) methodWell, thats the proper way to write a Swing applet. The code for building the GUI should be in the init() method. You never need to override the paint() method of the JApplet.
    Components will not be automatically resized when the size of the applet changes. A layered pane does not use a layout manager, therefore it is up to you to manually change the size of each component. You can add a ComponentListener to the applet to be notified when the size changes.

  • JApplet and the Images --PLEASE reply fast

    the problem is i am trying to put a .gif image into JApplet. no matter what i do it just DOESNT WANNA WORK! can anyone please post an example of working one?

    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.lang.Object.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.LineBorder.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    import java.util.Random;
    public class MoveTheSquare  extends JApplet implements ActionListener
         public static int size = 100;
           public     static        int life = 80;
            public     static       int eneLife=50;
         private AudioClip ohboy2= getAudioClip(getDocumentBase(), "ohboy2.wav");
    //      public Image bricks = getImage(getDocumentBase(),"bricks.gif");
        public static void main(String[] args)
            ApplicationFrame frame = new ApplicationFrame();
            frame.setBounds(50, 50, 900, 900);
            frame.setVisible(true);
            new ApplicationFrame();
        private static class ApplicationFrame extends JFrame
            public ApplicationFrame()
            super("Move the Sticky Figure!");
               // setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(500, 600);
                JPanel content = new JPanel();
                ((JPanel) getContentPane()).setOpaque(true);
               // new WindowListener(1);
                 ImageIcon bricks = new ImageIcon("bricks.gif");
                 JLabel backlabel = new JLabel(bricks);
                getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
                backlabel.setBounds(0,0,20000,2560);
                setLocation(500,600);
                  //WindowListener1 = new WindowAdapter() {
                  //public void windowClosing(WindowEvent e) {
                  //System.exit(0);
                  //setVisible(true);
                initUi();
            private void initUi()
                Container cp = getContentPane();
                Image img = getImage(getDocumentBase(), "bricks.gif" );
                cp.add(new MyPanel(img));
                cp.setLayout( new BorderLayout(0, 10) );
              //   addWindowListener1();
                cp.add( new JLabel(" Move the Sticky with the arrow keys:"), BorderLayout.NORTH );
                // Create the playing board and the squar
                Square sq = new Square( new Point(100, 100), 10 );
                Board board = new Board(sq);
                cp.add( board, BorderLayout.CENTER );
                // Register Key Bindings to move the square around. Read about the
                InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                ActionMap am = getRootPane().getActionMap();
                // The LEFT arrow will move the suare to pixels two the left
                MoveSquareAction moveLeft = new MoveSquareAction(board, -3, 0);
                KeyStroke keyStrokeLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
                im.put( keyStrokeLeft, "left" );
                am.put( "left", moveLeft );
                // The RIGHT arrow will move the suare to pixels two the right
                MoveSquareAction moveRight = new MoveSquareAction(board, 3, 0);
                KeyStroke keyStrokeRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
                im.put( keyStrokeRight, "right" );
                am.put( "right", moveRight );
                // The UP arrow will move the suare two pixels up
                MoveSquareAction moveUp = new MoveSquareAction(board, 0, -3);
                KeyStroke keyStrokeUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
                im.put( keyStrokeUp, "up" );
                am.put( "up", moveUp );
                // The DOWN arrow will move the suare two pixels down
                MoveSquareAction moveDown = new MoveSquareAction(board, 0, 3);
                KeyStroke keyStrokeDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
                im.put( keyStrokeDown, "down" );
                am.put( "down", moveDown );
                pack();
        // Class that represents the playing board
        private static class Board extends JPanel
              private Square square;
            public Board(Square sq)
                square = sq;
                setOpaque(true);
                setBorder( new LineBorder(Color.GREEN));
            int x=1;
            public void  paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage( img, currentX, currentY, this );
                   if (x==1)
                Point location = square.getLocation();
                String coordX = String.valueOf(location.x);
                String coordY = String.valueOf(location.y);
                String slife = String.valueOf(life);
                    //g.drawImage(bricks, 0, 0, 500, 16, this);
                  g.setColor(Color.red);
                   g.fillRect(240,240,250,250);
                   g.setColor(Color.GREEN);
                   g.fillRect(0,00,40,40);
                   g.setColor(Color.black);
                g.drawLine(location.x-5,location.y+5,location.x,location.y);
                   g.drawLine(location.x+5,location.y+5,location.x,location.y);
                   g.drawLine(location.x,location.y,location.x,location.y-7);
                   g.drawLine(location.x-4,location.y-4,location.x,location.y-7);
                   g.drawLine(location.x+4,location.y-4,location.x,location.y-7);
                   g.fillOval(location.x-3,location.y-15,8,8);
                   g.drawString(coordX,20,20);
                   g.drawString(coordY,20,30);
                   g.drawString("YOUR LIFE:", 00,70);
                   g.drawString(slife,70,70);
                   Random generator = new Random();
                  int takeaway = generator.nextInt(25);
                     int fight = generator.nextInt(50);
                   if (fight==4)
                  x=0;
                 life= life-takeaway;
                  JOptionPane.showMessageDialog(null, "YOU ARE BEING ATTACKED!!!!! YOU LOST HEALTH:" +takeaway);
                    slife = String.valueOf(life);
                 g.drawString(slife,70,70);
                 if (life<=0)
                 JOptionPane.showMessageDialog(null, "you lose. bye.");
                 System.exit(0);
                 if (((location.x>=240) && (location.y>=240)) &&((location.x<=490) && (location.y<=490)))
                 JOptionPane.showMessageDialog(null, "you Win! bye.");
                 System.exit(0);
           Random generator = new Random();
           int fight = generator.nextInt(50);
           if (fight==1)
           x=1;
            public Square getSquare()
                return square;
        // The Action class that implements moving the square:
        private static class MoveSquareAction extends AbstractAction
            // The board this action acts on:
            Board board;
            // The number of pixels to move in the X- and Y-directions:
            int pixelsToMoveX;
            int pixelsToMoveY;
            public MoveSquareAction(Board board, int pixelsToMoveX, int pixelsToMoveY)
                this.board = board;
                this.pixelsToMoveX = pixelsToMoveX;
                this.pixelsToMoveY = pixelsToMoveY;
            public void actionPerformed(ActionEvent e)
                // Move the square and repaint the board:
                board.getSquare().moveX(pixelsToMoveX);
                board.getSquare().moveY(pixelsToMoveY);
                board.repaint();
        // Class that represents the black square we move around
        private static class Square
            private Point     location;
            private int          size;
            public Square(Point loc, int size)
                location = loc;
                this.size = size;
            public Point getLocation()
                return location;
            public int getSize()
                return size;
            public void moveX(int pixels)
                location.x += pixels;
            public void moveY(int pixels)
                location.y += pixels;
        public void actionPerformed(ActionEvent e)
                 ohboy2.loop();//sound
    }

  • Caching images in a JApplet

    I have a JApplet here:
    http://www.jujubees.org/java_photo_album/photoAlbum.html
    the code is coming along well but I have one major problem. The images seem to take for ever to download even with a high speed cable connection (so god only knows how long a dial up would take). What technique can I use to make sure the images are being cached in the web browser? Also is there a way to check and see if the browser has cached a certain image? If you want to see the code then I could post it.

    I have a JApplet here:
    http://www.jujubees.org/java_photo_album/photoAlbum.htm
    the code is coming along well but I have one major
    problem. The images seem to take for ever to download
    even with a high speed cable connection (so god only
    knows how long a dial up would take). What technique
    can I use to make sure the images are being cached in
    the web browser? Also is there a way to check and see
    if the browser has cached a certain image? If you want
    to see the code then I could post it.Well you could check to see if the images are being cached by printing out the details of your images, byte size and so on. If you want the browser to cache all the images what you could do is feed the location of the images into the applet, with a parameter for instance, then create a thread that iterates over the images in the directory and loads them into a hashtable of some kind. So the rendering would be faster. Or put them into a .jar/.zip, would be faster. You don't have to wait for all the images to load to display the first one.
    Unless you are manually coding the images in your code you can be fairly certain that the browser is not going to. Perhaps with advanced browsers like Opera, but even then, no.
    See ya
    Michael

  • JScrolPane in JApplet

    Hi,
    I have written a JApplet that investigates some properties of pseudo random functions. After running the JApplet, the results are put on the screen. These results are put in a table.The width of that table depends of the user input. In most cases, the table is widther that the width of the applet. I want to add a JScrollbar. In the tutorials I found a lot about JScrollPane. JScrollPane want a component, but I cannot give the JApplet itself, since the JScrollPane is part of the JApplet. Hope someone can help me.
    You can see a screenshot of the situation here:
    http://www.josroseboom.nl/screenshot.jpg
    The code that paints the table is:
        public void paint(Graphics g)
            super.paint(g);
            debug(" string waarde g:" + g.toString());
            if(resultMode)
                int starty = 15;
                int regelhoogte = 15; //height of a line
                String[] temp,temp1;
                for(int i = 0;i<stringResultaten.size();i++)
                    temp = (String[])(stringResultaten.get(i));
                    for(int j = 0;j<temp.length;j++)
                        temp1 = temp[j].split("\t");
                        for(int k=0;k<temp1.length;k++)
                            g.drawString(temp1[k],10+75*k,starty+regelhoogte*j);
                    starty += (temp.length+2)*regelhoogte;
        } -----

    Thanks for helping me. I tried to do what you suggested, but unfortunatly it still does not work. After trying a bit, I got the results on the screen, but again as in http://www.josroseboom.nl/screenshot.jpg , the screen is not width enough. If you like to see the entire applet: http://www.josroseboom.nl/PseudoRandomClusteringApplet.htm (select SHA or MD5, fill in a number and press start). As you suggested, I have made a class that extends JPanel:
    public class ResultaatPane extends JPanel
        Vector stringResultaten;
        boolean DEBUG = true;
        public ResultaatPane(Vector stringResultaten)
            this.stringResultaten = stringResultaten;
        public void paintComponent(Graphics g)
            debug("paintcomponent wordt aangeroepen");
            int starty = 15;
            int regelhoogte = 15; //height of a line
            String[] temp,temp1;
            for(int i = 0;i<stringResultaten.size();i++)
                temp = (String[])(stringResultaten.get(i));
                for(int j = 0;j<temp.length;j++)
                    temp1 = temp[j].split("\t");
                    for(int k=0;k<temp1.length;k++)
                        g.drawString(temp1[k],10+75*k,starty+regelhoogte*j);
                starty += (temp.length+2)*regelhoogte;
        public void debug(String s)
            if(DEBUG)
                System.out.println(s);
    {code}
    When the computations are done, you can push a button to see the results:
    {code:java}
            if(e.getSource()==naarResultaat)
                stringResultaten = progressie.getStringResultaten();   
                resultaat = new ResultaatPane(stringResultaten);
                res_scrollpane = new JScrollPane(resultaat);
                this.setContentPane(res_scrollpane);
                this.validate();
    {code}
    I hope someone knows, thanks in advance.
    Edited by: _Jos_ on Sep 20, 2007 9:35 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to make smooth hardware accelerated JApplet?

    Hi there ive made a game that extends JPanel and im using the paintComponent method to do my painting
    as far as i know JPanel is hardware accelerated by default bufferStrategy(2)
    ive put the JPanel in a JFrame and the game runs very smooth with ~62fps and cpu usage is <10%
    then i tried putting the JPanel in JApplet and opened it in firefoxbrowser and the fps says ~59fps and cpu usage ~30% but its super skippy and looks like its drawing incorrectly like some of the objects are displaced very far from where they are supposed to be some frames and drawn perfectly some other frames. What's happening? Is there anyway to fix this?
    Below is some code that for a JApplet and JFrame they both contain the JPanel and ive packed everything in a jar file that can be run as a desktopapp or japplet
    I've also tried add the JApplet directly into the JFrame but it seems the performance might go down a little (though im not sure how much)
    main extends JApplet
    RobotValkyrieAttack extends JPanel
    package RobotValkyrieAttack;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class main extends JApplet{
         static LinkedList<Image> listImage;
         //no JApplet constructor is allowed to be overrriden
         public void init(){ //called by the japplet container
              this.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              this.add(r);
              Thread t = new Thread(r);
              t.start();
              this.addKeyListener(r);
         public void loadImages(){
              //images
              listImage = new LinkedList<Image>();
              listImage.add( new ImageIcon(this.getClass().getResource("data/valkyrie0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/astroid0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/clouds0.jpg")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud1.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud2.png")).getImage() );
              MediaTracker mt = new MediaTracker(this);
              for(int i=0; i<listImage.size(); i++){
                   mt.addImage(listImage.get(i),0);
              try{
                   mt.waitForAll();
              catch(Exception ex){
                   ex.printStackTrace();
         public void update(Graphics g){
              this.paint(g);
         public static void main(String args[]){
              JFrame j = new JFrame();
              j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              j.setSize(1200,700);
              j.setLocationRelativeTo(null);
              main m = new main();
              m.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              j.add(r);
              Thread t = new Thread(r);
              t.start();
              j.addKeyListener(r);
              main m = new main();
              m.init();
              j.add(m);
              j.setVisible(true);
    }

    Before we begin, note that performance of Java graphics has always been a bit 'hit and miss' in the sense that the same box with the same hardware and Java version can show radically different FPS rates if the video driver is updated.
    For better help sooner, post an SSCCE.
    Applet SSCCEs that involve images are a problem. Normally I would invite creators of image based SSCCEs to hot-link to [images available off my site|http://pscode.org/media/#image], but an applet cannot hot-link to images. It will be necessary to generate the images in code, if you want much chance of people running the code. Note that very few people will follow a link to anywhere, or download any 'build zip' or similar, to help out on a problem.
    That code snippet as posted, had a number of things that seemed horrific.
    - A class called 'main'. O_o Better would be AppletRenderTest which is not only more descriptive, but also uses the common nomenclature for a class name.
    - Frame size 1200x700?! It pays to ensure any 'comparison' of applet and application is done at the same size and my screen size is 1024x768. Make it a lot smaller, like 800x600.
    - A Swing based Timer is more typically used for Swing animation, than a Thread/Runnable.
    - GUI construction should be done on the EDT.
    - This..
    //no JApplet constructor is allowed to be overrriden..is not only factually wrong, but also incorrectly spelt.
    I am not confident you are up to writing:
    - Test code (especially test code you intend others to help with)
    - GUIs
    - Animation code
    - Applets
    Or if you are capable of parts of that, of combining the 4.
    Are you confident?

  • Applet on mac wrong size

    Hi,
    I have a program as an applet (rather than JApplet for backward compatability on the mac), and i am debugging it on the macintosh. the applet contains a panel with a card layout, this has a panel as a menu and another panel which is a game that i have overridden the paint method to update graphics.
    The problem is is that the size is supposed to be 500 by 500 but whenever i run it always paints at about 30 by 60, no matter what size(), bounds() or location() i set. It is always set to the center aswell.
    I have made it using all swing components and it works fine, but my specification says it should be on a mac. Because of this i have had to change all components to old awt components, the functionallity seems to work, but painting is buggered.
    any ideas?
    chers

    Fixed it now, just put layout manager as null

Maybe you are looking for