Dissapear JButton when click JButton [closed] - eclipse

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).

Related

iTextSharp 5 generated PDF-Document AdobeReader-compatibility [duplicate]

This question already has answers here:
iTextSharp-generated PDFs now cause Save dialog in Adobe Reader X
(2 answers)
Closed 5 years ago.
I am generating some reports with iTextSharp 5.
Opening the generated .PDF-file, everything looks and actually is fine with most PDF-readers.
When I open the PDF using AdobeReader(DC) however, it asks me if i want to save the changes on close. Although I didn't change anything.
Hitting 'Cancel' sure makes the message window go away, but hitting save causes the file to actually shrinks in size.
Now what is happening there? And why? How can I disable it?
The users of the application are most likely gonna use AdobeReader as well.
I don't want them to see the save dialog anytime they open a report.
Here is my BaseReport class
public abstract class BaseReport : PdfPageEventHelper
{
protected const string SPACE = " ";
protected const string COLON = ":";
protected static string NEWLINE = Environment.NewLine;
protected Document document;
protected PdfTemplate footerTemplate;
protected PdfContentByte contentByte;
protected PdfWriter writer;
private PdfTemplate totalPageNoTemplate;
private int lastPageNumber;
// properties for header
private bool done;
// needs to be overriden in subclass order to use header feature
protected string kundeHeader { get; set; }
// font definitions
protected BaseFont baseFont;
protected Font fontFooter;
protected Font fontGeneralText;
protected Font fontLabelText;
protected Font fontBoldLabelText;
protected Font fontBoldText;
protected Font fontSpace;
protected Font fontLargeBoldText;
protected int language;
protected bool useLogo = false;
protected bool usePageNumbers = false;
protected bool usePrintDate = false;
protected const string PRINT_FULLDATE_FORMAT = "dd.MM.yyyy HH:mm";
protected const string PRINT_DATE_ONLY_FORMAT = "dd.MM.yyyy";
protected Rectangle pagesize = PageSize.A4;
protected float marginLeft = 80;
protected float marginRight = 35;
protected float marginTop = 40;
protected float marginBottom = 40;
private MemoryStream PDFStream { get; set; } = new MemoryStream();
private DateTime printDate;
public BaseReport(int language = Languages.DE, bool landscape = false)
{
this.language = language;
if (landscape)
{
pagesize = pagesize.Rotate();
}
}
public byte[] GenerateReport()
{
CultureInfo cultureBefore = Resources.Culture;
try
{
Resources.Culture = SelectCultureForLangauge();
PrepareReport();
document = new Document(pagesize, marginLeft, marginRight, marginTop, marginBottom);
BuildFonts();
OpenDocument();
PrepareDocument();
GenerateContent();
document.Close();
return PDFStream.GetBuffer();
} finally
{
Resources.Culture = cultureBefore;
}
}
public void GenerateReport(string filename)
{
byte[] report = GenerateReport();
using (FileStream f = new FileStream(filename, FileMode.Create))
{
f.Write(report, 0, report.Length);
}
}
protected CultureInfo SelectCultureForLangauge()
{
string languageCode = GetLanguageCode();
return CultureInfo.GetCultureInfo(languageCode);
}
protected string GetLanguageCode()
{
string languageCode = string.Empty;
switch (language)
{
case Languages.FR: languageCode = "FR"; break;
case Languages.IT: languageCode = "IT"; break;
case Languages.EN: languageCode = "EN"; break;
default: languageCode = "DE"; break;
}
return languageCode;
}
protected virtual void PrepareReport() { }
protected virtual void PrepareDocument() { }
protected abstract void GenerateContent();
private void BuildFonts()
{
baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
fontFooter = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.ITALIC, BaseColor.DARK_GRAY);
fontGeneralText = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.NORMAL, BaseColor.BLACK);
fontLabelText = FontFactory.GetFont(FontFactory.HELVETICA, 8.5f, Font.NORMAL, BaseColor.BLACK);
fontBoldLabelText = FontFactory.GetFont(FontFactory.HELVETICA, 8.5f, Font.BOLD, BaseColor.BLACK);
fontBoldText = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.BOLD, BaseColor.BLACK);
fontSpace = FontFactory.GetFont(FontFactory.HELVETICA, 3.5f, Font.NORMAL, BaseColor.BLACK);
fontLargeBoldText = FontFactory.GetFont(FontFactory.HELVETICA, 17, Font.BOLD, BaseColor.BLACK);
GetFontIfAvailable();
}
private void GetFontIfAvailable()
{
string fileName = "IF_Rg";
try
{
baseFont = LoadFontFromFile(fileName, true);
fontFooter = new Font(baseFont, 11, Font.ITALIC, BaseColor.DARK_GRAY);
fontGeneralText = new Font(baseFont, 11, Font.NORMAL, BaseColor.BLACK);
fontLabelText = new Font(baseFont, 8.5f, Font.NORMAL, BaseColor.BLACK);
fontBoldLabelText = new Font(baseFont, 8.5f, Font.BOLD, BaseColor.BLACK);
fontBoldText = new Font(baseFont, 11, Font.BOLD, BaseColor.BLACK);
fontSpace = new Font(baseFont, 3.5f, Font.NORMAL, BaseColor.BLACK);
fontLargeBoldText = new Font(baseFont, 17, Font.BOLD, BaseColor.BLACK);
} catch (FileNotFoundException)
{
LogWrapper.Warn("Font not found - using default.");
}
}
protected BaseFont LoadFontFromFile(string fileName, bool embedded)
{
string fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\" + fileName + ".ttf";
if (File.Exists(fontPath))
{
return BaseFont.CreateFont(fontPath, BaseFont.WINANSI, embedded);
}
else
{
throw new FileNotFoundException($"Fontfile {fileName} was not found!");
}
}
protected Image HeaderLogo()
{
Image logo = Image.GetInstance(Resources.logo, BaseColor.BLACK);
// TODO msc pick logo from debitor
logo.ScaleToFit(100f, 100f);
return logo;
}
protected void OpenDocument()
{
writer = PdfWriter.GetInstance(document, PDFStream);
writer.PageEvent = this;
writer.SetFullCompression();
document.Open();
contentByte = writer.DirectContent;
}
protected void AddLabelAt(string label, float posX, float posY)
{
PdfContentByte cb = writer.DirectContent;
ColumnText column = new ColumnText(cb);
column.SetText(new Paragraph(label + NEWLINE, fontLabelText));
column.SetSimpleColumn(posX, 20, posX + 200, posY);
column.Go();
}
protected void AddLabelOnMargin(string label)
{
AddLabelAt(label, document.LeftMargin - 40, writer.GetVerticalPosition(false));
}
protected Phrase ParaLine(string Text, Font textfont)
{
return new Phrase(Text, textfont);
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
if (usePageNumbers)
{
totalPageNoTemplate = writer.DirectContentUnder.CreateTemplate(50, 50);
}
if (usePrintDate)
{
printDate = DateTime.Now;
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
if (useLogo || (document.PageNumber > 1 && !string.IsNullOrEmpty(kundeHeader)))
{
PdfContentByte canvas = writer.DirectContentUnder;
canvas.SaveState();
if (document.PageNumber > 1 && !string.IsNullOrEmpty(kundeHeader))
{
//showtextaligned only shows a single line
//therefor the header needs to be split and its parts need to be added seperately
string[] headerParts = kundeHeader.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Phrase header = new Phrase(kundeHeader, fontLabelText);
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
ParaLine(headerParts[0], fontLabelText),
document.LeftMargin,
document.Top + 30, 0);
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
ParaLine(headerParts[1], fontLabelText),
document.LeftMargin,
document.Top + 20, 0);
}
if (useLogo)
{
Image logo = HeaderLogo();
logo.SetAbsolutePosition(marginLeft - 17.5f, document.Top + document.TopMargin - 50);
document.Add(logo);
}
canvas.RestoreState();
}
}
public override void OnEndPage(PdfWriter writer, Document document)
{
if (usePageNumbers || usePrintDate)
{
PdfContentByte canvas = writer.DirectContentUnder;
canvas.SaveState();
if (usePageNumbers)
{
// adds current page number to the footer section of the document
int pageN = writer.PageNumber;
string text = Resources.LabelSeite + SPACE + pageN + "/";
float len = fontLabelText.BaseFont.GetWidthPoint(text, fontLabelText.Size);
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
ParaLine(text, fontLabelText),
document.LeftMargin,
document.Bottom - 10, 0);
// adds template to fill in total page number (see OnCloseDocument method)
canvas.AddTemplate(totalPageNoTemplate, document.LeftMargin + len, document.Bottom - 10);
lastPageNumber = pageN;
}
if (usePrintDate)
{
// adds the printdate to the footer secdtion of the document
string dateFormatted = printDate.ToString(PRINT_FULLDATE_FORMAT);
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT,
ParaLine(dateFormatted, fontLabelText),
document.Right,
document.Bottom - 10, 0);
}
canvas.RestoreState();
}
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
if (usePageNumbers)
{
// fills in the total page number to the prepared template in the footer section of the document
string text = lastPageNumber + "";
float widthPoint = fontLabelText.BaseFont.GetWidthPoint(text, fontLabelText.Size);
totalPageNoTemplate.Width = widthPoint;
ColumnText.ShowTextAligned(totalPageNoTemplate, Element.ALIGN_LEFT, ParaLine(text, fontLabelText), 0, 0, 0);
}
}
iTextSharp-generated PDFs now cause Save dialog in Adobe Reader X
I had to switch PDFStream.GetBuffer() with PDFStream.ToArray(); problem solved.

Create PDF with iText on iSeries leads to error "The document has no pages."

We use the nice library iText for one of my customer's project to generate a pdf from a string representing a html page. The iText version is 5.5.10.
The following piece of code works well on the development environments and servers running on Windows, but it is not working on the customer's server running on iSeries.
public class GeneratePDFCmdImpl extends ControllerCommandImpl implements
GeneratePDFCmd {
private String charsetStr = null;
private Charset charset = null;
private BaseFont bf = null;
private String destFile = null;
private String destFilename = null;
private String srcContent = null;
private String docName = null;
public void setDocName(String docname) {
this.docName = docname;
}
public void setSrcContent(String srcContent) {
this.srcContent = srcContent;
}
private void prepareDefaultsAndSettings() {
/* srcContent may be more complex html but even this simple one is not working */
srcContent = "<html><head></head><body>This is just a test</body></html>";
docName = "mypdf";
charsetStr = "UTF-8";
destFilename = docName+".pdf";
Date timestamp = new Date();
/* destFile = "/" is just for the sample. In my real project, the value is a folder where my app has full rights
*/
destFile = "/" + destFilename;
charset = Charset.forName(charsetStr);
FontFactory.register("/fonts/arial.ttf","Arial");
bf = FontFactory.getFont("Arial").getBaseFont();
}
#Override
public void performExecute() throws ECException {
super.performExecute();
Document document = null;
OutputStream os = null;
prepareDefaultsAndSettings();
try {
InputStream srcInputStream;
srcInputStream = new ByteArrayInputStream(srcContent.getBytes(charset));
document = new Document(PageSize.A4, 20, 20, 75, 80);
FileOutputStream destOutput = new FileOutputStream(destFile);
PdfWriter writer = PdfWriter.getInstance(document,destOutput);
writer.setPageEvent( new HeaderFooterPageEvent(bf));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, srcInputStream, charset);
document.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
if(document != null) {
document.close();
}
document = null;
try {
if (os != null) {
os.close();
}
} catch(IOException e) {
e.printStackTrace();
}
os = null;
}
}
private class HeaderFooterPageEvent extends PdfPageEventHelper {
PdfContentByte cb;
PdfTemplate template;
BaseFont bf;
Font f;
float fs;
public HeaderFooterPageEvent(BaseFont _bf) {
super();
bf = _bf;
f = new Font(bf);
}
#Override
public void onOpenDocument(PdfWriter writer, Document document) {
cb = writer.getDirectContent();
template = cb.createTemplate(50, 50);
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
Date dat = new Date();
ColumnText ct = new ColumnText(writer.getDirectContent());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
ct.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(sdf.format(dat) ), 100, 30, 0);
String text = "Page " +writer.getPageNumber() + " to ";
float len = bf.getWidthPoint(text, 12);
cb.beginText();
cb.setFontAndSize(bf, 12);
cb.setTextMatrix(450, 30);
cb.showText(text);
cb.endText();
cb.addTemplate(template, 450 + len, 30);
}
#Override
public void onCloseDocument(PdfWriter writer, Document document) {
template.beginText();
template.setFontAndSize(bf, 12);
template.showText(String.valueOf(writer.getPageNumber()));
template.endText();
}
}
}
When executed on the iSeries, we have the error message
com.ibm.commerce.command.ECCommandTarget executeCommand CMN0420E: The following command exception has occurred during processing: "ExceptionConverter: java.io.IOException: The document has no pages.". ExceptionConverter: java.io.IOException: The document has no pages.
at com.itextpdf.text.pdf.PdfPages.writePageTree(PdfPages.java:112)
at com.itextpdf.text.pdf.PdfWriter.close(PdfWriter.java:1256)
at com.itextpdf.text.pdf.PdfDocument.close(PdfDocument.java:900)
at com.itextpdf.text.Document.close(Document.java:415)
at be.ourcustomer.package.GeneratePDFCmdImpl.performExecute(GeneratePDFCmdImpl.java:107)
I don't have much idea about what we do wrong. Any help would be greatly appreciated

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

external link subgurim google maps open infowindow

this code is not working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeServerSide();
ConfigureClientSide();
}
}
private void InitializeServerSide()
{
GLatLng latlng = new GLatLng(39, -0.5);
GMarker marker = new GMarker(latlng);
GMap1.Add(marker);
InitializeClientSide(marker.ID);
}
private void InitializeClientSide(string markerId)
{
btnGInfoWindow.Attributes.Add("onclick", string.Format("windowMe("+ markerId +");"));
}
private void ConfigureClientSide()
{
string js = string.Format(#"function windowMe(markerId){{var marker = getGMapElementById(subgurim_GMap1,markerId); marker.openInfoWindowHtml('Hello world!'); }}", GMap1.GMap_Id);
GMap1.addCustomJavascript(js);
}
try this,
private void InitializeServerSide()
{
GMap1.addInfoWindow(GetInfoWindow(new GLatLng(7.225261, 80.198994)));
}
protected GInfoWindow GetInfoWindow(GLatLng loc)
{
GIcon icon = new GIcon();
icon.image = "http://localhost:9477/icons/red.png";
icon.shadow = "http://localhost:9477/icons/shadow.png";
icon.iconSize = new GSize(50, 50);
icon.shadowSize = new GSize(0, 0);
icon.iconAnchor = new GPoint(6, 18);
icon.infoWindowAnchor = new GPoint(0, 0);
GMarkerOptions mOpts = new GMarkerOptions();
mOpts.icon = icon;
GMarker marker = new GMarker(loc, mOpts);
GInfoWindow infoWindow = new GInfoWindow(marker, "Line ID: sachinda", GListener.Event.click);
return infoWindow;
}

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.