How can I make a jbutton trigger by pressing "Enter" key? - jframe

Hello I have build a simple GUI game to guess a number between 0-100 and I have a button which the user clicks to check the number. I want the user to be able to press the key enter and execute the action of the button. I have looked around for a solution but cant seemed to find a answer for my problem :/
thank you in advance
package org.eclipse.wb.swt;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class JGuessinggame {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JGuessinggame window = new JGuessinggame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JGuessinggame() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 15));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblWwe = new JLabel("Welcome to the Magic Number Guessing game");
lblWwe.setFont(new Font("Segoe UI", Font.PLAIN, 15));
lblWwe.setBounds(56, 11, 333, 44);
frame.getContentPane().add(lblWwe);
JLabel lblGuessANumber = new JLabel("Guess a number between 0 - 100");
lblGuessANumber.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblGuessANumber.setBounds(100, 66, 215, 14);
frame.getContentPane().add(lblGuessANumber);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
});
textField.setBounds(159, 128, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblAnswer = new JLabel("");
lblAnswer.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblAnswer.setBounds(100, 174, 324, 29);
frame.getContentPane().add(lblAnswer);
Random ran = new Random();
int number;
number = (ran.nextInt(100)+1);
JButton btnCheck = new JButton("Check!");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
int guess = Integer.parseInt(textField.getText());
if(number>guess)
lblAnswer.setText("try higher!");
else if(number<guess)
lblAnswer.setText("try lower!");
else if(number==guess)
lblAnswer.setText("you guess correctly! , the magic number was "+number);
}catch(Exception exc){
exc.printStackTrace();
}
}
});
btnCheck.setBounds(159, 214, 89, 23);
frame.getContentPane().add(btnCheck);
}
}

Related

Exception in thread "main" java.lang.Error: Unresolved compilation problem: at QuizGame.main(QuizGame.java:83)

How can I solve this error occurred in VS-Code after I used implements in my code what's the error help me out
I just trying to make a project on QuizGame with the help of this YouTube channel:https://youtu.be/EMTkeefioMg
I tried everything but still getting the error many times please help me out with this code
import javax.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.plaf.FontUIResource;
public class QuizGame extends JFrame implements ActionListener {
JButton b1, b2;
QuizGame () //Constructor
{
setBounds(200, 100, 1000, 500);
getContentPane().setBackground(Color.WHITE);
setLayout(null);
/* ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("2021 project/Java project/GUI Programs/quizlogo.jpg"));
JLabel l1 = new JLabel(i1);
l1.setBounds(0, 0, 500, 500);
add(l1);*/
JLabel l2 = new JLabel("Quiz Game");
l2.setFont(new FontUIResource("Mongolian Baiti",Font.BOLD,
55));
l2.setForeground(Color.BLUE);
l2.setBounds(620, 40, 300, 45);
add(l2);
JLabel l3 = new JLabel("Enter Your Name:");
l3.setFont(new FontUIResource("Mongolian Baiti", Font.BOLD, 25));
l3.setForeground(Color.BLUE);
l3.setBounds(650, 180, 250, 45);
add(l3);
JTextField t1 = new JTextField();
t1.setBounds(625, 240, 250, 35);
t1.setFont(new FontUIResource("Times New Roman", Font.BOLD, 20));
add(t1);
b1 = new JButton("Rules");
b1.setBounds(600, 320, 120, 25);
b1.setBackground(new Color(30, 144, 254));
b1.setForeground(Color.WHITE);
b1.addActionListener(this);
add(b1);
b2 = new JButton("Exit");
b2.setBounds(800, 320, 120, 25);
b2.setBackground(new Color(255, 0, 0));
b2.setForeground(Color.WHITE);
b2.addActionListner(this);
add(b2);
setVisible(true);
}
public class Rules extends JFrame{
Rules(){
setBounds(200, 100, 1000, 500);
getContentPane().setBackground(Color.WHITE);
setLayout(null);
JLabel l1 = new JLabel("Welcome"+ username + "to Quiz Game");
l1.setBounds(50, 20, 700, 30);
add(l1);
setVisible(true);
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == b1){
}
else{
System.exit(0);
}
}
public static void main(String[] args){ //(Line 83)
new QuizGame(); //object created
}
}
After Java: Clean Java Language Server Workspace from Command Palette, here's a simple correction that makes your code show the first window at least:
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.plaf.FontUIResource;
public class QuizGame extends JFrame implements ActionListener {
JButton b1, b2;
JTextField t1;
QuizGame () //Constructor
{
setBounds(200, 100, 1000, 500);
getContentPane().setBackground(Color.WHITE);
setLayout(null);
/* ImageIcon i1 = new ImageIcon(ClassLoader.getSystemResource("2021 project/Java project/GUI Programs/quizlogo.jpg"));
JLabel l1 = new JLabel(i1);
l1.setBounds(0, 0, 500, 500);
add(l1);*/
JLabel l2 = new JLabel("Quiz Game");
l2.setFont(new FontUIResource("Mongolian Baiti",Font.BOLD,
55));
l2.setForeground(Color.BLUE);
l2.setBounds(620, 40, 300, 45);
add(l2);
JLabel l3 = new JLabel("Enter Your Name:");
l3.setFont(new FontUIResource("Mongolian Baiti", Font.BOLD, 25));
l3.setForeground(Color.BLUE);
l3.setBounds(650, 180, 250, 45);
add(l3);
t1 = new JTextField();
t1.setBounds(625, 240, 250, 35);
t1.setFont(new FontUIResource("Times New Roman", Font.BOLD, 20));
add(t1);
b1 = new JButton("Rules");
b1.setBounds(600, 320, 120, 25);
b1.setBackground(new Color(30, 144, 254));
b1.setForeground(Color.WHITE);
b1.addActionListener(this);
add(b1);
b2 = new JButton("Exit");
b2.setBounds(800, 320, 120, 25);
b2.setBackground(new Color(255, 0, 0));
b2.setForeground(Color.WHITE);
b2.addActionListener(this);
add(b2);
setVisible(true);
}
public class Rules extends JFrame{
Rules(){
setBounds(200, 100, 1000, 500);
getContentPane().setBackground(Color.WHITE);
setLayout(null);
String username=t1.getText();
JLabel l1 = new JLabel("Welcome" +username+"to Quiz Game");
l1.setBounds(50, 20, 700, 30);
add(l1);
setVisible(true);
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == b1){
}
else{
System.exit(0);
}
}
public static void main(String[] args){ //(Line 83)
new QuizGame(); //object created
}
}
The tutorial you referred is very explicit, and the author created the standalone rules.java to make code more succinct. Please follow the tutorial carefully and try again.

Netbeans 8.0.2 Simple 2D Drawing

Having trouble getting started with Java 2D using Netbeans 8.0.2. Would really appreciate if someone could post some very basic code for just a frame with a panel and a simple shape within.
I've been through so many tutorials, overridden the paintcomponent(), super.paintcomponent() etc. but really not sure how or what actually invokes this method, as it isn't getting invoked in my code :(
package guitest2;
import java.awt.Color;
import java.awt.Graphics;
public class TablePanel extends javax.swing.JPanel {
public TablePanel() {
initComponents();
this.setSize(50, 50);
}
/**
* 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.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(100, 100, 100, 100);
}
}
package guitest2;
public class TableFrame extends javax.swing.JFrame {
public TableFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 529, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 393, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TableFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TableFrame().setVisible(true);
}
});
}
}
package guitest2;
import javax.swing.JFrame;
public class GUITest2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
TableFrame tf = new TableFrame();
tf.setTitle("BJ");
tf.setSize(1200,800);
tf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TablePanel p = new TablePanel();
tf.setVisible(true);
tf.add(p);
}
}
Here's the simple code for drawing an oval on JPanel within a Frame
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
public Test ()
{
setSize (300,300);
JPanel panel=new JPanel (){
#Override
public void paint (Graphics g){
g.setColor (Color.BLUE);
g.fillOval(100, 100, 100, 100);
}
};
add(panel);
setVisible (true);
}
public static void main (String args[]){
new Test();
}
}

Adding JCheckBox to JTable using Netbeans

I have a JTable in my JDialog which I populate myself in another method. Here is my code and I want the second null in my Object array to be a JCheckBox. I have been scowering the internet and saw someone say I need to override a method in the tablerenderer or something like that and I got confused on how to do it. Anyway here is the code
package privatelessontrackernetbeans;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Brent C
*/
public class WeeklyLessonsReductionGUI extends javax.swing.JDialog {
/**
* Creates new form WeeklyLessonsReductionGUI
* #param parent
* #param modal
*/
public WeeklyLessonsReductionGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
postInitComponents();
}
private void postInitComponents() {
ImageIcon icon = new ImageIcon(PSLTrackerInfo.file + "ymcaLogo.png");
setIconImage(icon.getImage());
//Table for students that need more lessons
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
//Center the Titles
DefaultTableCellRenderer centerRenderer = (DefaultTableCellRenderer)
jTable1.getTableHeader().getDefaultRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
//Center the Cells
jTable1.setDefaultRenderer(Object.class, centerRenderer);
TreeMap<Instructor, ArrayList<Student>> theList =
PSLTrackerInfo.theList_getMap();
for (Instructor key : theList.keySet()) {
ArrayList<Student> students = theList.get(key);
boolean listed = false;
for (Student values : students) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
c.set(Calendar.WEEK_OF_YEAR, values.getLastUpdateWeek());
c.set(Calendar.YEAR, values.getLastUpdateYear());
DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
Date date = c.getTime();
String s = df.format(date);
if (listed) {
Object[] data = new Object[]{null,
values.getName(), s, null, null, null};
dtm.addRow(data);
} else {
Object[] data = new Object[]{values.getInstructor(),
values.getName(), s, null, null, null};
dtm.addRow(data);
listed = true;
}
}
}
}
/**
* 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.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Lessons Update");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Instructor", "Student", "Last Update", "Lesson Date", "Lesson Complete", "Unscheduled Lessons"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Update");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(375, 375, 375))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
No need for a custom renderer, just override the getColumnClass() method of the DefaultTableModel making the column with the boolean a Boolean object.
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class CheckBoxTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[][] data
= {{"false", false},
{"true", true}};
String[] cols = {"String", "Boolean"};
DefaultTableModel model = new DefaultTableModel(data, cols) {
#Override
public Class<?> getColumnClass(int column) {
if (column == 1) {
return Boolean.class;
} else {
return String.class;
}
}
};
JTable table = new JTable(model);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
});
}
}
why you just don't do a "new JCheckBox()" instead of the second null??

Dissapear JButton when click JButton [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've got an application with some JButtons, if you click them you see a image. Now if you open the frame and you dont have clicked yet you see a image in the middle of the screen. Now i want if you click the JButton for the image, the image is shown and the other image in the middle of the screen is gone but i dont know how to do.
My Frame:
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Gregory = "Gregory";
private static String Vermeer = "Vermeer";
private static String Alderweireld = "Alderweireld";
private static String Vertonghen = "Vertonghen";
private static String Anita = "Anita";
private static String Enoh = "Enoh";
private static String Sulejmani = "Sulejmani";
private static String Cristian = "Cristian";
private static String Kolbeinn = "Kolbeinn";
private static String Siem = "Siem";
private static String Lorenzo = "Lorenzo";
private static String Andre = "Andre";
private static String Nicolai = "Nicolai";
private static String Theo = "Theo";
private static String Daley = "Daley";
private static String Nicolas = "Nicolas";
private static String Dmitri = "Dmitri";
private static String Kruis = "Kruis";
private JLabel label, label1, label2;
private JButton keeper, verdediger, verdediger1, verdediger2, verdediger3, verdediger4;
private JButton middenvelder, middenvelder1, aanvaller, aanvaller1, middenvelder2;
private JButton aanvaller2, verdediger5, middenvelder3, verdediger6, middenvelder4;
private JButton aanvaller3, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle();
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
kruis.setActionCommand(Kruis);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
verdediger = new JButton("2. "+""+" Gregory van der Wiel");
Cursor cur1 = verdediger.getCursor();
verdediger.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger.setBounds(20, 70, 215, 17);
verdediger.setFocusable(false);
verdediger.setBorderPainted(false);
verdediger.setContentAreaFilled(false);
verdediger.setFont(new Font("Arial",Font.PLAIN,17));
verdediger.setForeground(Color.WHITE);
verdediger.setActionCommand(Gregory);
label.add(verdediger);
verdediger1 = new JButton("3. "+""+" Toby Alderweireld");
Cursor cur2 = verdediger1.getCursor();
verdediger1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger1.setBounds(20, 95, 188, 17);
verdediger1.setFocusable(false);
verdediger1.setBorderPainted(false);
verdediger1.setContentAreaFilled(false);
verdediger1.setFont(new Font("Arial",Font.PLAIN,17));
verdediger1.setForeground(Color.WHITE);
verdediger1.setActionCommand(Alderweireld);
label.add(verdediger1);
verdediger2 = new JButton("4. "+""+" Jan Vertonghen");
Cursor cur3 = verdediger2.getCursor();
verdediger2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger2.setBounds(20, 120, 174, 17);
verdediger2.setFocusable(false);
verdediger2.setBorderPainted(false);
verdediger2.setContentAreaFilled(false);
verdediger2.setFont(new Font("Arial",Font.PLAIN,17));
verdediger2.setForeground(Color.WHITE);
verdediger2.setActionCommand(Vertonghen);
label.add(verdediger2);
verdediger3 = new JButton("5. "+""+" Vurnon Anita");
Cursor cur4 = verdediger3.getCursor();
verdediger3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger3.setBounds(20, 145, 153, 12);
verdediger3.setFocusable(false);
verdediger3.setBorderPainted(false);
verdediger3.setContentAreaFilled(false);
verdediger3.setFont(new Font("Arial",Font.PLAIN,17));
verdediger3.setForeground(Color.WHITE);
verdediger3.setActionCommand(Anita);
label.add(verdediger3);
middenvelder = new JButton("6. "+""+" Eyong Enoh");
Cursor cur5 = middenvelder.getCursor();
middenvelder.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder.setBounds(20, 170, 148, 17);
middenvelder.setFocusable(false);
middenvelder.setBorderPainted(false);
middenvelder.setContentAreaFilled(false);
middenvelder.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder.setForeground(Color.WHITE);
middenvelder.setActionCommand(Enoh);
label.add(middenvelder);
aanvaller = new JButton("7. "+""+" Miralem Sulejmani");
Cursor cur6 = aanvaller.getCursor();
aanvaller.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller.setBounds(20, 195, 190, 17);
aanvaller.setFocusable(false);
aanvaller.setBorderPainted(false);
aanvaller.setContentAreaFilled(false);
aanvaller.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller.setForeground(Color.WHITE);
aanvaller.setActionCommand(Sulejmani);
label.add(aanvaller);
middenvelder1 = new JButton("8. "+""+" Cristian Eriksen");
Cursor cur7 = middenvelder1.getCursor();
middenvelder1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder1.setBounds(20, 220, 174, 12);
middenvelder1.setFocusable(false);
middenvelder1.setBorderPainted(false);
middenvelder1.setContentAreaFilled(false);
middenvelder1.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder1.setForeground(Color.WHITE);
middenvelder1.setActionCommand(Cristian);
label.add(middenvelder1);
aanvaller1 = new JButton("9. "+""+" Kolbeinn Sightórsson");
Cursor cur8 = aanvaller1.getCursor();
aanvaller1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller1.setBounds(20, 245, 212, 17);
aanvaller1.setFocusable(false);
aanvaller1.setBorderPainted(false);
aanvaller1.setContentAreaFilled(false);
aanvaller1.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller1.setForeground(Color.WHITE);
aanvaller1.setActionCommand(Kolbeinn);
label.add(aanvaller1);
middenvelder2 = new JButton("10. "+""+" Siem de Jong");
Cursor cur9 = middenvelder2.getCursor();
middenvelder2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder2.setBounds(20, 270, 168, 17);
middenvelder2.setFocusable(false);
middenvelder2.setBorderPainted(false);
middenvelder2.setContentAreaFilled(false);
middenvelder2.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder2.setForeground(Color.WHITE);
middenvelder2.setActionCommand(Siem);
label.add(middenvelder2);
aanvaller2 = new JButton("11. "+""+" Lorenzo Ebecilio");
Cursor cur10 = aanvaller2.getCursor();
aanvaller2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller2.setBounds(20, 295, 189, 12);
aanvaller2.setFocusable(false);
aanvaller2.setBorderPainted(false);
aanvaller2.setContentAreaFilled(false);
aanvaller2.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller2.setForeground(Color.WHITE);
aanvaller2.setActionCommand(Lorenzo);
label.add(aanvaller2);
verdediger4 = new JButton("13. "+""+" André Ooijer");
Cursor cur11 = verdediger4.getCursor();
verdediger4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger4.setBounds(20, 320, 159, 17);
verdediger4.setFocusable(false);
verdediger4.setBorderPainted(false);
verdediger4.setContentAreaFilled(false);
verdediger4.setFont(new Font("Arial",Font.PLAIN,17));
verdediger4.setForeground(Color.WHITE);
verdediger4.setActionCommand(Andre);
label.add(verdediger4);
verdediger5 = new JButton("15. "+""+" Nicolai Boilesen");
Cursor cur12 = verdediger5.getCursor();
verdediger5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger5.setBounds(20, 345, 183, 12);
verdediger5.setFocusable(false);
verdediger5.setBorderPainted(false);
verdediger5.setContentAreaFilled(false);
verdediger5.setFont(new Font("Arial",Font.PLAIN,17));
verdediger5.setForeground(Color.WHITE);
verdediger5.setActionCommand(Nicolai);
label.add(verdediger5);
middenvelder3 = new JButton("16. "+""+" Theo Janssen");
Cursor cur13 = middenvelder3.getCursor();
middenvelder3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder3.setBounds(20, 370, 169, 12);
middenvelder3.setFocusable(false);
middenvelder3.setBorderPainted(false);
middenvelder3.setContentAreaFilled(false);
middenvelder3.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder3.setForeground(Color.WHITE);
middenvelder3.setActionCommand(Theo);
label.add(middenvelder3);
verdediger6 = new JButton("17. "+""+" Daley Blind");
Cursor cur14 = verdediger6.getCursor();
verdediger6.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
verdediger6.setBounds(20, 395, 150, 17);
verdediger6.setFocusable(false);
verdediger6.setBorderPainted(false);
verdediger6.setContentAreaFilled(false);
verdediger6.setFont(new Font("Arial",Font.PLAIN,17));
verdediger6.setForeground(Color.WHITE);
verdediger6.setActionCommand(Daley);
label.add(verdediger6);
middenvelder4 = new JButton("18. "+""+" Nicolás Lodeiro");
Cursor cur15 = middenvelder4.getCursor();
middenvelder4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
middenvelder4.setBounds(20, 420, 180, 12);
middenvelder4.setFocusable(false);
middenvelder4.setBorderPainted(false);
middenvelder4.setContentAreaFilled(false);
middenvelder4.setFont(new Font("Arial",Font.PLAIN,17));
middenvelder4.setForeground(Color.WHITE);
middenvelder4.setActionCommand(Nicolas);
label.add(middenvelder4);
aanvaller3 = new JButton("19. "+""+" Dmitri Bulykin");
Cursor cur16 = aanvaller3.getCursor();
aanvaller3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
aanvaller3.setBounds(20, 445, 168, 17);
aanvaller3.setFocusable(false);
aanvaller3.setBorderPainted(false);
aanvaller3.setContentAreaFilled(false);
aanvaller3.setFont(new Font("Arial",Font.PLAIN,17));
aanvaller3.setForeground(Color.WHITE);
aanvaller3.setActionCommand(Dmitri);
label.add(aanvaller3);
SelectieController s1 = new SelectieController(keeper, foto, verdediger, verdediger1, verdediger2,
verdediger3, middenvelder, aanvaller, middenvelder1, aanvaller1, middenvelder2, aanvaller2,
verdediger4, verdediger5, middenvelder3, verdediger6, middenvelder4, aanvaller3, kruis);
keeper.addActionListener(s1);
verdediger.addActionListener(s1);
verdediger1.addActionListener(s1);
verdediger2.addActionListener(s1);
verdediger3.addActionListener(s1);
verdediger4.addActionListener(s1);
verdediger5.addActionListener(s1);
verdediger6.addActionListener(s1);
middenvelder.addActionListener(s1);
aanvaller.addActionListener(s1);
middenvelder1.addActionListener(s1);
aanvaller1.addActionListener(s1);
middenvelder2.addActionListener(s1);
aanvaller2.addActionListener(s1);
middenvelder3.addActionListener(s1);
middenvelder4.addActionListener(s1);
aanvaller3.addActionListener(s1);
}
}
Kruis is the image in the midd of the screen a=
ActionPerformed class:
package Controller;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SelectieController implements ActionListener {
private JButton keeper, verdediger, verdediger1, verdediger2, verdediger3;
private JButton middenvelder, aanvaller, middenvelder1, aanvaller1, middenvelder2;
private JButton aanvaller2, verdediger4, verdediger5, middenvelder3, verdediger6;
private JButton middenvelder4, aanvaller3, kruis;
private ImageIcon imageIcon, imageIcon1, imageIcon2, imageIcon3, imageIcon4, imageIcon5;
private ImageIcon imageIcon6, imageIcon7, imageIcon8, imageIcon9, imageIcon10, imageIcon11;
private ImageIcon imageIcon12, imageIcon13, imageIcon14, imageIcon15, imageIcon16;
private JLabel imageLabel;
private Image image, image1, image2, image3, image4, image5, image6, image7, image8, image9;
private Image image10, image11, image12, image13, image14, image15, image16;
private static String Vermeer = "Vermeer";
private static String Gregory = "Gregory";
private static String Alderweireld = "Alderweireld";
private static String Vertonghen = "Vertonghen";
private static String Anita = "Anita";
private static String Enoh = "Enoh";
private static String Sulejmani = "Sulejmani";
private static String Cristian = "Cristian";
private static String Kolbeinn = "Kolbeinn";
private static String Siem = "Siem";
private static String Lorenzo = "Lorenzo";
private static String Andre = "Andre";
private static String Nicolai = "Nicolai";
private static String Theo = "Theo";
private static String Daley = "Daley";
private static String Nicolas = "Nicolas";
private static String Dmitri = "Dmitri";
private static String Kruis = "Kruis";
public SelectieController(JButton vermeer, JLabel vermeer1, JButton gregory, JButton toby, JButton jan,
JButton vurnon, JButton eyong, JButton sulejmani, JButton cristian, JButton kolbeinn, JButton siem,
JButton lorenzo, JButton andre, JButton nicolai, JButton theo, JButton daley, JButton nicolas,
JButton dmitri, JButton kruis)
{
kruis = kruis;
keeper = vermeer;
verdediger1 = toby;
verdediger = gregory;
verdediger2 = jan;
verdediger3 = vurnon;
middenvelder = eyong;
aanvaller = sulejmani;
aanvaller1 = kolbeinn;
middenvelder1 = cristian;
imageLabel = vermeer1;
middenvelder2 = siem;
aanvaller2 = lorenzo;
verdediger4 = andre;
verdediger5 = nicolai;
middenvelder3 = theo;
verdediger6 = daley;
middenvelder4 = nicolas;
aanvaller3 = dmitri;
//Kenneth Vermeer
try
{
image = ImageIO.read(getClass().getResource("/img/kenneth.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon = new ImageIcon(image);
}{
// Gregory van der Wiel
try
{
image1 = ImageIO.read(getClass().getResource("/img/wiel.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon1 = new ImageIcon(image1);
}{
// Toby Alderweireld
try
{
image2 = ImageIO.read(getClass().getResource("/img/toby.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon2 = new ImageIcon(image2);
}{
// Jan Vertonghen
try
{
image3 = ImageIO.read(getClass().getResource("/img/jan.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon3 = new ImageIcon(image3);
}{
// Vurnon anita
try
{
image4 = ImageIO.read(getClass().getResource("/img/vurnon.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon4 = new ImageIcon(image4);
}{
// Eyong Enoh
try
{
image5 = ImageIO.read(getClass().getResource("/img/eyong.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon5 = new ImageIcon(image5);
}{
// Miralem Sulejmani
try
{
image6 = ImageIO.read(getClass().getResource("/img/sulejmani.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon6 = new ImageIcon(image6);
}{
// Cristian Eriksen
try
{
image7 = ImageIO.read(getClass().getResource("/img/eriksen.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon7 = new ImageIcon(image7);
}{
// Kolbeinn sightorsson
try
{
image8 = ImageIO.read(getClass().getResource("/img/kolbeinn.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon8 = new ImageIcon(image8);
}{
// Siem de Jong
try
{
image9 = ImageIO.read(getClass().getResource("/img/siem.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon9 = new ImageIcon(image9);
}{
// Lorenzo Ebecilio
try
{
image10 = ImageIO.read(getClass().getResource("/img/lorenzo.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon10 = new ImageIcon(image10);
}{
// Andre Ooijer
try
{
image11 = ImageIO.read(getClass().getResource("/img/andre.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon11 = new ImageIcon(image11);
}{
// Nicolai Boilesen
try
{
image12 = ImageIO.read(getClass().getResource("/img/nicolai.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon12 = new ImageIcon(image12);
}{
// Theo Janssen
try
{
image13 = ImageIO.read(getClass().getResource("/img/theo.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon13 = new ImageIcon(image13);
}{
// Daley Blind
try
{
image14 = ImageIO.read(getClass().getResource("/img/daley.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon14 = new ImageIcon(image14);
}{
// Nicolas Lodeiro
try
{
image15 = ImageIO.read(getClass().getResource("/img/nicolas.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon15 = new ImageIcon(image15);
}{
// Dmitri Bulykin
try
{
image16 = ImageIO.read(getClass().getResource("/img/dmitri.png"));
}
catch(Exception e)
{
e.printStackTrace();
}
imageIcon16 = new ImageIcon(image16);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon );
imageLabel.setBounds(75, 50, 120, 150);
kruis.setVisible(false);
}
});
}
// Gregory van der Wiel
if (Gregory.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon1 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Toby Alderweireld
if (Alderweireld.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon2 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Jan Vertonghen
if (Vertonghen.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon3 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
//Vurnon Anita
if (Anita.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon4 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Eyong Enoh
if (Enoh.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon5 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
// Miralem Sulejmani
if (Sulejmani.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(imageIcon6 );
imageLabel.setBounds(75, 50, 120, 150);
}
});
}
}}
First, whenever you have elements with names like button1, button2 etc. you need to refactor the code and work with an array instead. This way you can refer to the needed element using its index, instead of many if-else statements. That's applies for the Strings , Buttons, Images and ImageIcons.
Now, when a button is pressed, find it's index (in a loop for example) and make all other button/images disappear, using setVisible(false), and only the relevant image display using setVisible(true).

Java applet RuntimeException: java.lang.NoClassDefFoundError: javax/mail/Authenticator

I have written my first java applet and get errors when deploying it on my web server. My applet uses couple of additional jar files like javaMail mail.jar, smtp.jar, mailapi.jar and others. When I try to display my applet in web browser I get such info in Error Dialog:
java.lang.RuntimeException: java.lang.NoClassDefFoundError: javax/mail/Authenticator
..
Caused by: java.lang.NoClassDefFoundError: javax/mail/Authenticator
... 20 more
I am not very good with web applications and not sure what causes this error. From the info I assume that my applet cannot load the libraries. So how can I solve this? I have those libraries on my server in /lib directory. All other files are in main directory. My HTML file is as follows:
<HTML>
<HEAD>
<TITLE>TPSA Speed Test</TITLE>
</HEAD>
<BODY>
<P>
<APPLET code="speedtester_pkg/AppletMain.class" archive="SpeedTester.jar" width=440 height=600></APPLET>
</P>
</BODY>
</HTML>
I also tried to load my applet to web browser using JNLP with the same effect. I tried to find some way to point those libraries in HTML file, but I didn't manage (tried to add another jar archive lines or nativelib in JNLP file). I also tried to add those libraries to jar file with my applet classes, but that didn't help either.
This is my code where I use javaMail (sendTestResults() method near end of the code):
/*
* AppletMain.java
*/
package speedtester_pkg;
import java.awt.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class AppletMain extends javax.swing.JApplet implements PropertyChangeListener{
private ArrayList<String> customerFields;
private DataReader dataReader;
private Test test;
private FileHandler fh;
private ProgressBarTask progressBarTask;
private JTextField[] customerData;
private String speed, cpuLoad, NICspeed, testTime;
private int timeDef = 60;
/**
* The input file directory
*/
// public String directory = "C:\\Documents and Settings\\Administrator\\Pulpit\\";
public String filename = "speedtestData.txt";
/**
* Input file should be a simple "*.txt" file named "speedtestData.txt"
*/
public File file;
// mail sending data
/**
* TO DO encrypt mailing data
*/
private String smtpHost = "smtp.gmail.com",
username = "myUserName",
password = "myPassword";
private int port = 465; // TLS 587/ SSL 465
/** Initializes the applet Applet */
#Override
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
infoPanel = new javax.swing.JPanel();
labelLogo = new javax.swing.JLabel();
labelTitle = new javax.swing.JLabel();
labelLinkSpeed = new javax.swing.JLabel();
labelProcessorLoad = new javax.swing.JLabel();
labelNIC = new javax.swing.JLabel();
buttonStart = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jProgressBar = new javax.swing.JProgressBar();
formPanel = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
buttonSend = new javax.swing.JButton();
labelForm = new javax.swing.JLabel();
infoLabel = new javax.swing.JLabel();
jScrollPane = new javax.swing.JScrollPane();
commentText = new javax.swing.JTextArea();
labelTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
labelTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelTitle.setText("Link Speed Test");
labelLinkSpeed.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
labelLinkSpeed.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
labelProcessorLoad.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
labelProcessorLoad.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
labelNIC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labelNIC.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
buttonStart.setText("Start");
buttonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStartActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel4.setText("Szybkość łącza:");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel5.setText("Obciążenie procesora:");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel6.setText("Szybkość karty sieciowej:");
javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
infoPanel.setLayout(infoPanelLayout);
infoPanelLayout.setHorizontalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
.addComponent(labelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelLinkSpeed, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
.addComponent(labelProcessorLoad, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
.addComponent(labelNIC, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)))
.addComponent(labelTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
.addContainerGap(352, Short.MAX_VALUE)
.addComponent(buttonStart, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
);
infoPanelLayout.setVerticalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
.addComponent(labelTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelLinkSpeed, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(labelProcessorLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(labelNIC, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6))
.addGroup(infoPanelLayout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(labelLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addComponent(buttonStart)
.addContainerGap())
);
javax.swing.GroupLayout formPanelLayout = new javax.swing.GroupLayout(formPanel);
formPanel.setLayout(formPanelLayout);
formPanelLayout.setHorizontalGroup(
formPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 417, Short.MAX_VALUE)
);
formPanelLayout.setVerticalGroup(
formPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 127, Short.MAX_VALUE)
);
jLabel8.setText("Uwagi:");
buttonSend.setText("Wyślij");
buttonSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSendActionPerformed(evt);
}
});
labelForm.setFont(new java.awt.Font("Tahoma", 0, 14));
labelForm.setText("Formularz:");
infoLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
infoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
infoLabel.setText("Kliknij przycisk \"Start\" aby rozpocząć test");
commentText.setColumns(20);
commentText.setRows(5);
jScrollPane.setViewportView(commentText);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 437, Short.MAX_VALUE)
.addGap(0, 437, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
.addComponent(formPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(infoLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
.addComponent(infoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelForm)
.addComponent(buttonSend, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 572, Short.MAX_VALUE)
.addGap(0, 572, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(infoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(infoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(labelForm)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(formPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buttonSend)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>
public void createGUI()
{
try {
dataReader = new DataReader(this);
dataReader.read();
customerFields = dataReader.getCustomerFields();
testTime = String.valueOf(dataReader.getTestTime());
initComponents();
generateCustomerForm();
test = new Test(this, dataReader.getDownloadURLs(), dataReader.getTestTime());
} catch (ClassNotFoundException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {
buttonStart.setEnabled(false);
infoLabel.setText("Poczekaj do końca testu...");
progressBarTask = new ProgressBarTask(this);
infoLabel.setText("progress bar");
progressBarTask.addPropertyChangeListener(this);
progressBarTask.execute();
Thread testThread = new Thread(this.test);
testThread.start();
System.out.println("Test thread \"" + testThread.getName() + "\" started.");
}
private void buttonSendActionPerformed(java.awt.event.ActionEvent evt) {
try {
sendTestResults();
} catch (MessagingException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(AppletMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void generateCustomerForm() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
//correcting auto-generated layout
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 11));
labelProcessorLoad.setAlignmentX(RIGHT_ALIGNMENT);
labelLogo.setIcon(new ImageIcon(getImage(getDocumentBase(), "orange.jpeg")));
//gereate JLabels and JTextFields read from file
GridBagLayout gridBagLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
formPanel.setLayout(gridBagLayout);
customerData = new JTextField[customerFields.size()];
for(int i=0; i<customerFields.size(); i++)
{
JLabel l = new JLabel(customerFields.get(i));
l.setFont(new java.awt.Font("Tahoma", 0, 11));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=i;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
formPanel.add(l, gbc);
JTextField t = new JTextField();
t.setFont(new java.awt.Font("Tahoma", 0, 11));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx=1;
gbc.gridy=i;
gbc.weightx = 0.5;
gbc.weighty = 0.5;
formPanel.add(t, gbc);
customerData[i] = t;
}
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("progress")) {
int progress = (Integer) evt.getNewValue();
jProgressBar.setValue(progress);
}
}
public void setLabelProcessorLoad(String text)
{
labelProcessorLoad.setText(text);
}
public void setLabelLinkSpeed(String text)
{
labelLinkSpeed.setText(text);
}
public void setLabelNIC(String text)
{
labelNIC.setText(text);
}
public JProgressBar getProgressBar()
{
return jProgressBar;
}
public JButton getButtonStart()
{
return buttonStart;
}
public Test getTest()
{
return this.test;
}
public void setNICspeed(String NICspeed) {
this.NICspeed = NICspeed;
}
public void setCpuLoad(String cpuLoad) {
this.cpuLoad = cpuLoad;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public JLabel getInfoLabel() {
return infoLabel;
}
/**
* Prepares e-mail message for sending via google SMTP protocol with SSL
*/
private void sendTestResults() throws MessagingException, UnsupportedEncodingException{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
MimeMessage message = new MimeMessage(session);
//Setting message fields
Address toAddress = new InternetAddress(dataReader.getMail(), "SpeedTest crew");
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject("SpeedTest");
message.setText(prepareMailText(), "UTF8");
Transport.send(message);
infoLabel.setText("Wiadomość z wynikami testu została wysłana pomyślnie");
System.out.println("Mail sent.");
}
/**
* Gets all test results and customer data and prepares mail content
* #return the content of e-mail body
*/
private String prepareMailText()
{
String messageContentHeader = "Prędkość pobierania\t" + "Obciążenie procesora\t" +
"Szybkość łącza karty sieciowej\t" + "Czas trwania testu\t";
String messageContent = speed + "\t"+ cpuLoad + "\t" + NICspeed + "\t" + testTime + "\t";
for(int j=0;j<customerData.length;j++)
{
messageContentHeader += customerFields.get(j) + "\t";
messageContent += customerData[j].getText() + "\t";
}
messageContentHeader += "Uwagi";
messageContent += commentText.getText();
String messageText = messageContentHeader + "\n" + messageContent;
return messageText;
}
// Variables declaration - do not modify
private javax.swing.JButton buttonSend;
private javax.swing.JButton buttonStart;
private javax.swing.JTextArea commentText;
private javax.swing.JPanel formPanel;
private javax.swing.JLabel infoLabel;
private javax.swing.JPanel infoPanel;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JProgressBar jProgressBar;
private javax.swing.JScrollPane jScrollPane;
private javax.swing.JLabel labelForm;
private javax.swing.JLabel labelLinkSpeed;
private javax.swing.JLabel labelLogo;
private javax.swing.JLabel labelNIC;
private javax.swing.JLabel labelProcessorLoad;
private javax.swing.JLabel labelTitle;
// End of variables declaration
}
I also had a problem with other libraries like Sigar.jar, but I suppose it will solve similarly.
Somebody has good tips?
It is necessary to add the Jar containing the javax.mail packages to the run-time class-path of the applet. To achieve that (one way is to) put that Jar in the same place SpeedTester.jar and change the archive attribute from:
archive="SpeedTester.jar"
..to:
archive="SpeedTester.jar,mail.jar"
Update 1
Change the entire applet element:
From
<APPLET
code="speedtester_pkg/AppletMain.class"
archive="SpeedTester.jar"
width=440
height=600>
</APPLET>
To
<APPLET
code="speedtester_pkg.AppletMain"
archive="SpeedTester.jar,mail.jar"
width=440
height=600>
</APPLET>
Presuming the package of the applet class is speedtester_pkg and the applet is named AppletMain. The code attribute should be the fully qualified name of the applet class, not the path/file name.
Update 2
The above advice re. the mail.jar does not account for classes that are referenced from within the Test, DataReader or ProgressBarTask (or the classes they load). 'Rinse and repeat' that advice for adding extra APIs to the run-time class-path using the archive attribute.
Note
It seems the other answers are referring to a web-app. that is entirely server-side. For such a web-app., putting Jars into the lib makes sense. OTOH an applet can only access a Jar that is available by copy/pasting the URL of the Jar into the browser address bar and hitting enter.
In fact doing just that, using a combination of the code-base & href of the Jar, is a good 'acid test' of whether an applet will be able to access the archive.
Looks like you're missing the JAR with javax.mail.Authenticator
You can use the FindJar site to figure out what the name of the JAR is and where to download it. Google for it; it's worth knowing about.
You might be missing others as well. Keep adding JARs to your app's WEB-INF/lib until those CNF exceptions go away.
Missing JARs (mail.jar in your case) is the primary reason for any ClassNotFound exception. Place it in your app server's lib directory to resolve this.