readLine() does not return any value - sockets

When I try to execute this code, server correctly gets the data that I send, however client does not print "response". Program goes into infinite loop at readLine() line and even "Something" String is not printed. What might be the problem?
class SecuritySystemClient {
public static void main(String argv[]) throws Exception{
byte [] a = {0, 0, 13, 98, 105, 108, 107, 101, 110, 116, 58, 99, 115, 52, 50, 49};
Socket clientSocket = new Socket("localhost", 80);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.write(a, 0, a.length);
outToServer.flush();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String response = inFromServer.readLine();
System.out.println("Something");
System.out.println(response);
clientSocket.close();
}
}

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.

How to set the key of the message?

I am using Spring Cloud with Apache Kafka. The messages sent to a kafka topic usally contain a key as well. How can I set that key?
Let's say, I produce messages like this
#StreamListener(CashflowSink.T1_CASHFLOW_IN)
#SendTo(CashflowSink.T2_CASHFLOW_OUT)
public synchronized Cashflow receive1(String message) {
System.out.println("******************");
System.out.println("At Sink1");
System.out.println("******************");
System.out.println("Received message " + message);
String arr[] = message.split(";");
if (arr[0].equalsIgnoreCase("Cashflow")) {
Cashflow cf = new Cashflow();
cf.setContractId(Integer.parseInt(arr[1]));
cf.setDate(arr[2]);
cf.setAmount(Float.parseFloat(arr[3]));
return cf;
}
return null;
}
Later I want to join cashflows with other topics. For joins, I need a key. Let's say the key is the contractId of the cashflow. How can I set that key in the message?
EDIT 1
Trying to incorporate the code from Gary, I came up with:
//#Bean //--> leads to: Parameter 0 of method runner in tki.bigdata.steams.CashflowService required a single bean, but 10 were found:
#Qualifier("t2_cashflow_in") // is this a correct way to get a handle to the channel?
public ApplicationRunner runner(MessageChannel output) {
((AbstractMessageChannel) output).addInterceptor(0, new ChannelInterceptor() {
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
return MessageBuilder.fromMessage(message)
.setHeader(KafkaHeaders.MESSAGE_KEY, ((Cashflow) message.getPayload()).getContractId())
.build();
}
});
return args -> {
};
}
#StreamListener(CashflowSink.T2_CASHFLOW_IN)
public synchronized void receive2(Cashflow cashflow, #Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) byte[] key) {
System.out.println("******************");
System.out.println("At Sink2");
System.out.println("******************");
System.out.println("Received cashflow " + cashflow);
System.out.println(cashflow + ", key:" + new String(key));
}
The #Bean annotation gave me an error, probably because there are multiple "channels". I followed a hint in the error message and used the #Channel annotation. Not sure, if this does what I want to achieve.
Executing that code, I am getting Errors like the following. So I assume the interception did not work?
2019-06-20 20:56:02,557 ERROR [Ljava.lang.String;#4195105b.container-0-C-1 o.s.k.l.LoggingErrorHandler:37 - Error while processing: ConsumerRecord(topic = tier2.cashflow, partition = 0, offset = 11, CreateTime = 1561056959426, serialized key size = -1, serialized value size = 63, headers = RecordHeaders(headers = [RecordHeader(key = deliveryAttempt, value = [49]), RecordHeader(key = contentType, value = [34, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 106, 115, 111, 110, 34]), RecordHeader(key = spring_json_header_types, value = [123, 34, 100, 101, 108, 105, 118, 101, 114, 121, 65, 116, 116, 101, 109, 112, 116, 34, 58, 34, 106, 97, 118, 97, 46, 117, 116, 105, 108, 46, 99, 111, 110, 99, 117, 114, 114, 101, 110, 116, 46, 97, 116, 111, 109, 105, 99, 46, 65, 116, 111, 109, 105, 99, 73, 110, 116, 101, 103, 101, 114, 34, 44, 34, 99, 111, 110, 116, 101, 110, 116, 84, 121, 112, 101, 34, 58, 34, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 83, 116, 114, 105, 110, 103, 34, 125])], isReadOnly = false), key = null, value = [B#5884f4e2)
org.springframework.messaging.MessageHandlingException: Missing header 'kafka_receivedMessageKey' for method parameter type [class [B]
at org.springframework.messaging.handler.annotation.support.HeaderMethodArgumentResolver.handleMissingValue(HeaderMethodArgumentResolver.java:105)
at org.springframework.messaging.handler.annotation.support.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:106)
at org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:117)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:148)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:116)
at org.springframework.cloud.stream.binding.StreamListenerMessageHandler.handleRequestMessage(StreamListenerMessageHandler.java:55)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:123)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:176)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:115)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:132)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:73)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:453)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:109)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:205)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.sendMessageIfAny(KafkaMessageDrivenChannelAdapter.java:369)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$400(KafkaMessageDrivenChannelAdapter.java:74)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:431)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:402)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.lambda$onMessage$0(RetryingMessageListenerAdapter.java:120)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:211)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:114)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:40)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeOnMessage(KafkaMessageListenerContainer.java:1263)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeOnMessage(KafkaMessageListenerContainer.java:1256)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeRecordListener(KafkaMessageListenerContainer.java:1217)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeWithRecords(KafkaMessageListenerContainer.java:1198)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:1118)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:933)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:749)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:698)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:745)
For the case that there is more useful information, I post the whole class
#EnableBinding(CashflowService.CashflowSink.class)
public class CashflowService {
#StreamListener(CashflowSink.T1_CASHFLOW_IN)
#SendTo(CashflowSink.T2_CASHFLOW_OUT)
public synchronized Cashflow receive1(String message) {
System.out.println("******************");
System.out.println("At Sink1");
System.out.println("******************");
System.out.println("Received message " + message);
String arr[] = message.split(";");
if (arr[0].equalsIgnoreCase("Cashflow")) {
Cashflow cf = new Cashflow();
cf.setContractId(Integer.parseInt(arr[1]));
cf.setDate(arr[2]);
cf.setAmount(Float.parseFloat(arr[3]));
return cf;
}
return null;
}
// #Bean //--> leads to: Parameter 0 of method runner in
// tki.bigdata.steams.CashflowService required a single bean, but 10 were
// found:
#Qualifier("t2_cashflow_in") // is this a correct way to get a handle to the
// channel?
public ApplicationRunner runner(MessageChannel output) {
((AbstractMessageChannel) output).addInterceptor(0, new ChannelInterceptor() {
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
return MessageBuilder.fromMessage(message)
.setHeader(KafkaHeaders.MESSAGE_KEY, ((Cashflow) message.getPayload()).getContractId()).build();
}
});
return args -> {
};
}
#StreamListener(CashflowSink.T2_CASHFLOW_IN)
public synchronized void receive2(Cashflow cashflow, #Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) byte[] key) {
System.out.println("******************");
System.out.println("At Sink2");
System.out.println("******************");
System.out.println("Received cashflow " + cashflow);
System.out.println(cashflow + ", key:" + new String(key));
}
public interface CashflowSink {
String T1_CASHFLOW_IN = "t1_cashflow_in";
String T2_CASHFLOW_IN = "t2_cashflow_in";
String T1_CASHFLOW_OUT = "t1_cashflow_out";
String T2_CASHFLOW_OUT = "t2_cashflow_out";
#Input(T1_CASHFLOW_IN)
SubscribableChannel t1_cashflow_in();
#Input(T2_CASHFLOW_IN)
SubscribableChannel t2_cashflow_in();
#Output(T1_CASHFLOW_OUT)
SubscribableChannel t1_cashflow_out();
#Output(T2_CASHFLOW_OUT)
SubscribableChannel t2_cashflow_out();
}
}
There is a messageKeyExpression kafka extension producer property; the problem is, the expression is evaluated after the payload is converted (unless you are using nativeEncoding, in which case you can use that with payload.contractId).
If you are not using native encoding, you can add an interceptor (before the conversion interceptor) and promote the key to the KafkaHeaders.MESSAGE_KEY header.
Here is an example:
#SpringBootApplication
#EnableBinding(Processor.class)
public class So56689257Application {
public static void main(String[] args) {
SpringApplication.run(So56689257Application.class, args);
}
#Bean
public ApplicationRunner runner(MessageChannel output) {
((AbstractMessageChannel) output).addInterceptor(0, new ChannelInterceptor() {
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
return MessageBuilder.fromMessage(message)
.setHeader(KafkaHeaders.MESSAGE_KEY, ((Foo) message.getPayload()).getContractId().getBytes())
.build();
}
});
return args -> {
output.send(MessageBuilder.withPayload(new Foo("someContractId")).build());
};
}
#StreamListener(Processor.INPUT)
public void listen(Foo foo, #Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) byte[] key) {
System.out.println(foo + ", key:" + new String(key));
}
public static class Foo {
private String contractId;
public Foo() {
super();
}
public Foo(String contractId) {
this.contractId = contractId;
}
public String getContractId() {
return this.contractId;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
#Override
public String toString() {
return "Foo [contractId=" + this.contractId + "]";
}
}
}
and
Foo [contractId=someContractId], key:someContractId
The RabbitMQ binder already has a built-in RabbitExpressionEvaluatingInterceptor (which evaluates expressions before payload conversion) but there is currently no equivalent in the Kafka binder, so you have to add your own interceptor.
Or, if you are using json, you can use #jsonpath in the expression to extract the key.

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

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);
}
}

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.