I have two GUI classes. When I click a row in JTable in the first user interface, the second interface should display the corresponding values in JLabels.
But the second user interface does not show the values.
Here's my first GUI class:
public class ChequeGUI extends JFrame {
public String chqNo;
public String payName;
public double chkAmount = 10;
public Date chkDate;
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Cheque Number","Payee Name","Cheque Amount","Cheque Date"});
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
//guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
chqNo = (String) guiTable.getValueAt(row,0);
payName = (String) guiTable.getValueAt(row,1);
chkAmount = (Double) guiTable.getValueAt(row,2);
chkDate = (Date) guiTable.getValueAt(row, 3);
try {
PrintChequeGUI pcg = new PrintChequeGUI();
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
System.out.println(chqNo);
System.out.println(payName);
System.out.println(chkAmount);
System.out.println(chkDate);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
guiTable.setModel(model);
add(new JScrollPane(guiTable));
DBConnection connection = new DBConnection();
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
chqdi.setConnection(connection);
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getChqNum(), cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
This is my second GUI class:
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
* #throws SQLException
*/
public PrintChequeGUI() throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(gui.chqNo);
lblAmount.setText(Double.toString(gui.chkAmount));
lblName.setText(gui.payName);
lblDate.setText(String.valueOf(gui.chkDate));
}
}
This can be solved in many ways:
1.
As I mentioned in my comment, Pass the current instance of ChequeGUI to the constructor of PrintChequeGUI and use that instance instead of creating new one in PrintChequeGUI
PrintChequeGUI pcg = new PrintChequeGUI(this);
and in PrintChequeGUI class
public PrintChequeGUI(ChequeGUI gui) throws SQLException {
(but i think its not a good approach)
2.
For Better option, Pass the selected instance of Cheque to PrintChequeGUI as constructor argument. For this you need to create a TableModel with instance of Cheque.
Sample is given below:
package com.test;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
ChequeTableModel model;
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
Cheque c = model.getChequeByRow(row);
try {
PrintChequeGUI pcg = new PrintChequeGUI(c);
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
model = new ChequeTableModel();
guiTable.setModel(model);
add(new JScrollPane(guiTable));
model.loadData();
}
public class ChequeTableModel extends AbstractTableModel {
List<Cheque> dataModel;
String[] columns = { "Cheque Number", "Payee Name", "Cheque Amount",
"Cheque Date" };
public ChequeTableModel() {
super();
dataModel = new ArrayList<Cheque>();
}
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
return dataModel.size();
}
#Override
public Object getValueAt(int row, int column) {
Object value = null;
Cheque c = getChequeByRow(row);
switch (column) {
case 0:
value = c.chqNo;
break;
case 1:
value = c.payName;
break;
case 2:
value = c.chkAmount;
break;
case 3:
value = c.chkDate;
break;
default:
break;
}
return value;
}
public Cheque getChequeByRow(int row) {
if (dataModel.size() <= 0)
return null;
if (row < 0)
return null;
return dataModel.get(row);
}
public void loadData() {
/*
*
* //Uncomment this for database connection and load data from
* database; //Please note to disconnect database if not needed
*
*
* DBConnection connection = new DBConnection();
*
* // Populate Table ChequeDAOImpl chqdi = new ChequeDAOImpl();
* chqdi.setConnection(connection); List<Cheque> cheques =
* chqdi.getCheques();
*
* for (Cheque cq : cheques) { model.addRow(new Object[] {
* cq.getChqNum(), cq.getName(), cq.getAmount(), cq.getDate() }); }
*/
for (int i = 0; i < 10; i++) {
Cheque c = new Cheque();
c.chkAmount = i * 1000;
c.chqNo = String.valueOf(i);
c.chkDate = new Date(System.currentTimeMillis());
dataModel.add(c);
}
fireTableRowsInserted(0, dataModel.size());
}
}
public static void main(String[] args) throws SQLException {
ChequeGUI c = new ChequeGUI();
c.pack();
c.setVisible(true);
}
}
Second class
package com.test;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
*
* #throws SQLException
*/
public PrintChequeGUI(Cheque cheque) throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
// ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(cheque.chqNo);
lblAmount.setText(Double.toString(cheque.chkAmount));
lblName.setText(cheque.payName);
lblDate.setText(String.valueOf(cheque.chkDate));
}
}
The Cheque class you already used to get details from database
Related
I attempt to send Text Field values to Table using button click event. But using combo box I need to change Unit type as "Imperial" or "Metric".
When select "Imperial" from combo box and Click ADD Button, Table should fill using "Name" , "Unit Imperial" & "Price Imperial" Text Field values.
But When select "Metric" from combo box and Click ADD Button,Table should fill using "Name" , "Unit Metric" & "Price Metric" Text Field values.
I don't have clear idea to use comboBox Item change use to effect on Button click event. Thanks in advance to guiding me to solve this problem.
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
JComboBox cmbUType = new JComboBox();
cmbUType.setModel(new DefaultComboBoxModel(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}
You should not be using a null layout and absolute positioning. Study Swing layout managers.
A JComboBox can hold any object. You need to tell the compiler what type of object (String) you're passing. You also need to tell the compiler what type of object you're storing in the DefaultComboBoxModel.
Having said that, I made cmbUType a class variable so I could reference it in the Add button action listener.
Here's your modified code.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
private JComboBox<String> cmbUType;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String type = (String) cmbUType.getSelectedItem();
if (type.equals("Imperial")) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
} else {
row[0] = txtName.getText();
row[1] = txtUMetric.getText();
row[2] = txtPMetric.getText();
}
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
cmbUType = new JComboBox<>();
cmbUType.setModel(new DefaultComboBoxModel<String>
(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}
I want to add a dynamic checkbox after selecting an item in combo box.
I am working on eclipse and design my frame on window builder.
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
c.setVisible(true);
coursePanel.add(c);
frame.repaint();
frame.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
edit: thats my full code.
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(75, 171, 221, 39);
frame.getContentPane().add(dateChooser);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
btnSend.setBounds(258, 334, 61, 58);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// date
Date date = new Date(dateChooser.getDate().getTime());
}
});
frame.getContentPane().add(btnSend);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = c.getParent() == coursePanel;
if (selectedIndex == 1 && !isInPanel) {
coursePanel.add(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
} else if (isInPanel && selectedIndex != 1) {
coursePanel.remove(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
}
coursePanel.repaint();
coursePanel.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
List<String> lst = SqlQuery.getTypes();
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox.
Why the frame does'nt show the checkbox?
Thank you.
First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers. Also add 'swing' tag in your post since you are referring to Swing library.
The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.
Also checkBox.setVisible(true)is not required, since checkBox is visible by default.
Finally i have added the way of how i would do it.
package test;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JCheckBox checkBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createPanel());
frame.pack();
}
private JPanel createPanel() {
JPanel p = new JPanel(new FlowLayout());
checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
JComboBox<String> combo = new JComboBox<>();
combo.addItem("Hello");
combo.addItem("Stack");
combo.addItem("OverFlow");
combo.addActionListener(e -> {
//Its better to handle indices when there is not dynmic data to your combobox
int selectedIndex = combo.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == p;
if (selectedIndex == 1 && !isInPanel) {
p.add(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
} else if (isInPanel && selectedIndex != 1) {
p.remove(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
}
});
p.add(combo);
return p;
}
}
The answer to your problem (make the checkbox visible) after comments:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
private JCheckBox checkBox;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("Stack");
lst.add("Over");
lst.add("Flow");
//Prepare the checkBox
checkBox = new JCheckBox("nothing");
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < lst.size(); i++) {
checkBox.setText(typeName);
//set the same bounds as comboBox but reduce its X by 80.
//Compare checkBoxbounds and combobox bounds
//Remind: setBounds is baaaaad practice.
checkBox.setBounds(128, 221, 91, 20);
//if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == frame.getContentPane();
if (selectedIndex == 1 && !isInPanel) {
frame.getContentPane().add(checkBox);
} else if (isInPanel && selectedIndex != 1) {
frame.getContentPane().remove(checkBox);
}
frame.getContentPane().repaint();
frame.getContentPane().validate();
System.out.println(checkBox.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)
I'm new in java, and I'm working on a program using GUI. My problem is that I'm reaching 1000 Line and this is stressful because all my code are in one file. I'm not liking this. So I research the internet about Inheritance. However, I'm not sure how this can help me in my problem because all what I know about Inheritance that Inherit everything in the parent class. However, when I try to use a variables in the child class I can't for example let say that I have in the parent class something like this:
JButton getButton = new JButton("Enter");
now when I go to the child class. I want to Inherit and use this variable so I can use the ActionListener it's not working.
So could any tell me what I'm I doing wrong here, or this not the right way to do it ?
Thank you everyone before and after.
Here is some of my code:
public class H_Store extends JFrame {
private JCheckBox groundMeatCheckBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
H_Store frame = new H_Store();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public H_Store() {
super("Hussin Store");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1378, 657);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(new GridLayout(0, 2, 0, 0));
JPanel meetPanel = new JPanel();
meetPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(meetPanel);
JLabel meatLabel = new JLabel("*Meat*");
meatLabel.setBounds(546, 101, 79, 77);
meatLabel.setHorizontalAlignment(SwingConstants.LEFT);
meatLabel.setFont(new Font("Times New Roman", Font.PLAIN, 25));
///////////////////
JCheckBox groundMeatCheckBox = new JCheckBox("Ground ");
groundMeatCheckBox.setBounds(8, 71, 113, 25);
groundMeatCheckBox.setVerticalAlignment(SwingConstants.BOTTOM);
groundMeatCheckBox.setHorizontalAlignment(SwingConstants.LEFT);
meetPanel.setLayout(null);
meetPanel.add(meatLabel);
meetPanel.add(groundMeatCheckBox);
JCheckBox chuckMeatCheckBox = new JCheckBox("Chuck");
chuckMeatCheckBox.setBounds(8, 126, 113, 25);
meetPanel.add(chuckMeatCheckBox);
JCheckBox ribMeatCheckBox = new JCheckBox("Rib");
ribMeatCheckBox.setBounds(8, 101, 113, 25);
meetPanel.add(ribMeatCheckBox);
JCheckBox steakMeatCheckBox = new JCheckBox("Steak");
steakMeatCheckBox.setBounds(8, 153, 120, 25);
meetPanel.add(steakMeatCheckBox);
JCheckBox flankMeatCheckBox = new JCheckBox("Flank");
flankMeatCheckBox.setBounds(8, 183, 113, 25);
meetPanel.add(flankMeatCheckBox);
JCheckBox roundMeatCheckBox = new JCheckBox("Round");
roundMeatCheckBox.setBounds(8, 213, 113, 25);
meetPanel.add(roundMeatCheckBox);
ground_M_QTextField = new JTextField(10);
ground_M_QTextField.setText("0");
ground_M_QTextField.setBounds(155, 76, 18, 16);
meetPanel.add(ground_M_QTextField);
ground_M_QTextField.setColumns(10);
chuck_M_QTextField = new JTextField();
chuck_M_QTextField.setText("0");
chuck_M_QTextField.setColumns(10);
chuck_M_QTextField.setBounds(155, 105, 18, 16);
meetPanel.add(chuck_M_QTextField);
rib_M_QTextField = new JTextField();
rib_M_QTextField.setText("0");
rib_M_QTextField.setColumns(10);
rib_M_QTextField.setBounds(155, 130, 18, 16);
meetPanel.add(rib_M_QTextField);
steak_M_QTextField = new JTextField();
steak_M_QTextField.setText("0");
steak_M_QTextField.setColumns(10);
steak_M_QTextField.setBounds(155, 157, 18, 16);
meetPanel.add(steak_M_QTextField);
flank_M_QTextField = new JTextField();
flank_M_QTextField.setText("0");
flank_M_QTextField.setColumns(10);
flank_M_QTextField.setBounds(155, 187, 18, 16);
meetPanel.add(flank_M_QTextField);
round_M_QTextField = new JTextField();
round_M_QTextField.setText("0");
round_M_QTextField.setColumns(10);
round_M_QTextField.setBounds(155, 217, 18, 16);
meetPanel.add(round_M_QTextField);
JLabel lblType = new JLabel("Type:");
lblType.setFont(new Font("Tahoma", Font.BOLD, 13));
lblType.setBounds(8, 46, 44, 16);
meetPanel.add(lblType);
JLabel lblNewLabel = new JLabel("Quantity:");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel.setBounds(155, 46, 61, 16);
meetPanel.add(lblNewLabel);
ground_M_WTextField = new JTextField();
ground_M_WTextField.setText("0.00");
ground_M_WTextField.setColumns(10);
ground_M_WTextField.setBounds(291, 73, 36, 16);
meetPanel.add(ground_M_WTextField);
chuck_M_WTextField = new JTextField();
chuck_M_WTextField.setText("0.00");
chuck_M_WTextField.setColumns(10);
chuck_M_WTextField.setBounds(291, 105, 36, 16);
meetPanel.add(chuck_M_WTextField);
rib_M_WTextField = new JTextField();
rib_M_WTextField.setText("0.00");
rib_M_WTextField.setColumns(10);
rib_M_WTextField.setBounds(291, 130, 36, 16);
meetPanel.add(rib_M_WTextField);
steak_M_WTextField = new JTextField();
steak_M_WTextField.setText("0.00");
steak_M_WTextField.setColumns(10);
steak_M_WTextField.setBounds(291, 157, 36, 16);
meetPanel.add(steak_M_WTextField);
flank_M_WTextField = new JTextField();
flank_M_WTextField.setText("0.00");
flank_M_WTextField.setColumns(10);
flank_M_WTextField.setBounds(291, 187, 36, 16);
meetPanel.add(flank_M_WTextField);
round_M_WTextField = new JTextField();
round_M_WTextField.setText("0.00");
round_M_WTextField.setColumns(10);
round_M_WTextField.setBounds(291, 217, 36, 16);
meetPanel.add(round_M_WTextField);
JLabel lblWeightlp = new JLabel("(LP) Weight: ");
lblWeightlp.setFont(new Font("Tahoma", Font.BOLD, 13));
lblWeightlp.setBounds(291, 46, 86, 16);
meetPanel.add(lblWeightlp);
at_M_QTextField = new JTextField();
at_M_QTextField.setText("0");
at_M_QTextField.setColumns(10);
at_M_QTextField.setBounds(155, 251, 18, 16);
meetPanel.add(at_M_QTextField);
at_M_WTextField = new JTextField();
at_M_WTextField.setText("0.00");
at_M_WTextField.setColumns(10);
at_M_WTextField.setBounds(291, 251, 36, 16);
meetPanel.add(at_M_WTextField);
at_meat_TextField = new JTextField();
at_meat_TextField.setText("Another Type..");
at_meat_TextField.setColumns(10);
at_meat_TextField.setBounds(8, 250, 98, 24);
meetPanel.add(at_meat_TextField);
lblPrice = new JLabel("(LP)Price:");
lblPrice.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPrice.setBounds(446, 46, 73, 16);
meetPanel.add(lblPrice);
ground_M_PTextField = new JTextField();
ground_M_PTextField.setText("0.00");
ground_M_PTextField.setColumns(10);
ground_M_PTextField.setBounds(445, 71, 36, 16);
meetPanel.add(ground_M_PTextField);
rib_M_PTextField = new JTextField();
rib_M_PTextField.setText("0.00");
rib_M_PTextField.setColumns(10);
rib_M_PTextField.setBounds(445, 103, 36, 16);
meetPanel.add(rib_M_PTextField);
chuck_M_PTextField = new JTextField();
chuck_M_PTextField.setText("0.00");
chuck_M_PTextField.setColumns(10);
chuck_M_PTextField.setBounds(445, 128, 36, 16);
meetPanel.add(chuck_M_PTextField);
steak_M_PTextField = new JTextField();
steak_M_PTextField.setText("0.00");
steak_M_PTextField.setColumns(10);
steak_M_PTextField.setBounds(445, 155, 36, 16);
meetPanel.add(steak_M_PTextField);
flank_M_PTextField = new JTextField();
flank_M_PTextField.setText("0.00");
flank_M_PTextField.setColumns(10);
flank_M_PTextField.setBounds(445, 185, 36, 16);
meetPanel.add(flank_M_PTextField);
round_M_PTextField = new JTextField();
round_M_PTextField.setText("0.00");
round_M_PTextField.setColumns(10);
round_M_PTextField.setBounds(445, 215, 36, 16);
meetPanel.add(round_M_PTextField);
at_M_PTextField = new JTextField();
at_M_PTextField.setText("0.00");
at_M_PTextField.setColumns(10);
at_M_PTextField.setBounds(445, 249, 36, 16);
meetPanel.add(at_M_PTextField);
JPanel chikenPanel = new JPanel();
chikenPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, Color.BLUE, null, null));
mainPane.add(chikenPanel);
chikenPanel.setLayout(null);
JLabel lblChiken = new JLabel("*Chiken*");
lblChiken.setBounds(543, 104, 120, 77);
lblChiken.setFont(new Font("Times New Roman", Font.PLAIN, 25));
chikenPanel.add(lblChiken);
JCheckBox whole_C_CheckBox = new JCheckBox("Whole");
whole_C_CheckBox.setVerticalAlignment(SwingConstants.BOTTOM);
whole_C_CheckBox.setHorizontalAlignment(SwingConstants.LEFT);
whole_C_CheckBox.setBounds(12, 66, 113, 25);
chikenPanel.add(whole_C_CheckBox);
JCheckBox half_C_CheckBox = new JCheckBox("Half");
half_C_CheckBox.setBounds(12, 96, 113, 25);
chikenPanel.add(half_C_CheckBox);
JCheckBox breast_C_CheckBox = new JCheckBox("Breast");
breast_C_CheckBox.setBounds(12, 126, 113, 25);
chikenPanel.add(breast_C_CheckBox);
JCheckBox wings_C_CheckBox = new JCheckBox("Wings");
wings_C_CheckBox.setBounds(12, 156, 120, 25);
chikenPanel.add(wings_C_CheckBox);
JCheckBox liver_C_CheckBox = new JCheckBox("Liver");
liver_C_CheckBox.setBounds(12, 186, 113, 25);
chikenPanel.add(liver_C_CheckBox);
JCheckBox heart_C_CheckBox = new JCheckBox("Heart");
heart_C_CheckBox.setBounds(12, 216, 113, 25);
chikenPanel.add(heart_C_CheckBox);
textField_13 = new JTextField();
textField_13.setText("0");
textField_13.setColumns(10);
textField_13.setBounds(170, 71, 25, 16);
chikenPanel.add(textField_13);
textField_14 = new JTextField();
textField_14.setText("0");
textField_14.setColumns(10);
textField_14.setBounds(170, 97, 25, 16);
chikenPanel.add(textField_14);
textField_15 = new JTextField();
textField_15.setText("0");
textField_15.setColumns(10);
textField_15.setBounds(170, 130, 25, 16);
chikenPanel.add(textField_15);
textField_16 = new JTextField();
textField_16.setText("0");
textField_16.setColumns(10);
textField_16.setBounds(170, 160, 25, 16);
chikenPanel.add(textField_16);
textField_17 = new JTextField();
textField_17.setText("0");
textField_17.setColumns(10);
textField_17.setBounds(170, 190, 25, 16);
chikenPanel.add(textField_17);
textField_18 = new JTextField();
textField_18.setText("0");
textField_18.setColumns(10);
textField_18.setBounds(170, 220, 25, 16);
chikenPanel.add(textField_18);
textField_19 = new JTextField();
textField_19.setText("0.00");
textField_19.setColumns(10);
textField_19.setBounds(320, 220, 38, 16);
chikenPanel.add(textField_19);
textField_20 = new JTextField();
textField_20.setText("0.00");
textField_20.setColumns(10);
textField_20.setBounds(320, 190, 38, 16);
chikenPanel.add(textField_20);
textField_21 = new JTextField();
textField_21.setText("0.00");
textField_21.setColumns(10);
textField_21.setBounds(320, 157, 38, 16);
chikenPanel.add(textField_21);
textField_22 = new JTextField();
textField_22.setText("0.00");
textField_22.setColumns(10);
textField_22.setBounds(320, 130, 38, 16);
chikenPanel.add(textField_22);
textField_23 = new JTextField();
textField_23.setText("0.00");
textField_23.setColumns(10);
textField_23.setBounds(320, 100, 38, 16);
chikenPanel.add(textField_23);
textField_24 = new JTextField();
textField_24.setText("0.00");
textField_24.setColumns(10);
textField_24.setBounds(320, 71, 38, 16);
chikenPanel.add(textField_24);
JLabel label = new JLabel("Type:");
label.setFont(new Font("Tahoma", Font.BOLD, 13));
label.setBounds(12, 41, 56, 16);
chikenPanel.add(label);
JLabel label_1 = new JLabel("Quantity:");
label_1.setFont(new Font("Tahoma", Font.BOLD, 13));
label_1.setBounds(170, 41, 75, 16);
chikenPanel.add(label_1);
JLabel label_2 = new JLabel("(LP) Weight: ");
label_2.setFont(new Font("Tahoma", Font.BOLD, 13));
label_2.setBounds(320, 41, 92, 16);
chikenPanel.add(label_2);
textField_12 = new JTextField();
textField_12.setText("Another Type..");
textField_12.setColumns(10);
textField_12.setBounds(12, 250, 99, 24);
chikenPanel.add(textField_12);
textField_34 = new JTextField();
textField_34.setText("0");
textField_34.setColumns(10);
textField_34.setBounds(170, 251, 25, 16);
chikenPanel.add(textField_34);
textField_35 = new JTextField();
textField_35.setText("0.00");
textField_35.setColumns(10);
textField_35.setBounds(320, 251, 38, 16);
chikenPanel.add(textField_35);
label_5 = new JLabel("Price:");
label_5.setFont(new Font("Tahoma", Font.BOLD, 13));
label_5.setBounds(477, 41, 43, 16);
chikenPanel.add(label_5);
textField_7 = new JTextField();
textField_7.setText("0.00");
textField_7.setColumns(10);
textField_7.setBounds(477, 71, 36, 16);
chikenPanel.add(textField_7);
textField_8 = new JTextField();
textField_8.setText("0.00");
textField_8.setColumns(10);
textField_8.setBounds(477, 100, 36, 16);
chikenPanel.add(textField_8);
textField_9 = new JTextField();
textField_9.setText("0.00");
textField_9.setColumns(10);
textField_9.setBounds(476, 130, 36, 16);
chikenPanel.add(textField_9);
textField_10 = new JTextField();
textField_10.setText("0.00");
textField_10.setColumns(10);
textField_10.setBounds(476, 160, 36, 16);
chikenPanel.add(textField_10);
textField_11 = new JTextField();
textField_11.setText("0.00");
textField_11.setColumns(10);
textField_11.setBounds(477, 190, 36, 16);
chikenPanel.add(textField_11);
textField_25 = new JTextField();
textField_25.setText("0.00");
textField_25.setColumns(10);
textField_25.setBounds(477, 220, 36, 16);
chikenPanel.add(textField_25);
textField_32 = new JTextField();
textField_32.setText("0.00");
textField_32.setColumns(10);
textField_32.setBounds(477, 254, 36, 16);
chikenPanel.add(textField_32);
JPanel otherThingsPanel = new JPanel();
otherThingsPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(otherThingsPanel);
otherThingsPanel.setLayout(null);
JLabel lblOtherThings = new JLabel("*Other Things*");
lblOtherThings.setBounds(421, 117, 176, 42);
lblOtherThings.setFont(new Font("Tahoma", Font.PLAIN, 25));
otherThingsPanel.add(lblOtherThings);
JLabel label_3 = new JLabel("Type:");
label_3.setFont(new Font("Tahoma", Font.BOLD, 13));
label_3.setBounds(16, 46, 65, 16);
otherThingsPanel.add(label_3);
JCheckBox chckbxCheese = new JCheckBox("Cheese");
chckbxCheese.setVerticalAlignment(SwingConstants.BOTTOM);
chckbxCheese.setHorizontalAlignment(SwingConstants.LEFT);
chckbxCheese.setBounds(12, 71, 113, 25);
otherThingsPanel.add(chckbxCheese);
JCheckBox chckbxBread = new JCheckBox("Bread");
chckbxBread.setBounds(12, 101, 113, 25);
otherThingsPanel.add(chckbxBread);
JCheckBox chckbxRice = new JCheckBox("Rice");
chckbxRice.setBounds(12, 131, 113, 25);
otherThingsPanel.add(chckbxRice);
JCheckBox chckbxBeefBurger = new JCheckBox("Burger ");
chckbxBeefBurger.setBounds(12, 161, 120, 25);
otherThingsPanel.add(chckbxBeefBurger);
JCheckBox chckbxChickenBurger = new JCheckBox("Kebab");
chckbxChickenBurger.setBounds(12, 191, 113, 25);
otherThingsPanel.add(chckbxChickenBurger);
JCheckBox chckbxFalafel = new JCheckBox("Falafel");
chckbxFalafel.setBounds(12, 221, 113, 25);
otherThingsPanel.add(chckbxFalafel);
textField_26 = new JTextField();
textField_26.setText("0");
textField_26.setColumns(10);
textField_26.setBounds(165, 225, 25, 16);
otherThingsPanel.add(textField_26);
textField_27 = new JTextField();
textField_27.setText("0");
textField_27.setColumns(10);
textField_27.setBounds(165, 195, 25, 16);
otherThingsPanel.add(textField_27);
textField_28 = new JTextField();
textField_28.setText("0");
textField_28.setColumns(10);
textField_28.setBounds(165, 162, 25, 16);
otherThingsPanel.add(textField_28);
textField_29 = new JTextField();
textField_29.setText("0");
textField_29.setColumns(10);
textField_29.setBounds(165, 132, 25, 16);
otherThingsPanel.add(textField_29);
textField_30 = new JTextField();
textField_30.setText("0");
textField_30.setColumns(10);
textField_30.setBounds(165, 102, 25, 16);
otherThingsPanel.add(textField_30);
textField_31 = new JTextField();
textField_31.setText("0");
textField_31.setColumns(10);
textField_31.setBounds(165, 76, 25, 16);
otherThingsPanel.add(textField_31);
JLabel label_4 = new JLabel("Quantity:");
label_4.setFont(new Font("Tahoma", Font.BOLD, 13));
label_4.setBounds(165, 46, 65, 16);
otherThingsPanel.add(label_4);
otherThings_AnotherTypeTextField = new JTextField();
otherThings_AnotherTypeTextField.setText("Another Type..");
otherThings_AnotherTypeTextField.setColumns(10);
otherThings_AnotherTypeTextField.setBounds(16, 250, 93, 24);
otherThingsPanel.add(otherThings_AnotherTypeTextField);
textField_36 = new JTextField();
textField_36.setText("0");
textField_36.setColumns(10);
textField_36.setBounds(165, 254, 25, 16);
otherThingsPanel.add(textField_36);
label_6 = new JLabel("Price:");
label_6.setFont(new Font("Tahoma", Font.BOLD, 13));
label_6.setBounds(310, 46, 56, 16);
otherThingsPanel.add(label_6);
textField_33 = new JTextField();
textField_33.setText("0.00");
textField_33.setColumns(10);
textField_33.setBounds(309, 71, 36, 16);
otherThingsPanel.add(textField_33);
textField_37 = new JTextField();
textField_37.setText("0.00");
textField_37.setColumns(10);
textField_37.setBounds(309, 103, 36, 16);
otherThingsPanel.add(textField_37);
textField_38 = new JTextField();
textField_38.setText("0.00");
textField_38.setColumns(10);
textField_38.setBounds(309, 128, 36, 16);
otherThingsPanel.add(textField_38);
textField_39 = new JTextField();
textField_39.setText("0.00");
textField_39.setColumns(10);
textField_39.setBounds(309, 155, 36, 16);
otherThingsPanel.add(textField_39);
textField_40 = new JTextField();
textField_40.setText("0.00");
textField_40.setColumns(10);
textField_40.setBounds(309, 185, 36, 16);
otherThingsPanel.add(textField_40);
textField_41 = new JTextField();
textField_41.setText("0.00");
textField_41.setColumns(10);
textField_41.setBounds(309, 215, 36, 16);
otherThingsPanel.add(textField_41);
textField_42 = new JTextField();
textField_42.setText("0.00");
textField_42.setColumns(10);
textField_42.setBounds(309, 249, 36, 16);
otherThingsPanel.add(textField_42);
JPanel calculationPanel = new JPanel();
calculationPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(calculationPanel);
calculationPanel.setLayout(null);
JLabel lblCalculation = new JLabel("*Calculation*");
lblCalculation.setBounds(212, 12, 148, 29);
lblCalculation.setFont(new Font("Times New Roman", Font.PLAIN, 25));
calculationPanel.add(lblCalculation);
// Calculation everything
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(new CalcButtonListener());
calculateButton.setFont(new Font("Tahoma", Font.PLAIN, 25));
calculateButton.setBounds(340, 177, 313, 97);
calculationPanel.add(calculateButton);
txtrWriteYourComment = new JTextArea();
txtrWriteYourComment.setRows(1);
txtrWriteYourComment.setFont(new Font("Courier New", Font.PLAIN, 12));
txtrWriteYourComment.setText("Write Your Comment here.....");
txtrWriteYourComment.setBounds(12, 54, 641, 111);
calculationPanel.add(txtrWriteYourComment);
getProfitJButton = new JButton("Get Profit");
getProfitJButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame frame2 = new JFrame("Profit");
frame2.setVisible(true);
frame2.setSize(350,200);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
profitPanel = new JPanel();
profitPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(profitPanel);
profitPanel.setLayout(new GridLayout(0, 2, 0, 0));
frame2.getContentPane().add(profitPanel);
profitFileButton = new JButton("Porfit File");
profitFileTextField = new JTextField();
getProfitJButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profitJFileChooser = new JFileChooser();
profitJFileChooser.showOpenDialog(null);
File f = profitJFileChooser.getSelectedFile();
String fileName = f.getAbsolutePath();
profitFileTextField.setText(fileName);
}
});
profitPanel.add(profitFileButton);
profitPanel.add(profitFileTextField);
sellFileButtton = new JButton("Sell File");
profitPanel.add(sellFileButtton);
}
});
getProfitJButton.setFont(new Font("Tahoma", Font.PLAIN, 25));
getProfitJButton.setBounds(12, 177, 316, 97);
calculationPanel.add(getProfitJButton);
///////////////////////////////////////////
theholder holder = new theholder();
groundMeatCheckBox.addItemListener(holder);
}
private class CalcButtonListener implements ActionListener{
// vairbles for the ground Meat check box
private double total_GM;
private double weightPrice_1;
private String stringQ;
private String stringW;
private String stringP;
private int meat_Q1;
private double meat_W1;
private double meat_P1;
public void actionPerformed(ActionEvent e){
total_GM = 0;
// The ground Meat check box calculation
stringQ = ground_M_QTextField.getText();
meat_Q1 = Integer.parseInt(stringQ);
stringW = ground_M_WTextField.getText();
meat_W1 = Double.parseDouble(stringW);
stringP = ground_M_PTextField.getText();
meat_P1 = Double.parseDouble(stringP);
weightPrice_1 = meat_W1 * meat_P1;
total_GM += weightPrice_1 * meat_Q1;
JOptionPane.showMessageDialog(null, total_GM + "\n" + s);
}
}
}
What I want to do exactly is to take the last code into another class or do something with so I can use it in the Parent class, in other word any math I want outside the Parent class.
Note: I mean this code
private class CalcButtonListener implements ActionListener{
// vairbles for the ground Meat check box
private double total_GM;
private double weightPrice_1;
private String stringQ;
private String stringW;
private String stringP;
private int meat_Q1;
private double meat_W1;
private double meat_P1;
public void actionPerformed(ActionEvent e){
total_GM = 0;
// The ground Meat check box calculation
stringQ = ground_M_QTextField.getText();
meat_Q1 = Integer.parseInt(stringQ);
stringW = ground_M_WTextField.getText();
meat_W1 = Double.parseDouble(stringW);
stringP = ground_M_PTextField.getText();
meat_P1 = Double.parseDouble(stringP);
weightPrice_1 = meat_W1 * meat_P1;
total_GM += weightPrice_1 * meat_Q1;
JOptionPane.showMessageDialog(null, total_GM + "\n" + s);
}
}
You state:
My problem is that I'm reaching 1000 Line and this is stressful because all my code are in one file. I'm not liking this.
You are quite right to not like this and to try to improve this set up as this type of program will be a monster to maintain, debug and enhance..
You then state:
Inheriting from a JFrame class to another class and using the variables
This is not what inheritance is for as objects of the child class will be a completely distinct entities from objects of the parent class, so you will not want to do this.
Instead
Remember to strive to enhance by composition rather than inheritance, meaning have classes contain fields of other classes.
Avoid using the static modifier to make global-like variables as this will hog-tie your code.
try to break out logical parts of your program from the visual, the GUI parts,
And split up each specific logical part and each major GUI part into its own class.
make sure all classes have decent setter and getter methods,
and that the classes are written so that they communicate well with each other.
A Swing specific recommendation is for you to avoid extending JFrame.
Instead gear your Swing GUI's towards creating JPanels, panels which can be placed anywhere you want them, including in JFrames, JApplets, JDialogs, JOptionPanes, inside of other JPanels, in JTabbedPanes, as "cards" in a CardLayout-using JPanel,....
This will greatly improve the flexibility and enhance-ability of your program.
For more specific help, please feel free to provide more details about your program and its code.
Edit
Sorry to be blunt, but you've come for advice on your code, and I have to inform you that it has some significant problems including:
it contains more quite a bit of unnecessary redundency that makes it hard to follow and debug.
You have grids of JTextFields, all of which can and should be replaced by three JTables, one for Meat, one for Chicken, and one for "other things".
You use null layouts and absolute positioning, something that seems to a newbie an easier way to create complex GUI's, but in the long run is the most difficult way to create, maintain and upgrade these. You're far better off learning about and using the layout managers, including nesting JPanels each with its own layout.
Any time I see variables named something12, something13, something14, something15, something16, something17, something18, ... I think that most of this can be replaced by an array or a collection such as an ArrayList, or in your case (as noted above), a JTable whose model is based in a collection.
Each one of your table entries should likely be in its own class.
I stand by my original recommendation that you should not have any of your classes inherit from the main GUI as this will lead to non-workable code.
Also, your JFrame should not launch another JFrame, but rather the getProfitButton should launch a modal JDialog.
Edit
For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class TableEg extends JPanel {
private static final String[] ROW_TITLES = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
MyTableModel tableModel = new MyTableModel(ROW_TITLES);
private JTable table;
public TableEg() {
table = new JTable(tableModel) {
#Override
public TableCellRenderer getCellRenderer(int row, int column) {
JComponent renderer = (JComponent) super.getCellRenderer(row,
column);
boolean enabled = (Boolean) table.getValueAt(row, 0);
renderer.setEnabled(enabled);
return super.getCellRenderer(row, column);
}
};
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
table.repaint();
}
});
}
});
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.getViewport().setPreferredSize(table.getPreferredSize());
JButton getSumButton = new JButton(new GetSumAction("Get Sum", tableModel));
JPanel southPanel = new JPanel();
southPanel.add(getSumButton);
setLayout(new BorderLayout());
add(scrollpane, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
TableEg mainPanel = new TableEg();
JFrame frame = new JFrame("TableEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyTableModel extends DefaultTableModel {
private static final String[] COLUMN_NAMES = { "Selected", "Name", "Number" };
public MyTableModel(String[] rowTitles) {
super(COLUMN_NAMES, 0);
for (int i = 0; i < rowTitles.length; i++) {
Object[] rowData = { Boolean.FALSE, rowTitles[i], Integer.valueOf(0) };
addRow(rowData);
}
Object[] rowData = { Boolean.FALSE, "", Integer.valueOf(0) };
addRow(rowData);
}
#Override
public boolean isCellEditable(int row, int column) {
if (column == 0) {
return true;
}
if (column == 1) {
return row >= getRowCount() - 1;
}
if (column > 1) {
return ((Boolean) getValueAt(row, 0)).booleanValue();
}
return super.isCellEditable(row, column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Boolean.class;
case 1:
return String.class;
case 2:
return Integer.class;
}
return super.getColumnClass(columnIndex);
}
}
class GetSumAction extends AbstractAction {
private MyTableModel tableModel;
public GetSumAction(String name, MyTableModel tableModel) {
super(name);
this.tableModel = tableModel;
}
#Override
public void actionPerformed(ActionEvent evt) {
int sum = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
Object value = tableModel.getValueAt(i, 2);
if (value != null) {
sum += ((Integer) value).intValue();
}
}
String text = "Number of days: " + sum;
String title = "Number of Days";
JOptionPane.showMessageDialog((JButton) evt.getSource(), text, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
First of all try to divide your code into methods, that would make your code more clear.
As for inheritance, you can only modify variables that are in the parent class from the child class if those variable are :
.Data members
.Their visibility is set to protected
Here is an example
public class Parent{
protected JButton button;
protected int something;
protected String whatever;
//^Those are the data members
public Parent(){//Constructor
//some code here
}
//more code
}//end of parent class
public class Child extends Parent{
private int randomstuff;
private String morerandomDatamembers;
public Child(){
super();
}
public void modify(){
something=3;
whatever="yayyy it worked";
}
}
protected data members can only be accessed by the children of some class.
EDIT- Inheritance can be used in specific cases. You can still modify data members of some class from a different class. Every method should have getters and setters.
Example:
public class Car{
private int ModelNumber;
private String CarName;
public Car(int ModelNum,String name){
ModelNumber=ModelNum;
CarName=name;
}
public int getModelNum(){//First getter
return ModelNumber;
}
public void setModelNum(int ModelNum){//First setter
ModelNumber=ModelNum;
}
public String getCarName(){//Second getter;
return CarName;
}
public void setCarName(String Car){
CarName=Car;
}
}
public class Company{
private Car car;
public Company(Car c){
car=c;
}
public void modify(){
car.setModelNum(123);
car.setCarName("Ferrari");
System.out.println("Being so awesome,Roudy will let me try his Ferrari");
}
}
I'm having a problem with my code in java. It is supposed to insert data into a database but it's returning a nullpointerexception. Here is my code.
package client;
import java.sql.*;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class AddCon {
private Connection conn;
private JFrame frmAddContract;
private JTextField ContractNo;
private JTextField EngagerName;
private JTextField contNo;
private JTextField month;
private JTextField day;
private JTextField year;
private JTextField tme;
private JTextField cladd;
private JTextField eventadd;
private JTextField textField_fp;
private JTextField refer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddCon window = new AddCon();
window.frmAddContract.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/KusinaNiKambal","root","1234");
Statement stmt = null;
stmt = conn.createStatement();}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);}
/**
* Initialize the contents of the frame.
*/
initialize();
}
private void initialize() {
frmAddContract = new JFrame();
frmAddContract.setResizable(false);
frmAddContract.setTitle("Add Contract");
frmAddContract.setBounds(100, 100, 450, 640);
frmAddContract.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAddContract.getContentPane().setLayout(null);
ContractNo = new JTextField();
ContractNo.setBounds(38, 32, 152, 20);
frmAddContract.getContentPane().add(ContractNo);
ContractNo.setColumns(10);
JLabel lblContract = new JLabel("Contract #");
lblContract.setBounds(38, 18, 76, 14);
frmAddContract.getContentPane().add(lblContract);
JLabel lblEngager = new JLabel("Engager");
lblEngager.setBounds(38, 63, 48, 14);
frmAddContract.getContentPane().add(lblEngager);
EngagerName = new JTextField();
EngagerName.setBounds(38, 78, 152, 20);
frmAddContract.getContentPane().add(EngagerName);
EngagerName.setColumns(10);
contNo = new JTextField();
contNo.setBounds(38, 128, 152, 20);
frmAddContract.getContentPane().add(contNo);
contNo.setColumns(10);
JLabel lblNewLabel = new JLabel("Contact #");
lblNewLabel.setBounds(38, 109, 86, 14);
frmAddContract.getContentPane().add(lblNewLabel);
month = new JTextField();
month.setBounds(38, 255, 116, 20);
frmAddContract.getContentPane().add(month);
day = new JTextField();
day.setBounds(181, 255, 81, 20);
frmAddContract.getContentPane().add(day);
year = new JTextField();
year.setBounds(294, 255, 86, 20);
frmAddContract.getContentPane().add(year);
year.setColumns(10);
JLabel lblMonth = new JLabel("Month in number format");
lblMonth.setBounds(38, 236, 100, 14);
frmAddContract.getContentPane().add(lblMonth);
JLabel lblDay = new JLabel("Day");
lblDay.setBounds(181, 236, 48, 14);
frmAddContract.getContentPane().add(lblDay);
JLabel lblYear = new JLabel("Year");
lblYear.setBounds(294, 236, 48, 14);
frmAddContract.getContentPane().add(lblYear);
JLabel lblEventDate = new JLabel("Event Date");
lblEventDate.setBounds(38, 222, 76, 14);
frmAddContract.getContentPane().add(lblEventDate);
tme = new JTextField();
tme.setBounds(38, 307, 59, 20);
frmAddContract.getContentPane().add(tme);
tme.setColumns(10);
cladd = new JTextField();
cladd.setBounds(38, 180, 363, 31);
frmAddContract.getContentPane().add(cladd);
cladd.setColumns(10);
JLabel lblAddress = new JLabel("Client Address");
lblAddress.setBounds(38, 159, 98, 14);
frmAddContract.getContentPane().add(lblAddress);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(38, 286, 60, 14);
frmAddContract.getContentPane().add(lblTime);
eventadd = new JTextField();
eventadd.setBounds(38, 358, 373, 50);
frmAddContract.getContentPane().add(eventadd);
eventadd.setColumns(10);
JLabel lblEventAddress = new JLabel("Event Address");
lblEventAddress.setBounds(38, 338, 116, 14);
frmAddContract.getContentPane().add(lblEventAddress);
textField_fp = new JTextField();
textField_fp.setBounds(38, 454, 276, 20);
frmAddContract.getContentPane().add(textField_fp);
textField_fp.setColumns(10);
JLabel lblFilepathOfContract = new JLabel("Filepath of Contract - the PDF file");
lblFilepathOfContract.setBounds(38, 431, 116, 14);
frmAddContract.getContentPane().add(lblFilepathOfContract);
JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBounds(324, 453, 89, 23);
frmAddContract.getContentPane().add(btnBrowse);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
String filepath = fc.getSelectedFile().getAbsolutePath();
textField_fp.setText(filepath);
}
});
refer = new JTextField();
refer.setBounds(38, 510, 276, 20);
frmAddContract.getContentPane().add(refer);
refer.setColumns(10);
JLabel lblEncodedBy = new JLabel("Referred By");
lblEncodedBy.setBounds(38, 485, 116, 14);
frmAddContract.getContentPane().add(lblEncodedBy);
JButton btnAdd = new JButton("Add");
btnAdd.setBounds(101, 560, 89, 23);
frmAddContract.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try{
String cntr = ContractNo.getText();
String en = EngagerName.getText();
String cont = contNo.getText();
String mo = month.getText();
String d = day.getText();
String yr = year.getText();
String dte = yr + "-" + mo + "-" + d;
String cla = cladd.getText();
String tm = tme.getText() + ":00";
String evadd = eventadd.getText();
String filepath = textField_fp.getText();
String ref = refer.getText();
String SQL = "insert into cis "+
"values ('"+cntr+"','"+en+"','"+
cont+"','"+cla+"' '"+dte+"','"+tm+"','"+
evadd+"','"+filepath+"','"+ref+")";
PreparedStatement stmt = conn.prepareStatement(SQL);
ResultSet rs = stmt.executeQuery();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(225, 560, 89, 23);
frmAddContract.getContentPane().add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frmAddContract.setVisible(false);
}
});
}
}
Sorry, i'm not really that experienced in java programming and this is my first time making a code for querying databases.
You do never initialize your conn instance variable. This will lead to a NullPointerException (at least) in this line:
PreparedStatement stmt = conn.prepareStatement(SQL);
^------------ NEVER INITIALIZED
public class AddCon {
private Connection conn;
...
// constructor
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(<your parameters>);
^----------- MISTAKE
...
In the above code you create a connection, but instead of assigning it to the instance variable you just use a local variable. Replace that line with:
this.conn = DriverManager.getConnection(<your parameters>);
Edit: Please always post the stacktrace in case of exceptions!
I'm having an issue with trying to change the icon of a JLabel. I am using the windowbuilder addon in eclipse to make this program, so just disregard all the bad naming choices of the label and all that, they will be changed later.
The error I'm having is that at the bottom of the my code where I try to change the icon of label_1, I get the following message.
The method seticon(icon) in the type jlabel is not applicable for the
arguments (string)
Does anyone have any idea what this could be?
Here is my code. Sorry that it's rather long, that's window builder for you I suppose:
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Game {
public Timer bomb1;
public JLabel label;
public JLabel label_1;
public JLabel lblScore;
public JButton btnQuit;
public JLabel label_2;
public JLabel label_3;
public JLabel label_4;
public JLabel label_5;
public JLabel label_6;
public JLabel label_7;
public JLabel label_8;
public JLabel label_9;
public JLabel label_10;
public JLabel label_11;
public JLabel label_12;
public JLabel label_13;
public JLabel label_14;
public JLabel label_15;
public JLabel label_16;
public JLabel lblDodgeTheBombs;
public JFrame frame;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Game window = new Game();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Game() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 489, 512);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setContentPane(contentPane);
contentPane.setLayout(null);
label_1 = new JLabel("");
label_1.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_1.setBackground(Color.WHITE);
label_1.setBounds(59, 44, 80, 80);
contentPane.add(label_1);
label = new JLabel("0");
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
label.setBounds(71, 12, 46, 14);
contentPane.add(label);
lblScore = new JLabel("Score:");
lblScore.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblScore.setBounds(28, 11, 45, 17);
contentPane.add(lblScore);
btnQuit = new JButton("Quit");
btnQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.dispose();
}
});
btnQuit.setBounds(359, 10, 89, 23);
contentPane.add(btnQuit);
label_2 = new JLabel("");
label_2.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_2.setBackground(Color.WHITE);
label_2.setBounds(149, 44, 80, 80);
contentPane.add(label_2);
label_3 = new JLabel("");
label_3.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_3.setBackground(Color.WHITE);
label_3.setBounds(239, 44, 80, 80);
contentPane.add(label_3);
label_4 = new JLabel("");
label_4.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_4.setBackground(Color.WHITE);
label_4.setBounds(329, 44, 80, 80);
contentPane.add(label_4);
label_5 = new JLabel("");
label_5.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_5.setBackground(Color.WHITE);
label_5.setBounds(59, 138, 80, 80);
contentPane.add(label_5);
label_6 = new JLabel("");
label_6.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_6.setBackground(Color.WHITE);
label_6.setBounds(149, 135, 80, 80);
contentPane.add(label_6);
label_7 = new JLabel("");
label_7.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_7.setBackground(Color.WHITE);
label_7.setBounds(239, 135, 80, 80);
contentPane.add(label_7);
label_8 = new JLabel("");
label_8.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_8.setBackground(Color.WHITE);
label_8.setBounds(329, 135, 80, 80);
contentPane.add(label_8);
label_9 = new JLabel("");
label_9.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_9.setBackground(Color.WHITE);
label_9.setBounds(329, 320, 80, 80);
contentPane.add(label_9);
label_10 = new JLabel("");
label_10.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_10.setBackground(Color.WHITE);
label_10.setBounds(59, 229, 80, 80);
contentPane.add(label_10);
label_11 = new JLabel("");
label_11.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_11.setBackground(Color.WHITE);
label_11.setBounds(149, 229, 80, 80);
contentPane.add(label_11);
label_12 = new JLabel("");
label_12.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_12.setBackground(Color.WHITE);
label_12.setBounds(239, 229, 80, 80);
contentPane.add(label_12);
label_13 = new JLabel("");
label_13.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_13.setBackground(Color.WHITE);
label_13.setBounds(329, 229, 80, 80);
contentPane.add(label_13);
label_14 = new JLabel("");
label_14.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_14.setBackground(Color.WHITE);
label_14.setBounds(239, 320, 80, 80);
contentPane.add(label_14);
label_15 = new JLabel();
label_15.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_15.setBackground(Color.WHITE);
label_15.setBounds(149, 320, 80, 80);
contentPane.add(label_15);
label_16 = new JLabel("");
label_16.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\WHITE.png"));
label_16.setBackground(Color.WHITE);
label_16.setBounds(59, 323, 80, 80);
contentPane.add(label_16);
lblDodgeTheBombs = new JLabel("Dodge the bombs!");
lblDodgeTheBombs.setForeground(Color.RED);
lblDodgeTheBombs.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblDodgeTheBombs.setBounds(137, 418, 217, 33);
contentPane.add(lblDodgeTheBombs);
bomb1 = new Timer(1000, new TimerListener());
bomb1.start();
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label_1.setIcon("C:\\Users\\Josh\\Desktop\\blank.png");
}
}
}
The method seticon(icon) in the type jlabel is not applicable for the
arguments (string)
yes its because as per the doc found here the setIcon() accepts a Icon as a parrameter not String. So, your code should be...
label_1.setIcon(new ImageIcon("C:\\Users\\Josh\\Desktop\\blank.png"));
I recommend you to go with documentations in the future. Its really a very good practice.
I think the error message is self-explanatory about what went wrong. The "setIcon()" method expects instance of Icon class and not string instance.
jLabelObject.setIcon("string") // Do not pass image path