Jtable cant load data from database - java

I cant seems to load data into table despite being able to load column name dynamically. When I try to load data nothing appear despite the fact that Java Icon still showed on the taskbar. It doesn't look like there is anything wrong with GUI itself so I was wondering if opening a connection from constructor will cause logical error.I printed out the locals variables in the second for loop of populateTable method to check if data was passed into local variables and they did, so I don't know exactly what was causing this error.
here is the code for GUI:
public class WeatherFrame extends JFrame {
private JPanel contentPane;
private JTable table;
HealthData health = new HealthData();
private DefaultTableModel model;
String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
"numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherFrame frame = new WeatherFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 300);
contentPane = new JPanel();
contentPane.setBounds(100, 100,750, 200);
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 25, 788, 180);
contentPane.add(scrollPane);
model = new DefaultTableModel();
populateTable();
table = new JTable(model);
scrollPane.setViewportView(table);
JButton btnInsert = new JButton("insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnInsert.setBounds(315, 217, 117, 29);
contentPane.add(btnInsert);
JButton btnDelete = new JButton("delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(198, 243, 117, 29);
contentPane.add(btnDelete);
JButton btnSearch = new JButton("search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnSearch.setBounds(81, 243, 117, 29);
contentPane.add(btnSearch);
JLabel lblWeatherTable = new JLabel("Weather Table");
lblWeatherTable.setBounds(149, 6, 107, 16);
contentPane.add(lblWeatherTable);
JButton btnNext = new JButton("update");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNext.setBounds(198, 217, 117, 29);
contentPane.add(btnNext);
JButton btnRefresh = new JButton("refresh");
btnRefresh.setBounds(81, 217, 117, 29);
contentPane.add(btnRefresh);
}
public void populateTable() {
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> healthdata = new ArrayList<Health>();
healthdata = health.showAllData();
model.addRow(healthdata.toArray());
}
}
this is the constructor for the HealthData class
public HealthData(){
try {
/* Connect to database */
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
statement = connection.createStatement();
data = new ArrayList<Health>();
} catch (Exception e)
{
e.printStackTrace();
}
}
this is the code for showAlldata method
public ArrayList<Health> showAllData(){
ArrayList<Health> list = new ArrayList<Health>();
try {
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(SELECT_ALL_QUERY);
/* Get and print out data from health table : zipcode, county, city, state, year, month, ageGroup, numberOfVisits, MMax, MMin, MNor */
while(result.next()){
Health data = new Health();
int zipcode = result.getInt(1);
data.setZipCode(zipcode);
String county = result.getString(2);
data.setCounty(county);
String city = result.getString(3);
data.setCity(city);
String state = result.getString(4);
data.setState(state);
int year = result.getInt(5);
data.setYear(year);
int month = result.getInt(6);
data.setMonth(month);
String ageGroup = result.getString(7);
data.setAgeGroup(ageGroup);
int numOfVisits = result.getInt(8);
data.setNumOfVisits(numOfVisits);
float MMax = result.getFloat(9);
data.setMMax(MMax);
float MMin = result.getFloat(10);
data.setMMin(MMin);
float MNor = result.getFloat(11);
data.setMNor(MNor);
list.add(data);
connection.close()
stmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
Can someone suggest a solution for solving this problem. Thank you in advance for helping. I already posted a question about this but this question is up to date with required codes.
I edit the code to make only one call to showAlldata and also close connection and statement, however, the same error still persist

public void populateTable() {
model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> temp = new ArrayList<Health>();
temp = health.showAllData();
for(int i = 0; i< temp.size(); i++) {
Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
model.addRow(data);
}
}
thank you very much for helping, I solved this question by modifying my populateTable Method as above.

Related

Adding a hyperlink to a single value of sql in jTable

I am implementing a search interface in eclipse with the help of mysql. My search interface yields the results I want, but I want to be able to have the "video_url" column clickable and bring up a hyperlink. Is there a way to do this for a single column? Right now the Jtable is "editable", so the user can click on it, but no changes are made to it. The link can be copied and then pasted later, but I'm really trying to have the link be opened from the interface.
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VIdeo_search_test window = new VIdeo_search_test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public VIdeo_search_test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.setBounds(400, 400, 1050, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblVideoSearch = new JLabel("Video Search");
lblVideoSearch.setFont(new Font("Tahoma", Font.PLAIN, 19));
lblVideoSearch.setBounds(241, 11, 230, 27);
frame.getContentPane().add(lblVideoSearch);
JButton btnSearchCity = new JButton("Search City");
btnSearchCity.setBounds(216, 80, 165, 25);
btnSearchCity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_city = '" +txtCity.getText()+"'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
frame.getContentPane().add(btnSearchCity);
JButton btnSearchTag = new JButton("Search Tag");
btnSearchTag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_tags LIKE '"+txtTag.getText()+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table_1.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
btnSearchTag.setBounds(216, 303, 165, 25);
frame.getContentPane().add(btnSearchTag);
txtCity = new JTextField();
txtCity.setBounds(216, 49, 165, 20);
frame.getContentPane().add(txtCity);
txtCity.setColumns(10);
table = new JTable();
table.setBounds(10, 116, 867, 135);
frame.getContentPane().add(table);
txtTag = new JTextField();
txtTag.setColumns(10);
txtTag.setBounds(216, 272, 165, 20);
frame.getContentPane().add(txtTag);
table_1 = new JTable();
table_1.setBounds(10, 341, 601, 135);
frame.getContentPane().add(table_1);
JButton btnViewVideo = new JButton("View Video");
btnViewVideo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
registered_video_interface info = new registered_video_interface();
registered_video_interface.main(null); }
});
btnViewVideo.setBounds(251, 509, 89, 23);
frame.getContentPane().add(btnViewVideo);
}
}

how can i remove and replace jlabel with image icon in java?

Im trying to create a banking system and to not make it boring we tried to add some image icon into the program in jlabel, when i tried to run the code and first pin mistake, removes the tester label successfully but the problem is when tries are equal to 4, Label pinwrongtester doesn't seem to remove instead it is mixing with the Label that i programmed when they entered pin 4 times, i hope you guys can help me to solve this mistakes
public void Option()
{
//option title
JLabel label = new JLabel("Choose Options");
label.setFont(new Font("Consolas",Font.BOLD,20));
JButton choose = new JButton();
choose.add(label);
choose.setBounds(200,300,200,40);
choose.setBackground(Color.white);
choose.setEnabled(false);
// Buttons Option
JButton Balance = new JButton("Balance");
JButton Withdraw= new JButton("Withdraw");
JButton Send = new JButton("Transfer");
JButton Exit = new JButton("Exit");
//Set Bounds
Balance.setBounds(50,350,200,40);
Withdraw.setBounds(50,450,200,40);
Send.setBounds(350,350,200,40);
Exit.setBounds(350,450,200,40);
//addActionListener
Balance.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinbalance();
}
});
Withdraw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pinwithdraw();
}
});
Send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pintransferfunds();
}
});
//add buttons and labels
p.add(choose);
p.add(Balance);
p.add(Withdraw);
p.add(Send);
p.add(Exit);
}
JPanel enterpinbg;
JFrame enterpinframe;
String account_name;
String balance;
String pindb;
JLabel tester;
JLabel pinwrongtester;
JLabel pinwrongertester;
JLabel balancetester;
JFrame balanceframe;
JPanel balancepanel;
ImageIcon enteryourpin;
ImageIcon pinwrong;
ImageIcon pinwronger;
ImageIcon balanceicon;
private LinkedList<String> picturetrans;
JTextField inputpin;
boolean police = false;
int x =0;
public void pinbalance()
{
//PIN FRAME
enterpinframe = new JFrame("Enter Pin");
enterpinframe.setSize(WIDTH,HEIGHT);
enterpinframe.setVisible(true);
enterpinframe.setResizable(false);
enterpinframe.setLocationRelativeTo(null);
enterpinframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//PIN PANEL
enterpinbg = new JPanel();
enterpinbg.setSize(WIDTH,HEIGHT);
enterpinbg.setBackground(Color.orange);
enterpinbg.setVisible(true);
enterpinbg.setLayout(null);
enterpinframe.add(enterpinbg);
inputpin = new JTextField();
inputpin.setFont(new Font("Consolas",Font.BOLD,20));
inputpin.setForeground(Color.gray);
//Setbounds
inputpin.setBounds(250,600,100,40);
//tester + image
enteryourpin = new ImageIcon(getClass().getResource("Enter yout PIN.png"));
tester = new JLabel(enteryourpin);
tester.setBounds(50,50,500,500);
//enterpin Add
enterpinbg.add(tester);
enterpinbg.add(inputpin);
this.dispose();
inputpin.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==(KeyEvent.VK_ENTER))
{
String pinx = inputpin.getText();
Connection con= null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER1);
Class.forName(JDBC_DRIVER2);
con = DriverManager.getConnection(URL,USER,PASS);
stmt=con.createStatement();
String sql ="SELECT*FROM TBL_BANK WHERE PIN ='"+pinx+"' ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
pindb = rs.getString("PIN");
account_name = rs.getString("ACCOUNT_NAME");
balance = rs.getString("BALANCE");
}
rs.close();
}
catch(Exception f)
{
System.out.println(f);
}
//if Login Success and Failed
if(pinx.equals(pindb))
{
// Balance will show up
}
else if(pinx!=(pindb))
{
enterpinbg.remove(tester);
x++;
System.out.println("x");
inputpin.setText("");
pinwrong = new ImageIcon(getClass().getResource("PIN Wrong (1_2Times).png"));
pinwrongtester = new JLabel(pinwrong);
pinwrongtester.setBounds(50,50,500,500);
enterpinbg.add(pinwrongtester);
enterpinbg.repaint();
if(x>=4 )
{
// this doesnt quite work please help me fix it
enterpinbg.remove(pinwrongtester);
enterpinbg.repaint();
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});

Previous instance of table appends to the newly invoked table. The page should show only one table

When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}

How to make TableView with status = 1 so data stored on jtable

How to make TableView with query select * from tableXXX where status='1'
if status = 1 data shown in jtable
else if status = 0 data not shown in jtable
or how to refresh jtable after status updated from 1 to 0`
This mycode
public class ViewDapur extends JInternalFrame implements ListenerDapur, ListSelectionListener{
private static final long serialVersionUID = -1108049190501656840L;
Connection konek;
Statement state;
//private ControllerDapur controllermak,controllermin;
private ModelDapur modelmak,modelmin;
private TableModelDapur tableModelmak, tableModelmin;
private JTable table;
private JTable tablemak;
private JTable tablemin;
public JTable getInputTable(){
return table;
}
public ViewDapur() {
setSize(1320, 590);
setTitle("DATA ORDERAN TRIPLE SIX");
setMaximizable(false);
setIconifiable(true);
setClosable(true);
setResizable(true);
setFrameIcon(new ImageIcon(ViewDapur.class.getResource("/com/sun/javafx/scene/web/skin/Undo_16x16_JFX.png")));
setBorder(new MatteBorder(2, 2, 2, 2, (Color) Color.MAGENTA));
setNormalBounds(new Rectangle(20, 0, 0, 0));
//controllermak = new ControllerPramusaji();
tableModelmak = new TableModelDapur();
modelmak = new ModelDapur();
modelmak.setListener(this);
//controllermak.setModel(modelmak);
//controllermin = new ControllerPramusaji();
tableModelmin = new TableModelDapur();
modelmin = new ModelDapur();
modelmin.setListener(this);
//controllermin.setModel(modelmin);
init();
tablemak.setModel(tableModelmak);
tablemak.getTableHeader().setReorderingAllowed(false);
tablemin.setModel(tableModelmin);
tablemin.getTableHeader().setReorderingAllowed(false);
try {
loadDatabasemak();
} catch (Exception ex) {
// TODO: handle exception
}
try {
loadDatabasemin();
} catch (Exception ex) {
// TODO: handle exception
}
/* Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
viewTabelMakanan("1");
viewTabelMinuman("1");
}
});
timer.start();timer.setRepeats(false);
*/ //refreshTablemamin();
//viewTabelMakanan("1");
//viewTabelMinuman("1");
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//Timer timer = new Timer(1000, new ActionListener() {
// public void actionPerformed(ActionEvent e) {
ViewDapur frame = new ViewDapur();
frame.setVisible(true);
// }
// });
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
private void init(){
JPanel panel = new JPanel();
panel.setBackground(new Color(119, 136, 153));
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "......"));
getContentPane().add(panel);
panel.setLayout(null);
tablemak = new JTable();
tablemak.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"No Meja", "Menu", "Jumlah", "No Antri"
}
));
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 640, 540);
panel_2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Makanan"));
panel_2.setLayout(null);
panel_2.add(tablemak);
panel.add(panel_2);
JScrollPane scrollPane2 = new JScrollPane(tablemak,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane2.setBounds(10, 26, 616, 502);
panel_2.add(scrollPane2);
scrollPane2.setViewportView(tablemak);
JPanel panel_1 = new JPanel();
panel_1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Daftar Order Minuman"));
panel_1.setBounds(660, 11, 650, 537);
panel.add(panel_1);
panel_1.setLayout(null);
tablemin = new JTable();
tablemin.setBounds(241, 24, 0, 0);
panel_1.add(tablemin);
JScrollPane scrollPane = new JScrollPane(tablemin,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 25, 627, 501);
panel_1.add(scrollPane);
scrollPane.setViewportView(tablemin);
}
private void loadDatabasemak() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmak.setList(daovi.selectAll());
}
private void loadDatabasemin() throws ErrorInfo, SQLException{
DAOdapur daovi = UtilGlobal.getDAOdapur();
tableModelmin.setList(daovi.selectAll2());
}
#Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDelete() {
// TODO Auto-generated method stub
}
#Override
public void onChange(ModelDapur model) {
// TODO Auto-generated method stub
}
public void refreshTablemamin() {
tablemak.revalidate();
tablemak.repaint();
tablemak.getSelectionModel().clearSelection();
tablemin.revalidate();
tablemin.repaint();
tablemin.getSelectionModel().clearSelection();
tableModelmak.fireTableDataChanged();
tableModelmin.fireTableDataChanged();
}
public void viewTabelMakanan(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MAKANAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmak.add(p);
tableModelmak.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
public void viewTabelMinuman(String status){
//mejahe="";
try {
konek = Koneksi.getKoneksi();
state = konek.createStatement();
String query = "select * from tbtrans where katmenu='MINUMAN' AND stord='"+status+"' AND stdpr='0'";
ResultSet result= state.executeQuery(query);
while(result.next()){
Dapur p = new Dapur();
p.setNokey(result.getString("nokey"));
p.setNovisitor(result.getString("novisitor"));
p.setNomeja(result.getInt("nomeja"));
p.setNoantri(result.getInt("noantri"));
p.setAddedpeg(result.getString("addedpeg"));
p.setKdmc(result.getInt("kdmc"));
p.setMncafe(result.getString("mncafe"));
p.setKatmenu(result.getString("katmenu"));
p.setQty(result.getDouble("qty"));
p.setHrg(result.getDouble("hrg"));
p.setSubtotal(result.getDouble("subtotal"));
p.setWorder(result.getString("worder"));
p.setStord(result.getInt("stord"));
p.setWsaji(result.getString("wsaji"));
p.setStdpr(result.getInt("stdpr"));
p.setStkasir(result.getInt("stkasir"));
p.setPegkasir(result.getString("pegkasir"));
tableModelmin.add(p);
tableModelmin.fireTableDataChanged();
}
}
catch(Exception e){
e.printStackTrace();
}
//Pramusaji p = new Pramusaji();
}
}

Issues with JList Calculation (CVE)?

I've been trying to get a running total price of all the elements within my Jlist as they are being added however just can't seem to get it to work. I've tried to provide the classes necessary to be able to reproduce my problem for greater clarity on what I'm trying to do. Thank you.
-Main GUI
public class PaymentSystemGUI extends javax.swing.JFrame {
private JLabel priceLabel;
private JLabel totalLabel;
private JTextField totalField;
private JButton scanBtn;
private JList checkoutList;
private JScrollPane jScrollCheckout;
private JLabel jLabel1;
private JButton removeBtn;
private JButton addBtn;
private JTextField priceField;
private JTextField barcodeField;
private JLabel barcodeLabel;
private JTextField itemNameField;
private JLabel jItemName;
private JLabel editorLabel;
private JScrollPane checkScrollPane;
private JScrollPane jScrollPane1;
private JMenuItem exitButton;
private JMenu StartButton;
private JMenuBar MainMenBar;
private DefaultListModel Inventory = new DefaultListModel();
private DefaultListModel checkoutBasket = new DefaultListModel();
private JList productList;
private InventoryList stockInst;
private JFileChooser chooser;
private File saveFile;
private boolean changesMade;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PaymentSystemGUI inst = new PaymentSystemGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public PaymentSystemGUI() {
super();
initGUI();
stockInst = new InventoryList();
productList.setModel(stockInst);
checkoutList.setModel(checkoutBasket);
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(new java.awt.Color(245, 245, 245));
this.setEnabled(true);
{
MainMenBar = new JMenuBar();
setJMenuBar(MainMenBar);
{
StartButton = new JMenu();
MainMenBar.add(StartButton);
StartButton.setText("File");
{
exitButton = new JMenuItem();
StartButton.add(exitButton);
exitButton.setText("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
);
}
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(31, 84, 275, 323);
jScrollPane1.setAlignmentY(0.4f);
{
ListModel stockListModel = new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
productList = new JList();
jScrollPane1.setViewportView(productList);
BorderLayout stockListLayout = new BorderLayout();
productList.setLayout(stockListLayout);
productList.setBounds(25, 92, 269, 330);
productList.setAlignmentX(0.4f);
productList.setModel(stockListModel);
}
}
{
editorLabel = new JLabel();
getContentPane().add(editorLabel);
editorLabel.setText("INVENTORY");
editorLabel.setBounds(121, 56, 88, 16);
}
{
jItemName = new JLabel();
getContentPane().add(jItemName);
jItemName.setText("Item Name");
jItemName.setBounds(31, 432, 61, 16);
}
{
itemNameField = new JTextField();
getContentPane().add(itemNameField);
itemNameField.setBounds(127, 426, 130, 28);
}
{
barcodeLabel = new JLabel();
getContentPane().add(barcodeLabel);
barcodeLabel.setText("Barcode Number");
barcodeLabel.setBounds(27, 476, 94, 16);
}
{
barcodeField = new JTextField();
getContentPane().add(barcodeField);
barcodeField.setBounds(127, 470, 130, 28);
}
{
priceLabel = new JLabel();
getContentPane().add(priceLabel);
priceLabel.setText("Price of Item");
priceLabel.setBounds(33, 521, 68, 16);
}
{
priceField = new JTextField();
getContentPane().add(priceField);
priceField.setBounds(127, 515, 130, 28);
}
{
addBtn = new JButton();
getContentPane().add(addBtn);
addBtn.setText("Add");
addBtn.setBounds(53, 560, 83, 28);
}
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evta) {
addButtonPressed();
}
});
{
removeBtn = new JButton();
getContentPane().add(removeBtn);
removeBtn.setText("Remove");
removeBtn.setBounds(148, 560, 83, 28);
removeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeButtonPressed();
}
});
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("CHECKOUT");
jLabel1.setBounds(480, 79, 68, 16);
}
{
jScrollCheckout = new JScrollPane();
getContentPane().add(jScrollCheckout);
jScrollCheckout.setBounds(395, 107, 248, 323);
{
ListModel checkoutListModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
checkoutList = new JList();
jScrollCheckout.setViewportView(checkoutList);
checkoutList.setModel(checkoutListModel);
}
}
{
scanBtn = new JButton();
getContentPane().add(scanBtn);
scanBtn.setText("Scan Item into Checkout");
scanBtn.setBounds(59, 613, 161, 28);
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValue());
double totalAddedValue = 0.00;
double oldCheckoutValue = 0.00;
//Iterate to get the price of the new items.
for (int i = 1; i < productList.getModel().getSize(); i++) {
InventItem item = (InventItem) productList.getModel().getElementAt(i);
totalAddedValue += Double.parseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
String checkoutField = totalField.getText();
//Check that cartTextField already contains a value.
if(checkoutField != null && !checkoutField.isEmpty())
{
oldCheckoutValue = Double.parseDouble(checkoutField);
}
totalField.setText(String.valueOf(oldCheckoutValue + totalAddedValue));
checkoutBasket.addElement(productList);
}
});
}
{
totalField = new JTextField();
getContentPane().add(totalField);
totalField.setBounds(503, 442, 115, 28);
totalField.setEditable(false);
}
{
totalLabel = new JLabel();
getContentPane().add(totalLabel);
totalLabel.setText("Total Cost of Items");
totalLabel.setBounds(367, 448, 124, 16);
}
pack();
this.setSize(818, 730);
}
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
private void loadMenuItemAction() {
try {
FileInputStream in = new FileInputStream("itemdata.dat");
ObjectInputStream oIn = new ObjectInputStream(in);
stockInst = (InventoryList)oIn.readObject();
productList.setModel(stockInst);
oIn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Failed to read file");
System.out.println("Error : " + e);
}
}
private void clearAllTextFields() {
barcodeField.setText("");
itemNameField.setText("");
priceField.setText("");
}
private void removeButtonPressed() {
int selectedIndex = productList.getSelectedIndex();
if (selectedIndex == -1) {
JOptionPane.showMessageDialog(this, "Select An Item to Remove");
} else {
InventItem toGo = (InventItem)stockInst.getElementAt(selectedIndex);
if (JOptionPane.showConfirmDialog(this, "Do you really want to remove the item from the cart ? : " + toGo,
"Delete Confirmation", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION) {
stockInst.removeItem(toGo.getID());
clearAllTextFields();
productList.clearSelection();
}
}
}
private void addButtonPressed() {
String newbarcode = barcodeField.getText();
String newitemName = itemNameField.getText();
String newprice = priceField.getText();
if (newbarcode.equals("") || newitemName.equals("") || newprice.equals("")) {
JOptionPane.showMessageDialog(this, "Please Enter Full Details");
} else {
stockInst.addInventItem(newbarcode, newitemName, newprice);
InventItem newBasket = stockInst.findItemByName(newbarcode);
productList.setSelectedValue(newBasket, true);
clearAllTextFields();
}
}
}
-InventoryList
import javax.swing.DefaultListModel;
public class InventoryList extends DefaultListModel {
public InventoryList(){
super();
}
public void addInventItem(String idNo, String itemName, String total){
super.addElement(new InventItem(idNo, itemName, total));
}
public InventItem findItemByName(String name){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public InventItem findItemByBarcode(String id){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getID().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
InventItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
InventoryItem
import java.io.Serializable;
public class InventItem implements Serializable {
private String idnum;
private String itemName;
private String cost;
public InventItem() {
}
public InventItem (String barno, String in, String price) {
idnum = barno;
itemName = in;
cost = price;
}
public String getID(){
return idnum;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return cost;
}
public String toString(){
return idnum + ": " + itemName + ", £ " + cost;
}
}
I'm a beginner and don't quite know how to change my code to add a single element from the list.
Read the List API and you will find methods like:
size()
get(...)
So you create a loop that loops from 0 to the number of elements. Inside the loop you get the element from the List and add it to the model of the checkoutBasket JList.
Here is the basics of an MCVE to get you started. All you need to do is add the code for the actionPerformed() method to copy the selected item(s):
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JList<String> left;
JList<String> right;
JLabel total;
public SSCCE()
{
setLayout( new BorderLayout() );
// change this to store Integer objects
String[] data = { "one", "two", "three", "four", "five", "four", "six", "seven" };
left = new JList<String>(data);
add(new JScrollPane(left), BorderLayout.WEST);
right = new JList<String>( new DefaultListModel<String>() );
add(new JScrollPane(right), BorderLayout.EAST);
JButton button = new JButton( "Copy" );
add(button, BorderLayout.CENTER);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultListModel<String> model = (DefaultListModel<String>)right.getModel();
List<String> selected = left.getSelectedValuesList();
for (String item: selected)
model.addElement( item );
// add code here to loop through right list and total the Integer items
total.setText("Selected total is ?");
}
});
total = new JLabel("Selected total is 0");
add(total, BorderLayout.SOUTH);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you have a problem then delete your original code and post the MCVE showing what you have tried based on the information in this answer. Don't create a new posting.
Edit:
My original answer talked about copying the data from the DefaultListModel. However, your code is using the JList.getSelectedValuesList() method to get a List of selected items. Each of these items needs to be copied from the List to the ListModel of the JList. I updated my answer to reflect this part of your code. I even wrote the code to show you how to copy the items from the list.
So now your next step is to calculate the a total of the items in the "right" JLIst (ie, your checkout basked). In order to do this, you need to change the data in the "left" list to be "Integer" Objects. So now when you copy the Integer objects yo9u can then iterate through the JList and calculate a total value. If you have problems, then any code you post should be based on this MVCE and NOT your real program.

Categories