How to execute actions when multiple check boxes selected? - java

When the user selects the multiple check boxes I need to execute the following with the same name. How to use the for loop condition for this?
I tried to use the if-else if but only one selection gets executed. Is there any way to implement for loop to reduce the code length?
I am using JFrame absolute layout so the checkbox variables already get pre-defined. I can't able to use an array.
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 512, 263);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Checkout Suite:");
lblNewLabel.setBounds(10, 11, 104, 20);
contentPane.add(lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.addItem("Platform - Desktop");
comboBox.addItem("Platform - Mobile");
comboBox.setBounds(124, 11, 331, 20);
contentPane.add(comboBox);
JLabel lblNewLabel_1 = new JLabel("Locales:");
lblNewLabel_1.setBounds(10, 53, 79, 34);
contentPane.add(lblNewLabel_1);
JCheckBox chckbxNewCheckBox = new JCheckBox("A");
chckbxNewCheckBox.setBounds(17, 94, 63, 23);
contentPane.add(chckbxNewCheckBox);
JCheckBox chckbxNewCheckBox_1 = new JCheckBox("B");
chckbxNewCheckBox_1.setBounds(104, 94, 63, 23);
contentPane.add(chckbxNewCheckBox_1);
JCheckBox chckbxNewCheckBox_2 = new JCheckBox("C");
chckbxNewCheckBox_2.setBounds(177, 94, 72, 23);
contentPane.add(chckbxNewCheckBox_2);
JCheckBox chckbxNewCheckBox_3 = new JCheckBox("D");
chckbxNewCheckBox_3.setBounds(17, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_3);
JCheckBox chckbxNewCheckBox_4 = new JCheckBox("E");
chckbxNewCheckBox_4.setBounds(104, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_4);
JCheckBox chckbxNewCheckBox_5 = new JCheckBox("F");
chckbxNewCheckBox_5.setBounds(177, 133, 72, 23);
contentPane.add(chckbxNewCheckBox_5);
JCheckBox chckbxNewCheckBox_6 = new JCheckBox("G");
chckbxNewCheckBox_6.setBounds(17, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_6);
JCheckBox chckbxNewCheckBox_7 = new JCheckBox("H");
chckbxNewCheckBox_7.setBounds(104, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_7);
JCheckBox chckbxNewCheckBox_8 = new JCheckBox("I");
chckbxNewCheckBox_8.setBounds(177, 174, 72, 23);
contentPane.add(chckbxNewCheckBox_8);
JButton btnNewButton = new JButton("Create Test Run");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(comboBox.getSelectedItem().equals("PLatform - Desktop"))
{
System.setProperty("webdriver.chrome.driver","\\chromedriver_win32\\chromedriver.exe");
WebDriver aru=new ChromeDriver();
aru.manage().window().maximize();
aru.get("https://google.com");
//Testrail Login
aru.findElement(By.id("name")).sendKeys("gmail#gmail.com");
aru.findElement(By.id("password")).sendKeys("xyz");
aru.findElement(By.id("button_primary")).click(); //Login
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
aru.findElement(By.xpath("//*[#id=\"suite-22496\"]/div[2]/div[1]/a")).click();
aru.findElement(By.xpath("//*[#id=\"content-header\"]/div/div[2]/a[1]")).click();
aru.findElement(By.xpath("//*[#id=\"includeSpecific\"]")).click();
aru.findElement(By.xpath("//*[#id=\"includeSpecificInfo\"]/a")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
aru.findElement(By.xpath("//*[#id=\"selectCasesNode-744350\"]/input")).click();
aru.findElement(By.id("selectCasesSubmit")).click();
//Suite Name
aru.findElement(By.id("name")).clear();
DateFormat today = new SimpleDateFormat("MM/dd/yyyy ");
Date palani = new Date();
String content= today.format(palani);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(chckbxNewCheckBox.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - A - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_1.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - B - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_2.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - C - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_3.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - D - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_4.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - E - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_5.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - F - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_6.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - G - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_7.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - H - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_8.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - I - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else
{
JOptionPane.showMessageDialog(null, "Please select from list");
}
}
}
});
btnNewButton.setBounds(285, 122, 169, 34);
contentPane.add(btnNewButton);
}
}

If you use else if it will stop executing further cases as soon as one if returns true. One way to maybe reduce your code a bit would be by adding all the Checkboxes to an ArrayList and then loop through that.
List<JCheckBox> cbList = new ArrayList<>();
JCheckBox chckbxNewCheckBox = new JCheckBox("US");
chckbxNewCheckBox.setBounds(17, 94, 63, 23);
contentPane.add(chckbxNewCheckBox);
cbList.add(chckbxNewCheckBox);
JCheckBox chckbxNewCheckBox_1 = new JCheckBox("UK");
chckbxNewCheckBox_1.setBounds(104, 94, 63, 23);
contentPane.add(chckbxNewCheckBox_1);
cbList.add(chckbxNewCheckBox_1);
JCheckBox chckbxNewCheckBox_2 = new JCheckBox("IN");
chckbxNewCheckBox_2.setBounds(177, 94, 72, 23);
contentPane.add(chckbxNewCheckBox_2);
cbList.add(chckbxNewCheckBox_2);
JCheckBox chckbxNewCheckBox_3 = new JCheckBox("JP");
chckbxNewCheckBox_3.setBounds(17, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_3);
cbList.add(chckbxNewCheckBox_3);
JCheckBox chckbxNewCheckBox_4 = new JCheckBox("FR");
chckbxNewCheckBox_4.setBounds(104, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_4);
cbList.add(chckbxNewCheckBox_4);
JCheckBox chckbxNewCheckBox_5 = new JCheckBox("DE");
chckbxNewCheckBox_5.setBounds(177, 133, 72, 23);
contentPane.add(chckbxNewCheckBox_5);
cbList.add(chckbxNewCheckBox_5);
JCheckBox chckbxNewCheckBox_6 = new JCheckBox("ES");
chckbxNewCheckBox_6.setBounds(17, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_6);
cbList.add(chckbxNewCheckBox_6);
JCheckBox chckbxNewCheckBox_7 = new JCheckBox("IT");
chckbxNewCheckBox_7.setBounds(104, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_7);
cbList.add(chckbxNewCheckBox_7);
JCheckBox chckbxNewCheckBox_8 = new JCheckBox("CA");
chckbxNewCheckBox_8.setBounds(177, 174, 72, 23);
contentPane.add(chckbxNewCheckBox_8);
cbList.add(chckbxNewCheckBox_8);
Alexeys comment got me thinking about checking wether or not any Checkboxes were selected, which might be useful to check at first.
private boolean selectionWasMade()
{
int selectedCounter = 0;
for(JCheckBox checkbox : cbList)
{
if(checkbox.isSelected())
{
selectedCounter++;
}
}
if(selectedCounter != 0)
{
return true;
}
return false;
}
Now you simply check if this returns true and execute this loop:
if(selectionWasMade())
{
for(JCheckBox checkbox : cbList)
{
if(checkbox.isSelected())
{
aru.findElement(By.id("name")).sendKeys("SNS - Checkout Preflight - Desktop - " + checkbox.getText() + " - "+content);
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Please select from list");
}
Hope I could help, my answer should be all cleaned up and correct now after several edits!

Related

Overwrite JLabels when different selections are selected in JComboBox?

I have a JComboBox that retrieves it's data from a database (Ahmed, Mahmoud, Ali).
when I select the first option, it displays the information of Ahmed that I retrieved from the database and shown in a JFrame as text of a JLabels
The problem is that when I choose the second option, it overwrites the informations of Ahmed with Mahmoud's and display it above.
JPanel calendarPanel = new JPanel();
calendarPanel.setToolTipText("");
calendarPanel.setBorder(new TitledBorder(null, "Calendar Panel", TitledBorder.LEADING, TitledBorder.TOP, null, null));
calendarPanel.setBounds(12, 13, 878, 254);
frameDetails.getContentPane().add(calendarPanel);
calendarPanel.setLayout(null);
JLabel lblSat = new JLabel("Saturday");
lblSat.setBounds(12, 70, 56, 16);
calendarPanel.add(lblSat);
JLabel lblSun = new JLabel("Sunday");
lblSun.setBounds(12, 99, 56, 16);
calendarPanel.add(lblSun);
JLabel lblMon = new JLabel("Monday");
lblMon.setBounds(12, 128, 56, 16);
calendarPanel.add(lblMon);
JLabel lblTus = new JLabel("Tuesday");
lblTus.setBounds(12, 157, 56, 16);
calendarPanel.add(lblTus);
JLabel lblWes = new JLabel("Wednesday");
lblWes.setBounds(12, 187, 77, 16);
calendarPanel.add(lblWes);
JLabel lblThur = new JLabel("Thursday");
lblThur.setBounds(12, 217, 56, 16);
calendarPanel.add(lblThur);
JPanel panel_12 = new JPanel();
String statment12 = "select f310t410 from calendar where days='saturday'";
panelColorChanger(panel_12, statment12);
panel_12.setForeground(Color.LIGHT_GRAY);
panel_12.setBounds(144, 64, 90, 21);
calendarPanel.add(panel_12);
JPanel panel_14 = new JPanel();
String statment14 = "select f420t520 from calendar where days='saturday'";
panelColorChanger(panel_14, statment14);
panel_14.setForeground(Color.LIGHT_GRAY);
panel_14.setBounds(300, 64, 90, 21);
calendarPanel.add(panel_14);
String statment16 = "select f530t630 from calendar where days='saturday'";
String statment18 = "select f640t740 from calendar where days='saturday'";
String statment110 = "select f750t850 from calendar where days='saturday'";
JPanel panel_22 = new JPanel();
panel_22.setForeground(Color.LIGHT_GRAY);
String statment22 = "select f310t410 from calendar where days='sunday'";
panelColorChanger(panel_22, statment22);
panel_22.setBounds(145, 92, 90, 24);
calendarPanel.add(panel_22);
JPanel panel_24 = new JPanel();
panel_24.setForeground(Color.LIGHT_GRAY);
String statment24 = "select f420t520 from calendar where days='sunday'";
panelColorChanger(panel_24, statment24);
panel_24.setBounds(301, 92, 90, 24);
calendarPanel.add(panel_24);
String statment26 = "select f530t630 from calendar where days='sunday'";
String statment28 = "select f640t740 from calendar where days='sunday'";
String statment210 = "select f750t850 from calendar where days='sunday'";
JPanel panel_32 = new JPanel();
panel_32.setForeground(Color.LIGHT_GRAY);
String statment32 = "select f310t410 from calendar where days='monday'";
panelColorChanger(panel_32, statment32);
panel_32.setBounds(145, 122, 90, 22);
calendarPanel.add(panel_32);
JPanel panel_34 = new JPanel();
panel_34.setForeground(Color.LIGHT_GRAY);
String statment34 = "select f420t520 from calendar where days='monday'";
panelColorChanger(panel_34, statment34);
panel_34.setBounds(301, 122, 90, 22);
calendarPanel.add(panel_34);
String statment36 = "select f530t630 from calendar where days='monday'";
String statment38 = "select f640t740 from calendar where days='monday'";
String statment310 = "select f750t850 from calendar where days='monday'";
JPanel panel_42 = new JPanel();
panel_42.setForeground(Color.LIGHT_GRAY);
String statment42 = "select f310t410 from calendar where days='tuesday'";
panelColorChanger(panel_42, statment42);
panel_42.setBounds(145, 149, 90, 23);
calendarPanel.add(panel_42);
JPanel panel_44 = new JPanel();
panel_44.setForeground(Color.LIGHT_GRAY);
String statment44 = "select f420t520 from calendar where days='tuesday'";
panelColorChanger(panel_44, statment44);
panel_44.setBounds(301, 149, 90, 23);
calendarPanel.add(panel_44);
String statment46 = "select f530t630 from calendar where days='tuesday'";
String statment48 = "select f640t740 from calendar where days='tuesday'";
String statment410 = "select f750t850 from calendar where days='tuesday'";
JPanel panel_52 = new JPanel();
panel_52.setForeground(Color.LIGHT_GRAY);
String statment52 = "select f310t410 from calendar where days='wednesday'";
panelColorChanger(panel_52, statment52);
panel_52.setBounds(145, 179, 90, 25);
calendarPanel.add(panel_52);
JPanel panel_54 = new JPanel();
panel_54.setForeground(Color.LIGHT_GRAY);
String statment54 = "select f420t520 from calendar where days='wednesday'";
panelColorChanger(panel_54, statment54);
panel_54.setBounds(301, 179, 90, 25);
calendarPanel.add(panel_54);
String statment56 = "select f530t630 from calendar where days='wednesday'";
String statment58 = "select f640t740 from calendar where days='wednesday'";
String statment510 = "select f750t850 from calendar where days='wednesday'";
JPanel panel_62 = new JPanel();
panel_62.setForeground(Color.LIGHT_GRAY);
String statment62 = "select f310t410 from calendar where days='thursday'";
panelColorChanger(panel_62, statment62);
panel_62.setBounds(145, 209, 90, 24);
calendarPanel.add(panel_62);
JPanel panel_64 = new JPanel();
panel_64.setForeground(Color.LIGHT_GRAY);
String statment64 = "select f420t520 from calendar where days='thursday'";
panelColorChanger(panel_64, statment64);
panel_64.setBounds(301, 209, 90, 24);
calendarPanel.add(panel_64);
String statment66 = "select f530t630 from calendar where days='thursday'";
String statment68 = "select f640t740 from calendar where days='thursday'";
String statment610 = "select f750t850 from calendar where days='thursday'";
////////////////////////////////////////////////////////////////////////////////Calendar Table
////////////////////////////////////////////////////////////////////////////////Add Patient
patientPanel = new JPanel();
patientPanel.setLayout(null);
patientPanel.setBorder(new TitledBorder(null, "Add New Patient", TitledBorder.LEADING, TitledBorder.TOP, null, null));
patientPanel.setBounds(12, 280, 1304, 163);
frameDetails.getContentPane().add(patientPanel);
lblName = new JLabel("Name");
lblName.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblName.setBounds(31, 24, 56, 16);
patientPanel.add(lblName);
txtName = new JTextField();
txtName.setBounds(120, 24, 240, 22);
patientPanel.add(txtName);
txtName.setColumns(10);
lblAge = new JLabel("Age");
lblAge.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblAge.setBounds(31, 59, 56, 23);
patientPanel.add(lblAge);
lblMobile = new JLabel("Mobile");
lblMobile.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblMobile.setBounds(31, 95, 56, 16);
patientPanel.add(lblMobile);
txtAge = new JTextField();
txtAge.setColumns(10);
txtAge.setBounds(120, 59, 240, 22);
patientPanel.add(txtAge);
txtMobile = new JTextField();
txtMobile.setColumns(10);
txtMobile.setBounds(120, 95, 240, 22);
patientPanel.add(txtMobile);
JComboBox comboBoxDays = new JComboBox();
List<String> arrDays = new ArrayList<String>();
//arrDays.add("44444444");
//comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray()));
comboBoxDays.setBounds(474, 24, 127, 22);
patientPanel.add(comboBoxDays);
JComboBox comboBoxTime = new JComboBox();
List<String> arrTime = new ArrayList<String>();
arrTime.add("");
comboBoxTime.setModel(new DefaultComboBoxModel(arrTime.toArray()));
// add time available to list of times when select a day
comboBoxDays.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
comboBoxTime.setBounds(474, 61, 127, 22);
patientPanel.add(comboBoxTime);
JLabel lblDay = new JLabel("Day");
lblDay.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDay.setBounds(389, 27, 56, 16);
patientPanel.add(lblDay);
JLabel lblTime = new JLabel("Time");
lblTime.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblTime.setBounds(389, 64, 56, 16);
patientPanel.add(lblTime);
JLabel lblDescription = new JLabel("Description");
lblDescription.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDescription.setBounds(31, 132, 77, 22);
patientPanel.add(lblDescription);
txtDescription = new JTextField();
txtDescription.setColumns(10);
txtDescription.setBounds(120, 132, 240, 22);
patientPanel.add(txtDescription);
JButton btnAddNewPatient = new JButton("Add New Patient");
btnAddNewPatient.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String radioText = "Not Confirmed";
try {
if (txtName.getText().isEmpty() || txtAge.getText().isEmpty() || txtMobile.getText().isEmpty() || txtDescription.getText().isEmpty() || comboBoxDays.getSelectedItem().toString().isEmpty() || comboBoxTime.getSelectedItem().toString().isEmpty())
{
JOptionPane.showMessageDialog(null, "Please fill empty fields!");
}
else {
//to insert the patient name with his time into table patientCalender
String statInsertPatient = "insert into patientCalendar values ('"+txtName.getText()+"','"+comboBoxDays.getSelectedItem().toString()+"','"+comboBoxTime.getSelectedItem().toString()+"')";
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnAddNewPatient.setBounds(630, 24, 194, 58);
patientPanel.add(btnAddNewPatient);
////////////////////////////////////////////////////////////////////////////////Add Patient
////////////////////////////////////////////////////////////////////////////////Details table
detailsPanel = new JPanel();
detailsPanel.setLayout(null);
detailsPanel.setToolTipText("");
detailsPanel.setBorder(new TitledBorder(null, "Details", TitledBorder.LEADING, TitledBorder.TOP, null, null));
detailsPanel.setBounds(12, 456, 1304, 252);
frameDetails.getContentPane().add(detailsPanel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 32, 940, 207);
detailsPanel.add(scrollPane);
detailsTable = new JTable();
scrollPane.setViewportView(detailsTable);
detailsTable.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
}
));
detailsTable.setBorder(new LineBorder(new Color(0, 0, 0)));
textFieldSearch = new JTextField();
textFieldSearch.setToolTipText("Enter Patient Name");
textFieldSearch.setBounds(1034, 45, 179, 29);
detailsPanel.add(textFieldSearch);
textFieldSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
}
}
);
textFieldSearch.setColumns(10);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from patient where name='"+textFieldSearch.getText() +"' ";
PreparedStatement pst= connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null , "Deleted ");
pst.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
);
btnDelete.setBounds(1065, 133, 116, 40);
detailsPanel.add(btnDelete);
JButton btnShow = new JButton("Show All");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from patient ";
PreparedStatement pst= connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
detailsTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception el) {
el.printStackTrace();
}
}
});
btnShow.setBounds(1065, 178, 116, 42);
detailsPanel.add(btnShow);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from patient where name=?";
PreparedStatement pst= connection.prepareStatement(query);
pst.setString(1, textFieldSearch.getText() );
ResultSet rs = pst.executeQuery();
detailsTable.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
});
btnSearch.setBounds(1065, 87, 116, 40);
detailsPanel.add(btnSearch);
////////////////////////////////////////////////////////////////////////////////Details table
////////////////////////////////////////////////////////////////////////////////Set Calendar
JPanel setCalendarPanel = new JPanel();
setCalendarPanel.setBorder(new TitledBorder(null, "Set Calender Days", TitledBorder.LEADING, TitledBorder.TOP, null, null));
setCalendarPanel.setBounds(902, 24, 260, 243);
frameDetails.getContentPane().add(setCalendarPanel);
setCalendarPanel.setLayout(null);
chckbxSaturday = new JCheckBox("Saturday");
chckbxSaturday.setBounds(8, 54, 160, 25);
setCalendarPanel.add(chckbxSaturday);
chckbxSunday = new JCheckBox("Sunday");
chckbxSunday.setBounds(8, 84, 160, 25);
setCalendarPanel.add(chckbxSunday);
chckbxMonday = new JCheckBox("Monday");
chckbxMonday.setBounds(8, 116, 160, 25);
setCalendarPanel.add(chckbxMonday);
chckbxTuesday = new JCheckBox("Tuesday");
chckbxTuesday.setBounds(8, 146, 160, 25);
setCalendarPanel.add(chckbxTuesday);
chckbxWednesday = new JCheckBox("Wednesday");
chckbxWednesday.setBounds(8, 178, 160, 25);
setCalendarPanel.add(chckbxWednesday);
chckbxThursday = new JCheckBox("Thursday");
chckbxThursday.setBounds(8, 209, 87, 25);
setCalendarPanel.add(chckbxThursday);
JLabel lblPleaseSelectAvailable = new JLabel("Please select available days: ");
lblPleaseSelectAvailable.setFont(new Font("Tahoma", Font.BOLD, 16));
lblPleaseSelectAvailable.setBounds(8, 19, 239, 37);
setCalendarPanel.add(lblPleaseSelectAvailable);
//////////////////////////////////
//Set selected days on launch to add the selected days to comboBoxDays
String sqlquery11 = "select f310t410 from calendar WHERE calendar.days='saturday'";
String panelColor11= connect2databaseWithexecuteQuery(sqlquery11);
if (panelColor11.contentEquals("white") || panelColor11.contentEquals("green") || panelColor11.contentEquals("red")){
chckbxSaturday.setSelected(true);
}
String sqlquery22 = "select f310t410 from calendar WHERE calendar.days='sunday'";
String panelColor22= connect2databaseWithexecuteQuery(sqlquery22);
if (panelColor22.contentEquals("white") || panelColor22.contentEquals("green") || panelColor22.contentEquals("red"))
{
chckbxSunday.setSelected(true);
}
String sqlquery33 = "select f310t410 from calendar WHERE calendar.days='monday'";
String panelColor33= connect2databaseWithexecuteQuery(sqlquery33);
if (panelColor33.contentEquals("white") || panelColor33.contentEquals("green") || panelColor33.contentEquals("red"))
{
chckbxMonday.setSelected(true);
}
String sqlquery44 = "select f310t410 from calendar WHERE calendar.days='tuesday'";
String panelColor44= connect2databaseWithexecuteQuery(sqlquery44);
if (panelColor44.contentEquals("white") || panelColor44.contentEquals("green") || panelColor44.contentEquals("red"))
{
chckbxTuesday.setSelected(true);
}
String sqlquery55 = "select f310t410 from calendar WHERE calendar.days='wednesday'";
String panelColor55= connect2databaseWithexecuteQuery(sqlquery55);
if (panelColor55.contentEquals("white") || panelColor55.contentEquals("green") || panelColor55.contentEquals("red"))
{
chckbxWednesday.setSelected(true);
}
String sqlquery66 = "select f310t410 from calendar WHERE calendar.days='thursday'";
String panelColor66= connect2databaseWithexecuteQuery(sqlquery66);
if (panelColor66.contentEquals("white") || panelColor66.contentEquals("green") || panelColor66.contentEquals("red")){
chckbxThursday.setSelected(true);
}
///***************
//check if checkboxes selected to add their text to comboBoxDays
arrDays.add("");
if (chckbxSaturday.isSelected()){
arrDays.add("Saturday");
}
if (chckbxSunday.isSelected()){
arrDays.add("Sunday");
}
if (chckbxMonday.isSelected()){
arrDays.add("Monday");
}
if (chckbxTuesday.isSelected()){
arrDays.add("Tuesday");
}
if (chckbxWednesday.isSelected()){
arrDays.add("Wednesday");
}
if (chckbxThursday.isSelected()){
arrDays.add("Thursday");
}
comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray()));
JButton btnUpdatePatientStatus = new JButton("Update Patient Status");
btnUpdatePatientStatus.setBounds(843, 21, 194, 58);
patientPanel.add(btnUpdatePatientStatus);
////////////////////////////////
JButton btnSetCalender = new JButton("Set Calender"); // Button Set Calendar
btnSetCalender.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (chckbxSaturday.isSelected()){
//access database
//make colms of Saturday all white
if(arrDays.contains("Saturday") == false){
arrDays.add("Saturday");
}
}
else
{
//access database
//make colms of Saturday all gray
if(arrDays.contains("Saturday") == true){
arrDays.remove("Saturday");
}
}
if (chckbxSunday.isSelected()){
//access database
//make colms of Sunday all white
if(arrDays.contains("Sunday") == false){
arrDays.add("Sunday");
}
}
else
{
//access database
//make colms of Sunday all gray
if(arrDays.contains("Sunday") == true){
arrDays.remove("Sunday");
}
}
if (chckbxMonday.isSelected()){
//access database
//make colms of Monday all white
if(arrDays.contains("Monday") == false){
arrDays.add("Monday");
}
}
else
{
//access database
//make colms of Monday all gray
if(arrDays.contains("Monday") == true){
arrDays.remove("Monday");
}
}
if (chckbxTuesday.isSelected()){
//access database
//make colms of Tuesday all white
if(arrDays.contains("Tuesday") == false){
arrDays.add("Tuesday");
}
}
else
{
//access database
//make colms of Tuesday all gray
if(arrDays.contains("Tuesday") == true){
arrDays.remove("Tuesday");
}
}
if (chckbxWednesday.isSelected()){
//access database
//make colms of Wednesday all white
if(arrDays.contains("Wednesday") == false){
arrDays.add("Wednesday");
}
}
else
{
//access database
//make colms of Wednesday all gray
if(arrDays.contains("Wednesday") == true){
arrDays.remove("Wednesday");
}
}
if (chckbxThursday.isSelected()){
//access database
//make colms of Thursday all white
if(arrDays.contains("Thursday") == false){
arrDays.add("Thursday");
}
}
else
{
//access database
//make colms of Thursday all gray
if(arrDays.contains("Thursday") == true){
arrDays.remove("Thursday");
}
}
comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray())); //Days ComboBox
JOptionPane.showMessageDialog(null, "Calendar Set Successfully!","Calender Set",JOptionPane.DEFAULT_OPTION);
}
});
btnSetCalender.setBounds(104, 203, 146, 37);
setCalendarPanel.add(btnSetCalender);
///////////////////////////////////////////////////////////////////////////////////////////Add Doctor
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Add/Choose Doctor", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(1174, 24, 162, 241);
frameDetails.getContentPane().add(panel);
panel.setLayout(null);
comboBoxDoctorsNames = new JComboBox();
arrDoctors = new ArrayList<String>();
arrDoctors.add("");
arrDoctors.addAll(getMultiDocsNames());
System.out.println(getMultiDocsNames());
comboBoxDoctorsNames.setModel(new DefaultComboBoxModel(arrDoctors.toArray()));
comboBoxDoctorsNames.setBounds(12, 49, 138, 22);
panel.add(comboBoxDoctorsNames);
comboBoxDoctorsNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String selectedDoctor = comboBoxDoctorsNames.getSelectedItem().toString();
String query = "select * from '"+selectedDoctor+"'";
List<String> arrColms = new ArrayList<String>();
List<JLabel> arrLbls = new ArrayList<JLabel>();
int boundTimelbl = 162;
try {
//access the table and get colms names
Connection con = DriverManager.getConnection("jdbc:sqlite:DoctorProject.db");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 2; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
if(arrColms.contains(name) == false){
arrColms.add(name);
}
}
for (String colm : arrColms) {
mTimelbl = new JLabel();
mTimelbl.setText(colm);
mTimelbl.setBounds(boundTimelbl, 35, 56, 16);
boundTimelbl = boundTimelbl + 156;
arrLbls.add(mTimelbl);
}
Component[] components = calendarPanel.getComponents();
for (Component component : components) {
if (component instanceof JLabel) {
jPanel1.remove(component);
}
}
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
calendarPanel.revalidate();
calendarPanel.repaint();
System.out.println(arrColms);
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
try to use calendarPanel.removeAll(); before to remove all components
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
or use before the loop that I mentioned to remove labels only
Component[] components = calendarPanel.getComponents();
for (Component component : components) {
if (component instanceof JLabel) {
calendarPanel.remove(component);
}
}
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
but to remove our last added Labels we should first store them somewhere so first we create a List of JLabels
private final List<JLabel> myPreviousAddedLabels = new ArrayList<JLabel>();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String selectedDoctor = comboBoxDoctorsNames.getSelectedItem().toString();
then you should use this
for (JLabel component : myPreviousAddedLabels) {
calendarPanel.remove(component);
}
myPreviousAddedLabels.clear();
for (JLabel mLbl : arrLbls) {
myPreviousAddedLabels.add(mLbl);
calendarPanel.add(mLbl);
}
calendarPanel.revalidate();
calendarPanel.repaint();

how to dedug in eclipse and solve Unknown Source erros

/*this is my java code which when i compile they don not show exactly error */
public class Login {
public JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conections;
private JTextField textField;
private JPasswordField passwordField;
public Login() {
initialize();
conections = SqliteConnectio.dbConnection();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 581, 411);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(266, 112, 193, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnLOGIN = new JButton("LOGIN");
Image jn=new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLOGIN.setIcon(new ImageIcon(jn));
btnLOGIN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select *from customer.sqlite where username=? and password=? ";
PreparedStatement pre = conections.prepareStatement(query);
pre.setString(1, textField.getText());
pre.setString(2, passwordField.getText());
ResultSet res = pre.executeQuery();
int count = 0;
while (res.next()) {
count++;
}
if (count == 1) {
JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
} else if (count > 1) {JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
}
else {
JOptionPane.showInternalMessageDialog(null, "username and password has been failed to be entered");
}
res.close();
pre.close();
} catch (Exception e) {
JOptionPane.showInternalMessageDialog(null, "you have failed to asses the database");
}
}
});
btnLOGIN.setBounds(321, 256, 125, 36);
frame.getContentPane().add(btnLOGIN);
JLabel userNAME = new JLabel("USERNAME");
userNAME.setBounds(156, 127, 85, 14);
frame.getContentPane().add(userNAME);
JLabel passLABEL = new JLabel("PASSWORD");
passLABEL.setBounds(156, 191, 85, 14);
frame.getContentPane().add(passLABEL);
passwordField = new JPasswordField();
passwordField.setBounds(266, 188, 193, 20);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("New label");
Image im=new ImageIcon(this.getClass().getResource("/login.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(im));
lblNewLabel.setBounds(10, 21, 136, 205);
frame.getContentPane().add(lblNewLabel);
}
}
//this is my connection to database which it seems to work just fine by prompting "username and password has sucseeful inserted"
package mi;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SqliteConnectio {
Connection conect=null;
public static Connection dbConnection(){
try {
Class.forName("org.sqlite.JDBC");
Connection conect=DriverManager.getConnection(
"jdbc:sqlite:E:\\JAVA WORLD\\sgliteDatabase\\customer.sqlite");
JOptionPane.showMessageDialog(null, "sucessful login to database");
return conect;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, "failed to login in database");
return null;
}
}
}

XOR Cipher encryption being messed up with my GUI?

I've setup a simple GUI system to use this XOR encryption system. When I decrypt through the GUI the decryption comes out wrong, but when I hard-code the string to decrypt it comes out right. For example:
For example, this prints "this_is_to_test_if_the_program_in_the_gui_is_working_which_it_wont":
System.out.println(Skeleton.xorDecrypt("BX_Dg_CgLVkCVKLfQUfC^SgHFWSFY^oP]iBPShSC]g^KgO[D\\Q]Qg#PQTPk^MiA_VD", "638460047789894"));
But if I do it through the GUI it comes out as "this_is_to_test_if_the_program_in_the_gui_is_workdiia_xdglf\g{Qykns"
Skeleton.java
public class Skeleton {
public static String xorEncrypt(String data, String key) {
data = data.replaceAll(" ", "_");
byte m_cData[] = data.getBytes();
byte m_cKey[] = key.getBytes();
int keyPointer = 0;
for (int i = 0; i < m_cData.length; i++) {
m_cData[i] ^= m_cKey[keyPointer];
keyPointer += m_cData[i];
keyPointer %= m_cKey.length;
}
return new String(m_cData).replaceAll("\\\\", "\\\\\\\\");
}
public static String xorDecrypt(String data, String key) {
byte m_cData[] = data.getBytes();
byte m_cKey[] = key.getBytes();
int keyPointer = 0;
byte keyPointerAdd = 0;
for (int i = 0; i < m_cData.length; i++) {
keyPointerAdd = m_cData[i];
m_cData[i] ^= m_cKey[keyPointer];
keyPointer += keyPointerAdd;
keyPointer %= m_cKey.length;
}
return new String(m_cData);
}
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
}
Window.java
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textPasscode;
public Window() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exception) {
exception.printStackTrace();
}
setTitle("Saypar");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 381);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textPasscode = new JTextField();
textPasscode.setBounds(94, 278, 241, 20);
contentPane.add(textPasscode);
textPasscode.setColumns(10);
JLabel lblPasscode = new JLabel("Passcode (#):");
lblPasscode.setBounds(10, 281, 74, 14);
contentPane.add(lblPasscode);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 424, 256);
contentPane.add(scrollPane);
JTextArea textAreaMessage = new JTextArea();
scrollPane.setViewportView(textAreaMessage);
textAreaMessage.setLineWrap(true);
textAreaMessage.setWrapStyleWord(true);
JButton btnEncrypt = new JButton("Encrypt");
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (textAreaMessage.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a message before encrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (textPasscode.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a passcode before encrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
StringSelection stringSelection = new StringSelection(Skeleton.xorEncrypt(textAreaMessage.getText(), textPasscode.getText()));
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
JOptionPane.showMessageDialog(null, "Message Encrypted... Copied to clipboard.", "Encrypted Message", JOptionPane.PLAIN_MESSAGE);
}
});
btnEncrypt.setBounds(345, 277, 89, 23);
contentPane.add(btnEncrypt);
JButton btnDecrypt = new JButton("Decrypt");
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (textAreaMessage.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a message before decrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (textPasscode.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a passcode before decrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
StringSelection stringSelection = new StringSelection(Skeleton.xorDecrypt(textAreaMessage.getText(), textPasscode.getText()));
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
JOptionPane.showMessageDialog(null, "Message Decrypted... Copied to clipboard.", "Decrypted Message", JOptionPane.PLAIN_MESSAGE);
}
});
btnDecrypt.setBounds(345, 311, 89, 23);
contentPane.add(btnDecrypt);
JButton btnGeneratePasscode = new JButton("Generate Random Passcode");
btnGeneratePasscode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textPasscode.setText("" + Skeleton.generateRandom(15));
}
});
btnGeneratePasscode.setBounds(107, 311, 228, 23);
contentPane.add(btnGeneratePasscode);
JLabel lblRecommended = new JLabel("RECOMMENDED:");
lblRecommended.setBounds(10, 315, 99, 14);
contentPane.add(lblRecommended);
}
}

Java Applet - How can i show an image when a button is clicked?

Hi new here at Stack Overflow. Well i am trying to make an Applet that will show the image package of the selected button and im new to java programming. Can someone help me how to use the code to display the image? here's my code:
public void init()
{
// Buttons/Labels/Etc
setBackground(Color.white);
this.setLayout(null);
packageB = new Button("Budget");
add(packageB);
packageB.setBounds(200, 20, 80, 20);
packageP = new Button("Premium");
add(packageP);
packageP.setBounds(300, 20, 80, 20);
sButton = new Button("Silver");
add(sButton);
sButton.setBounds(100, 20, 80, 20);
sButton.setVisible(false);
gButton = new Button("Gold");
add(gButton);
gButton.setBounds(200, 20, 80, 20);
gButton.setVisible(false);
pButton = new Button("Platinum");
add(pButton);
pButton.setBounds(300, 20, 80, 20);
pButton.setVisible(false);
dButton = new Button("Diamon");
add(dButton);
dButton.setBounds(400, 20, 80, 20);
dButton.setVisible(false);
backButton = new Button("<-- Back");
add(backButton);
backButton.setBounds(500, 20, 80, 20);
backButton.setVisible(false);
notice = new Label("CHOOSE YOUR PACKAGE!");
add(notice);
notice.setBounds(215, 0, 200, 20);
notice2 = new Label("WHAT PACKAGE DO YOU WANT?");
add(notice2);
notice2.setBounds(205, 0, 200, 20);
notice2.setVisible(false);
sLabel = new Label("Test Label");
add(sLabel);
sLabel.setBounds(205, 0, 200, 20);
sLabel.setVisible(false);
//adds an ActionListener to all of the buttons to be able to receive commands
packageB.addActionListener(this);
packageP.addActionListener(this);
backButton.addActionListener(this);
sButton.addActionListener(this);
gButton.addActionListener(this);
pButton.addActionListener(this);
dButton.addActionListener(this);
}
public void paint(Graphics g)
{
this.resize(600,400);
g.setColor(Color.black);
g.fillRect(60,50,460,300);
}
// receiver of the ActionListener method
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == packageB)
{
packageB.setVisible(false);
packageP.setVisible(false);
notice.setVisible(false);
notice2.setVisible(true);
backButton.setVisible(true);
}
else if (e.getSource() == packageP)
{
packageB.setVisible(false);
packageP.setVisible(false);
backButton.setVisible(true);
notice.setVisible(false);
notice2.setVisible(true);
sButton.setVisible(true);
gButton.setVisible(true);
pButton.setVisible(true);
dButton.setVisible(true);
}
else if (e.getSource() == backButton)
{
packageB.setVisible(true);
packageP.setVisible(true);
notice2.setVisible(false);
notice.setVisible(true);
backButton.setVisible(false);
sButton.setVisible(false);
gButton.setVisible(false);
pButton.setVisible(false);
dButton.setVisible(false);
}
else if (e.getSource() == sButton)
{
sButton.setBackground(Color.red);
gButton.setBackground(Color.lightGray);
pButton.setBackground(Color.lightGray);
dButton.setBackground(Color.lightGray);
sLabel.setVisible(true);
}
else if (e.getSource() == gButton)
{
sButton.setBackground(Color.lightGray);
gButton.setBackground(Color.red);
pButton.setBackground(Color.lightGray);
dButton.setBackground(Color.lightGray);
}
else if (e.getSource() == pButton)
{
sButton.setBackground(Color.lightGray);
gButton.setBackground(Color.lightGray);
pButton.setBackground(Color.red);
dButton.setBackground(Color.lightGray);
}
else if (e.getSource() == dButton)
{
sButton.setBackground(Color.lightGray);
gButton.setBackground(Color.lightGray);
pButton.setBackground(Color.lightGray);
dButton.setBackground(Color.red);
}
// Add New ActionListener Here!
/*else if (e.getSource() == TestButton)
{
}*/
}
}

SWT NullPointerException

I have a client and server. Server sends some questions to the Client. In client side I want to display these questions on a SWT application window.
I use one thread to show the window and main thread contacts with the Server. After client receives the questions, NullPointerException is thrown in text widget. (writeQuestions method below). I think "q1Txt" is not null because it is initiated in "createContets" method. Besides the arraylist that have question is not null too because I checked it.
Can you help me about it?
My code is below.
public class Client {
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
new Screen().start();
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while(!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void writeQuestions(ArrayList<String> questions){
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
open();
}
}
public static void open(){
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if(ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if(!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText()) ){
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
}else
isAnswered = true;
}
}
);
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}
I'm pretty sure the problem is the later execution for the "createContent".
We need to ensure that component will use after it creation
Try this:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Client{
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
Screen screen = new Screen();
screen.setCreationComplete(new CreationCompleteAction());
}
private static class Screen extends Thread {
Runnable creationCompleteAction;
public void setCreationComplete(Runnable action){
this.creationCompleteAction = action;
}
public void run() {
Display display = Display.getDefault();
createContents();
if(creationCompleteAction != null){
creationCompleteAction.run();
}
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
public static class CreationCompleteAction implements Runnable {
#Override
public void run() {
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while (!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void writeQuestions(ArrayList<String> questions) {
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if (ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if ((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if (!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText())) {
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
} else
isAnswered = true;
}
});
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}

Categories