authentication -- making username and password global in java - java

I wanted to authenticate a user.
For this I am using mysql connection.
The following is the code :
JTextField txt_Username= new JTextField();
String Username;
txt_Username.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
{
Username= txt_Username.getText();
}
});
Similarly there is code for password.
Now I want this username and password outside of its local scope so that clicking on the JButton will fire the sql databse and authenticate with the above username and password.
I am a naive in Java. Could anybody please help in here ?
I have the full code here . Please I need to understand where I am going wrong :
import java.awt.EventQueue;
public class Frame{
private private JFrame frame1;
private JTextField textFieldUserName;
private JTextField txtPassword;
public String textUserValue;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame window = new Frame();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws SQLException
*/
public multipleFrame() throws SQLException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws SQLException
*/
private void initialize() throws SQLException {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("C:\\sad.jpg"));
lblNewLabel.setBounds(10, 36, 196, 187);
frame.getContentPane().add(lblNewLabel);
JLabel lbl_Password = new JLabel("PASSWORD");
lbl_Password.setBackground(new Color(128, 128, 128));
lbl_Password.setOpaque(true);
lbl_Password.setBounds(217, 140, 75, 14);
frame.getContentPane().add(lbl_Password);
final Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/schema","user","pwd");
final JTextField textFieldUserName = new JTextField();
textFieldUserName.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
String textUserValue = textFieldUserName.getText();
System.out.println(textUserValue+" hi");
String textUserValue1 =textUserValue;
}
});
System.out.println(textUserValue+" HI");
textFieldUserName.setBounds(324, 79, 108, 20);
frame.getContentPane().add(textFieldUserName);
textFieldUserName.setColumns(10);
System.out.println();
JLabel label = new JLabel("USERNAME");
label.setOpaque(true);
label.setBackground(Color.GRAY);
label.setBounds(216, 82, 75, 14);
frame.getContentPane().add(label);
txtPassword = new JTextField();
txtPassword.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
String textPasswordValue = txtPassword.getText();
System.out.println(textPasswordValue+" hi");
}
});
txtPassword.setColumns(10);
txtPassword.setBounds(324, 137, 108, 20);
frame.getContentPane().add(txtPassword);
JButton btnLogin = new JButton("LOGIN");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnLogin.setBounds(262, 200, 91, 23);
frame.getContentPane().add(btnLogin);
PreparedStatement stmt1 = null;
try {
stmt1 = con.prepareStatement("select username from LOGIN_TABLE where username='"+textUserValue+"'");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet result1 = null;
try {
result1 = stmt1.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (result1.next()) {
String user_name_db=result1.getString("username");
System.out.println(user_name_db);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Turn your Username variable into public. And place it just inside the class, not in any method.
Example:
public String Username;
Or if you want to retain its privacy you can create a .getMethod for it.
public String getUsername(){
return Username;
}

You can just create a model class with getters and setters:
class UserModel.java
public String Username;
public String getUserName()
{
return Username;
}
public void setUserName(String USER_NAME)
{
this.Username = USER_NAME;
}
In the main.java,
UserModel userObj = new UserModel();
txt_Username.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent arg0) {
{
userObj.setUserName(txt_Username.getText());
//Username= txt_Username.getText();
}
});
To retrieve it anywhere in main.java, use
String userName = userObj.getUserName();

Related

Java Socket need to get name of sender

I'm starting with Socket Server in Java. I've written already simple app where I can send text between hosts. I'm sending with my message name of the host which is sending and here is my problem, how can I get host message?
Can someone just change my code to show host name instead of message?
Here is the code:
public class FMain extends JFrame {
private JPanel contentPane = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FMain frame = new FMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 508, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
PReceiver receiver = new PReceiver();
receiver.setBorder(new LineBorder(new Color(0, 0, 0)));
receiver.setBounds(35, 13, 423, 106);
contentPane.add(receiver);
PSender sender = new PSender((String) null, 0);
sender.setBorder(new LineBorder(new Color(0, 0, 0)));
sender.setBounds(35, 132, 423, 129);
contentPane.add(sender);
}
}
And the class which is receiving:
interface MyListener {
void messageReceived(String theLine);
}
class Receiver {
private List < MyListener > ml = new ArrayList < MyListener > ();
private Thread t = null;
private int port = 0;
private ServerSocket s = null;
private boolean end = false;
public void stop() {
t.interrupt();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
end = false;
t = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new ServerSocket(port);
while (true) {
Socket sc = s.accept();
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine = br.readLine();
ml.forEach((item) - > item.messageReceived(theLine));
sc.close();
}
} catch (SocketException e) {} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
public void addMyListener(MyListener m) {
ml.add(m);
}
public void removeMyListener(MyListener m) {
ml.remove(m);
}
Receiver(int port) {
this.port = port;
}
}
public class PReceiver extends JPanel implements MyListener {
private JTextField txtPort;
private Receiver r = null;
private JTextField txtMessage;
/**
* Create the panel.
*/
public PReceiver() {
setLayout(null);
txtPort = new JTextField();
txtPort.setBounds(282, 13, 62, 22);
add(txtPort);
// txtPort.setColumns(10);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(241, 16, 35, 16);
add(lblPort);
JToggleButton btnListen = new JToggleButton("Listen");
btnListen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (btnListen.isSelected()) {
r = new Receiver(Integer.parseInt(txtPort.getText()));
r.addMyListener(PReceiver.this);
r.start();
} else {
r.stop();
}
}
});
btnListen.setBounds(265, 70, 79, 25);
add(btnListen);
JLabel lblMessage = new JLabel("message");
lblMessage.setBounds(12, 51, 56, 16);
add(lblMessage);
txtMessage = new JTextField();
txtMessage.setBounds(12, 71, 220, 22);
add(txtMessage);
//txtMessage.setColumns(10);
}
#Override
public void messageReceived(String theLine) {
txtMessage.setText(theLine);
}
}
And the sender class:
class Sender {
public void send(String message, String host, int port) {
Socket s;
try {
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(out, false);
pw.println(message);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PSender extends JPanel {
private JTextField txtMessage;
private JTextField txtHost;
private JTextField txtPort;
private JLabel lblMessage;
/**
* Create the panel.
*/
public PSender(String host, int port) {
setLayout(null);
txtMessage = new JTextField();
txtMessage.setBounds(12, 77, 216, 22);
add(txtMessage);
//txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
new Sender().send(txtMessage.getText(), txtHost.getText(), Integer.parseInt(txtPort.getText()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
btnSend.setBounds(268, 76, 78, 25);
add(btnSend);
txtHost = new JTextField();
txtHost.setBounds(51, 13, 149, 22);
add(txtHost);
//txtHost.setColumns(10);
txtPort = new JTextField();
txtPort.setBounds(268, 13, 78, 22);
add(txtPort);
//txtPort.setColumns(10);
JLabel lblHost = new JLabel("host:");
lblHost.setBounds(12, 16, 35, 16);
add(lblHost);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(231, 16, 35, 16);
add(lblPort);
lblMessage = new JLabel("message");
lblMessage.setBounds(12, 58, 56, 16);
add(lblMessage);
}
}

how to dedug in eclipse and solve Unknown Source erros

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

Jtable cant load data from database

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.

How to print the console output in a notepad file?

I want to know how my console output can be save in a notepad file?
import java.awt.EventQueue;
public class HLS1 {
private JFrame frmHttpsLiveStreaming;
private JTextField textField;
// file is accessed to the whole class
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HLS1 window = new HLS1();
window.frmHttpsLiveStreaming.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HLS1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHttpsLiveStreaming = new JFrame();
frmHttpsLiveStreaming.setTitle("HTTPS Live Streaming");
frmHttpsLiveStreaming.setBounds(100, 100, 494, 112);
frmHttpsLiveStreaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHttpsLiveStreaming.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Open File");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Argument:" + arg0);
JFileChooser fs = new JFileChooser(new File("c:\\"));
fs.setDialogTitle("Open a file");
fs.setFileFilter(new FileTypeFilter(".m3u8", ""));
fs.setFileFilter(new FileTypeFilter(".m3u", ""));
fs.showOpenDialog(null);
file = fs.getSelectedFile();
textField.setText(file.getAbsolutePath());
}
});
btnBrowse.setBounds(336, 7, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnBrowse);
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("");
}
});
btnNewButton_1.setBounds(237, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton_1);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(83, 11, 24, 14);
frmHttpsLiveStreaming.getContentPane().add(lblUrl);
textField = new JTextField();
textField.setBounds(116, 11, 210, 19);
frmHttpsLiveStreaming.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Check");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
List<String> fileArray = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Scanner s = null;
if(textField.getText().matches(regex)){
URL url = new URL(textField.getText());
s= new Scanner(url.openStream());
}else{
s = new Scanner(new BufferedReader(new FileReader(file)));
}
if(s != null){
while(s.hasNextLine()){
String line = s.nextLine();
if(!line.isEmpty()){
fileArray.add(line);
}
System.out.println(line);
}
}
s.close();
errors.addAll(validateEXTM3U(fileArray));
for (String error : errors) {
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(126, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton);
}
private List<String> validateEXTM3U(List<String> fileArray){
List<String> errors = new ArrayList<String>();
String tag = fileArray.get(0);
if(!tag.equals("#EXTM3U")){
errors.add("First line in the menifest file is not #EXTM3U");
}
return errors;
}
}
It could be a hacky solution , but if you are running in windows or linux then you can pipe / redirect it.
java HLS1 > notepad.txt
if not what you are looking for , then why not using something called log4j ?
Why don't you write your own utility that has an public static void output(String output) method. Then instead of using System.out.println("...") you call output("...") then in your output(String output) method you can do anything with the output, like first write to the file, then print to the console.
Hope this helps.

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

Categories