I have two JFrames, the first one is used to display SQL table using JTable and the second one is used to update the data on the SQL table. On the first frame, there's a button used to show the second frame and it has radio buttons. However, I can't set it to true. What I want to happen is set the radio button to true based on what value I get from a Label where the Label's value came from the database. Here's what I have done:
FIRST JFRAME:
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
String hours = null;
try
{
DbUpdate up = new DbUpdate();
// To connect on SQL and get the JTable's value
int get = (int)jTable2.getModel().getValueAt(jTable2.getSelectedRow(), 0);
String query= "SELECT * FROM roominfo WHERE CustomerNo = '"+get+"' " ;
String url = "jdbc:mysql://localhost:3306/adve";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
rs = st.executeQuery(query);
while(rs.next())
{
hours= rs.getString("Hours"); // This is where I can get the value for hours and to be passed on a label
}
up.jLabel12.setText(hours); //I set on a Jlabel for the next frame
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Please select a record to update");
}
}
SECOND JFRAME:
public void set(){ //THIS SUPPOSE TO SET THE BUTTONS BASED ON THE VALUE OF THE LABEL
if (jLabel12.getText().equals("12-Hours")) { // if 12-Hours, Rdn12 should be true or selected
Rdn12.isSelected();
Rdn12.setSelected(true);
Rdn24.setSelected(false);
}
else if (jLabel12.getText().equals("24-Hours")) { // if 24-Hours, Rdn24 should be true or selected
Rdn12.setSelected(false);
Rdn24.setSelected(true);
}
jTextField1.setEditable(false);
jLabel20.setVisible(false);
}
However, The radiobutton still won't get selected. What am I doing wrong? Any suggestions? Please help.
UPDATE: I don't know, whether I did quite understand your question. Is this application kind of what you were looking for?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class DatabaseRadioButtons extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new DatabaseRadioButtons().setVisible(true);
}
});
}
JTable table = new JTable();
JButton showSecondFrame = new JButton("Show second frame");
SecondFrame secondFrame = new SecondFrame();
public DatabaseRadioButtons() {
table.setModel(new DefaultTableModel(new Object[][] {
new Object[] { "first", "entry" },
new Object[] { "second", "entry" } }, new Object[] { "column",
"names" }));
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return; // ignore this event, if we expect another event
// right after this one
int selectedRow = table.getSelectedRow();
refreshRadioButtonsAccordingToDatabaseValues(selectedRow);
}
});
showSecondFrame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
secondFrame.setVisible(true);
}
});
}
});
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JScrollPane(table), BorderLayout.CENTER);
panel.add(showSecondFrame, BorderLayout.SOUTH);
setContentPane(panel);
setSize(400, 300);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
protected void refreshRadioButtonsAccordingToDatabaseValues(int selectedRow) {
String databaseValue;
// put you database SELECT here, instead of this fixed value
System.out.println("Make Database select for row " + selectedRow);
databaseValue = selectedRow == 0 ? "12-Hours" : "24-Hours";
// Choose what to do, according to database values
if (databaseValue.equals("12-Hours")) {
// you can change the fields of the second frame directly in here
secondFrame.Rdn12.isSelected();
secondFrame.Rdn12.setSelected(true);
secondFrame.Rdn24.setSelected(false);
} else if (databaseValue.equals("24-Hours")) {
secondFrame.Rdn12.setSelected(false);
secondFrame.Rdn24.setSelected(true);
}
}
}
class SecondFrame extends JFrame {
JRadioButton Rdn12 = new JRadioButton("Radio 12");
JRadioButton Rdn24 = new JRadioButton("Radio 24");
public SecondFrame() {
setSize(400, 300);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocation(100, 100);
JPanel panel = new JPanel(new GridLayout(10, 1));
panel.add(Rdn12);
panel.add(Rdn24);
setContentPane(panel);
}
}
You can change a value of a Label in your Second Frame, but you don't necessarily have to. As my example shows you can just change your checkboxes of your second frame from within the code of your first frame.
Update the refreshRadioButtonsAccordingToDatabaseValues() method to read actual data from your database.
You should do something like this:
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
String hours = null;
try
{
DbUpdate up = new DbUpdate();
int get = (int)jTable2.getModel().getValueAt(jTable2.getSelectedRow(), 0);
String query= "SELECT * FROM roominfo WHERE CustomerNo = '"+get+"' " ;
String url = "jdbc:mysql://localhost:3306/adv";
Connection conn = DriverManager.getConnection(url,"root","sa");
Statement st = conn.createStatement();
rs = st.executeQuery(query);
while(rs.next())
{
hours= rs.getString("Hours");
}
if (hours.equals("12-Hours")) {
// you can change the fields of the second frame directly in here
up.Rdn12.isSelected();
up.Rdn12.setSelected(true);
up.Rdn24.setSelected(false);
} else if (hours.equals("24-Hours")) {
up.Rdn24.isSelected();
up.Rdn12.setSelected(false);
up.Rdn24.setSelected(true);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Please select a record to update");
}
}
Related
I created a shop cart login JFrame and I added a "shopkeeperToggle" so that when it's pressed the user logs in to the shopkeeper's JFrame and otherwise to a shopper's jframe. the problem is I don't know how to implement it, I tried to set a boolean "pressed" to false whenever the key is released in the "shopkeeperToggle" key listener, and apparently I'm unable to use the value of pressed inside the sign-in button.
Here's the code for the toggle:
shopkeeperToggle = new JToggleButton("Shopkeeper");
shopkeeperToggle.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
});
and this is what I'm trying to do in the sign in button:
signinButton = new JButton("Sign in ");
signinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
// select the users that have the inputted credentials from the database
String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernamelogin.getText());
ps.setString(2, emaillogin.getText());
ps.setString(3,passwordlogin.getText());
ResultSet rs = ps.executeQuery();
// if query executed and
if (rs.next()) {
// if login succ show window log succ, and go to home shopping page
JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
if (pressed) {
OwnerHomePage ownerhome = new OwnerHomePage();
ownerhome.setVisible(true);
setVisible(false);
} else {
UserHomePage home = new UserHomePage();
home.setVisible(true);
setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
}
This may offer some help in fixing your issue. It is a fully compilable demo. The following changes were made.
Used Actions in lieu of KeyListener. A little more involved to setup but they can be configured to monitor only certain keys.
Used a JButton in lieu of a JToggleButton. No specific reason and can be changed.
Created separate inner classes for the listeners. Tends to reduce clutter and is usually more readable.
Changed the name of the button depending on the mode.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMapAndButtons {
JFrame frame = new JFrame("Demo");
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new ActionMapAndButtons().start());
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyClass cls = new MyClass();
frame.add(cls);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyClass extends JPanel {
JButton button = new JButton("Shopper Sign in");
boolean pause = false;
public MyClass() {
setPreferredSize(new Dimension(300, 300));
button.addActionListener(new ButtonListener());
add(button);
InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
for (int i = 0; i < 256; i++) {
map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
}
getActionMap().put("anyKey", new MyAction());
setFocusable(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj instanceof JButton) {
JButton b = (JButton) obj;
pause = !pause;
if (pause) {
b.setText("Shopkeeper Sign in");
} else {
b.setText("Shopper Sign in");
}
}
}
}
private class MyAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (pause) {
System.out.println("Shopkeeper - " + cmd);
} else {
System.out.println("Shopper - " + cmd);
}
}
}
}
Inner (or nested) classes and action maps are covered in The Java Tutorials
You can define pressed as a static value;
class c {
static boolean pressed = true;
...
}
and you can access anywhere;
c.pressed; //will return true if you don't change
I am working with java RMI and swing and I have read the values from database but i am unable to read the value of selected row in this code. What i want to JTable to show all databases and it is showing all the available databases in server but i am unable to read the selected row value in this
package schoolclient;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import schoolserver.SchoolInterface;
public class DatabaseList {
JFrame jFrame = null;
JPanel jPanel = null;
JList jList = null;
JTable jTable = null;
String data = null;
schoolserver.SchoolInterface schoolInt = null;
public DatabaseList(SchoolInterface sii) {
schoolInt = sii;
jFrame = new JFrame();
jTable = new JTable(){
public boolean isCellEditable(int row, int column) {
return false;
}
};
jTable.setModel(createTable());
jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTable.addMouseListener(new MouseAdapter() {
public void MouseClicked(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e) && (e.getClickCount() == 2)) {
new createListSelection();
}
}
});
JScrollPane scrollPane = new JScrollPane(jTable);
jFrame.add(scrollPane);
jFrame.setSize(200, 200);
jFrame.setVisible(true);
}
private DefaultTableModel createTable() {
DefaultTableModel dtm = new DefaultTableModel();
dtm.addColumn("Databases", createArray());
return dtm;
}
private class createListSelection implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
ListSelectionModel lsm = jTable.getSelectionModel();
data = (String) jTable.getValueAt(jTable.getSelectedRow(), 0);
System.out.println(data);
}
}
}
Object[] createArray() {
ArrayList<Object> al = null;
Object[] x = null;
try {
al = schoolInt.availableDatabases();
x = new Object[al.size()];
int i = 0;
for(Object o : schoolInt.availableDatabases())
x[i++] = o;
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "no connection to database or "
+ "remote server availabe", "Server Information", JOptionPane.OK_OPTION);
}
return x;
}
}
You look to be over-complicating things. Don't re-add listeners within a listener, but rather simply add one listener, a MouseListener to the JTable, and add it once. Within it check for double clicks (presses) and respond. Something like:
jTable.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
data = (String) jTable.getValueAt(jTable.getSelectedRow(), 0);
System.out.println(data);
}
}
});
Other problems, your method within your MouseAdapter will never be called, ever:
jTable.addMouseListener(new MouseAdapter() {
public void MouseClicked(MouseEvent e) {
// ....
}
});
Your capitalization is wrong, and since MouseAdapter/MouseListener does not have a MouseClicked method (it is mouseClicked) this method is never called. Always place an #Override annotation above any method that you think might be an override, and let the compiler warn you if it is not so. Had you done this, you'd get a prompt warning from the compiler.
Regarding your comment
You never add a selection listener to the JTable. Again the method within the MouseAdapter is never called since it is not capitalized correctly
Even if it did get called, what use is there repeatedly adding a ListSelectionListener?
If your goal is to only respond to double-clicks, a ListSelectionListener is not what you want. Only a MouseListener would work in this situation.
Do read the appropriate tutorials as they explain all of this and well. Please check out the links to be found within the Swing Info tag.
I'm writing a java project and suddenly, out of nowhere eclipse is reporting that I have a problem with my code. It's specific to one file, but others are failing as well as they use a couple functions from the class in question, which they can't seem to find, the functions that is. I've tried almost everything I can think of to make this error go away.
Refreshing project
Clean project
Remove project and re-import
Removing file, make a new, paste content
Removed errors and cleaned project
To be specific the first error is:
Syntax error, insert "}" to complete ClassBody
Just to illustrate, here's the code:
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import model.HolderCompany;
import model.Row;
import viewmodel.App;
public class PanelMain extends JPanel {
private PanelTable table;
private DataDialog editDialog;
private DataDialog addDialog;
private ManageCompaniesDialog mcDialog;
private PanelConsole consolePane;
private JFrame frame;
private ArrayList<Row> data;
private ArrayList<HolderCompany> companies;
private static String[] labelHeaders = {
"ID",
"Deployment Date",
"IMEI",
"Name",
"Model",
"Software Version",
"A51 Device",
"Holder Company",
"Company E-mail",
"Company Phone"
}; //Here is the so called Syntax Error
public PanelMain(){
frame = new JFrame("Mobile Sensor Manager");
setLayout(new BorderLayout());
JPanel pane = new JPanel(new BorderLayout());
consolePane = new PanelConsole();
//Button Pane
JButton addRow = new JButton("Add Row");
addRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addDialog = openDialog("Add Row");
//Wait for return here
Object[] data = addDialog.getData();
if(data != null){
table.addRowToTable(data);
consolePane.write("Added row: " + table.dataToString(data), null);
}
}
});
JButton editRow = new JButton("Edit Row");
editRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int index = table.getSelectedRow();
if(index == -1){
//Write error message
consolePane.write("No row is selected!", null);
} else {
Object[] d1 = table.getData(index);
editDialog = openDialog("Edit Row", data);
Row data = App.getSharedResources().getData().get(index);
editDialog = openDialog("Edit Row", data);
//Wait for return here
Object[] newData = editDialog.getData();
Row newRow = editDialog.getRow();
if(newData != null){
table.changeRowInTable(index, newData);
App.getSharedResources().changeRow(index, newRow);
consolePane.write("Changed row " + index + " to " + table.dataToString(newData), null);
}
}
}
});
JButton deleteRow = new JButton("Delete Row");
deleteRow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int index = table.getSelectedRow();
if(index == -1){
//Write error message
consolePane.write("No row is selected!", null);
} else {
consolePane.write("Removed row: " + table.tableIndexToString(index), null);
table.deleteRowFromTable(index);
App.getSharedResources().removeRow(index);
}
}
});
JButton manageCompanies = new JButton("Manage Companies");
manageCompanies.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mcDialog = openDialog();
}
});
JButton clearDB = new JButton("Clear Database");
JButton deleteDB = new JButton("Delete Database");
JPanel buttonPane = new JPanel(new GridLayout(0, 1));
TitledBorder buttonBorder = new TitledBorder("Buttons");
buttonPane.setBorder(buttonBorder);
buttonPane.add(addRow);
buttonPane.add(editRow);
buttonPane.add(deleteRow);
buttonPane.add(new JSeparator());
buttonPane.add(manageCompanies);
buttonPane.add(new JSeparator());
buttonPane.add(clearDB);
buttonPane.add(deleteDB);
//Table Pane
table = new PanelTable();
JPanel tablePane = new JPanel(new BorderLayout());
TitledBorder dbContentBorder = new TitledBorder("Database Content");
tablePane.setBorder(dbContentBorder);
tablePane.add(table, BorderLayout.CENTER);
pane.add(buttonPane, BorderLayout.LINE_END);
pane.add(tablePane, BorderLayout.CENTER);
pane.add(consolePane, BorderLayout.PAGE_END);
add(pane, BorderLayout.CENTER);
}
public DataDialog openDialog(String name){
Window win = SwingUtilities.getWindowAncestor(this);
return new DataDialog(win, new DataTemplate(), name);
}
public DataDialog openDialog(String name, Object[] data){
Window win = SwingUtilities.getWindowAncestor(this);
return new DataDialog(win, new DataTemplate(), name, data);
}
public DataDialog openDialog(String name, Row data){
Window win = SwingUtilities.getWindowAncestor(this);
return new DataDialog(win, new DataTemplate(), name, data);
}
public ManageCompaniesDialog openDialog() {
Window win = SwingUtilities.getWindowAncestor(this);
return new ManageCompaniesDialog(win, new ManageCompaniesTemplate(companies));
}
public void injectCompanies(ArrayList<HolderCompany> companies) {
this.companies = companies;
}
public void injectData(ArrayList<Row> data) {
this.data = data;
table.injectDataToTable(data);
}
public void addMainToFrame(PanelMain main) {
frame.add(main);
}
public void createAndShowGUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static String[] getHeaders() {
return labelHeaders;
}
}
EDIT
Is it just me or does anyone else get this error?
Any suggestions on how to fix it are welcome!
Okay. I finally managed to fix the error.
As mentioned in the comments in the top post I could get it to compile if I cleared the constructor. Once I got it to compile I slowly copy pasted the code line by line into my project. I left out the ActionListeners and it compiled just fine. After this I slowly imported the ActionListener methods one by one and I found a line that resulted in the error. It was the line:
App.getSharedResources().changeRow(index, newRow); //line 106
This method was not yet implemented and it gave me that as an error after the above explained process. I could create the method and the rest of my code compiles as intended now. This was a really weird error.
I have also faced similar issue sometime in past, could you please try to delete the error from 'Problems' view and perform a clean project afterwards, and see if it disappears.
If it does not help try: looking into the .log file created by eclipse in your workspace directory. That may hold a clue how to fix this.
Application is simple with two panels in one frame
First panel, retrieve from database all student s, use multiple hashmap get parent and child arrangement and show it on tree.
Second panel, when you click on a student all details of that student (selectionlistener) shown in textboxes.
Now when I alter the name of the student on the 2nd panel, the database updates it properly but the tree shows the old value.
I have tried treepanel.reload(), I have tried treemodellistener.
Can anyone help me out here. Going through a lot of solutions online, all are partial which i could not apply to my code.
Thanks in advance.
Main frame.java
/**
* #author Suraj Baliga
*
* Returns a JFrame with two Panels one having the Jtree and other
* having the details of the selected tree component.It also has dynamic tree and
* dynamic textbox where updation of text in the textbox will change the value in
* databse on click of save button.The JDBC localhost url may change with each machine
* as the database location and port number may vary.
*/
package Student_Details;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.commons.collections.MultiHashMap;
public final class Main_frame extends JPanel
{
String sname,sschool;
ArrayList StudName_arrylst = new ArrayList();
ArrayList SchlName_arrylst = new ArrayList();
ArrayList StudDetailTxtFld_arrylst = new ArrayList();
static public Connection connect,connect_update;
public ResultSet resultSet;
public static ResultSet resultset2;
MultiHashMap SchlStud_hashmap = new MultiHashMap();
int i,j,k,k2,z;
DefaultMutableTreeNode tree_parent;
int SchlName_arylist_length, StudNamearrylst_length;
private tree_generation treePanel;
static JButton save_button = new JButton("Save");
static JButton cancel_button = new JButton("Cancel");
static JTextField studName_txtbox= new JTextField();
static JTextField studAddress_txtbox = new JTextField();
static JTextField studOthr_txtbox = new JTextField();
static public String user_name;
static public String user_add;
static public String user_other;
static JLabel name_label = new JLabel("Name : ");
static JLabel address_label = new JLabel("Adress : ");
static JLabel other_label = new JLabel("Other Deatils : ");
static String studDetailsTxtbox_disp[] = new String[10];
static String studDetailsTxtbx_disp_db[] = new String[10];
static String studDetailsTxtbxchange[] = new String[10];
public JPanel panel;
static JPanel panel_boxes = new JPanel();
public Main_frame()
{
super(new BorderLayout());
//Create the components.
treePanel = new tree_generation();
populateTree(treePanel);
//Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.WEST);
panel = new JPanel(new GridLayout(1, 2));
add(panel, BorderLayout.CENTER);
}
public void populateTree(tree_generation treePanel)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement AllStuddetails = connect.prepareStatement("SELECT * from student_details");
resultSet = AllStuddetails.executeQuery();
while (resultSet.next())
{
sname = resultSet.getString(1);
sschool = resultSet.getString(3);
SchlStud_hashmap.put(sschool, sname);
}
}
catch (Exception e)
{
}
Set keySet = SchlStud_hashmap.keySet();
Iterator keyIterator = keySet.iterator();
while (keyIterator.hasNext())
{
Object key = keyIterator.next();
SchlName_arrylst.add(key);
Collection values = (Collection) SchlStud_hashmap.get(key);
Iterator valuesIterator = values.iterator();
while (valuesIterator.hasNext())
{
StudName_arrylst.add(valuesIterator.next());
}
SchlName_arylist_length = SchlName_arrylst.size();
StudNamearrylst_length = StudName_arrylst.size();
String schlname_tree[] = new String[SchlName_arylist_length];
String studname_tree[] = new String[StudNamearrylst_length];
Iterator SchlName_iterator = SchlName_arrylst.iterator();
i = 0;
while (SchlName_iterator.hasNext())
{
schlname_tree[i] = SchlName_iterator.next().toString();
}
Iterator StudName_iterator = StudName_arrylst.iterator();
j = 0;
while (StudName_iterator.hasNext())
{
studname_tree[j] = StudName_iterator.next().toString();
j++;
}
for (k = 0; k < schlname_tree.length; k++)
{
tree_parent = treePanel.addObject(null, schlname_tree[k]);
for (k2 = 0; k2 < studname_tree.length; k2++)
{
treePanel.addObject(tree_parent, studname_tree[k2]);
}
}
StudName_arrylst.clear();
SchlName_arrylst.clear();
}
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Student Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Main_frame newContentPane = new Main_frame();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
panel_boxes.setLayout(null);
name_label.setBounds(55,90,150,100);
studName_txtbox.setBounds(225,130, 155, 25);
panel_boxes.add(name_label);
panel_boxes.add(studName_txtbox);
address_label.setBounds(55,160, 150, 100);
studAddress_txtbox.setBounds(225,200, 155, 25);
panel_boxes.add(address_label);
panel_boxes.add(studAddress_txtbox);
other_label.setBounds(55,220, 150, 100);
studOthr_txtbox.setBounds(225,270, 155, 25);
panel_boxes.add(other_label);
panel_boxes.add(studOthr_txtbox);
save_button.setBounds(150,350, 100, 50);
cancel_button.setBounds(350,350, 100, 50);
panel_boxes.add(save_button);
panel_boxes.add(cancel_button);
frame.add(panel_boxes);
//Display the window.
frame.pack();
frame.setSize(1000,700);
frame.setVisible(true);
save_button.setEnabled(false);
cancel_button.setEnabled(false);
studName_txtbox.addFocusListener(new FocusListener()
{
#Override //since some additional functionality is added by the user to
//the inbuilt function #override notation is used
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
System.out.println("out of focus textbox");
}
});
studAddress_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
studOthr_txtbox.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
cancel_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel_button )
{
clear_textboxes();
}
}
} );
save_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== save_button )
{
selectionButtonPressed();
}
}
} );
}
public void fill_textboxes(ArrayList a1)
{
Iterator alldetails = a1.iterator();
z=0;
while (alldetails.hasNext())
{
studDetailsTxtbx_disp_db[z]= (String) alldetails.next();
System.out.println("this is the Detail : "+studDetailsTxtbx_disp_db[z]);
z++;
}
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
public static void selectionButtonPressed()
{
studDetailsTxtbxchange[0]=studName_txtbox.getText();
studDetailsTxtbxchange[1]=studAddress_txtbox.getText();
studDetailsTxtbxchange[2]=studOthr_txtbox.getText();
try
{
if((studDetailsTxtbxchange[0].equals(""))||(studDetailsTxtbxchange[0] == null)||(studDetailsTxtbxchange[1].equals(""))||(studDetailsTxtbxchange[1] == null)||(studDetailsTxtbxchange[2].equals(""))||(studDetailsTxtbxchange[2] == null))
{
JOptionPane.showMessageDialog(null,"One of the Fields is Blank","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here inside else baby..that has : : "+studDetailsTxtbxchange[0]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement execqry = connect.prepareStatement("select * from student_details where student_name='"+studDetailsTxtbxchange[0]+"'");
resultset2=execqry.executeQuery();
System.out.println("control at end if else");
if(resultset2.next())
{
JOptionPane.showMessageDialog(null,"Sorry This name already exists","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here");
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void clear_textboxes()
{
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
void dbaction(String string)
{
studDetailsTxtbox_disp[0]= string;
System.out.println("This is the stuff :" + studDetailsTxtbox_disp[0]);
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2","suraj","suraj");
PreparedStatement statement4 = connect.prepareStatement("SELECT * from student_details where student_name ='"+studDetailsTxtbox_disp[0]+"'");
resultSet = statement4.executeQuery();
while(resultSet.next())
{
user_name = resultSet.getString("student_name");
StudDetailTxtFld_arrylst.add(user_name);
System.out.println("name :"+user_name);
user_add = resultSet.getString("student_address");
StudDetailTxtFld_arrylst.add(user_add);
System.out.println("address : "+ user_add);
user_other = resultSet.getString("student_school");
StudDetailTxtFld_arrylst.add(user_other);
System.out.println("school : "+user_other);
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
fill_textboxes(StudDetailTxtFld_arrylst);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createAndShowGUI();
}
});
}
}
tree_generation.java
/**
* #author Suraj
*
* Tree generation and actions such as adding new parent or child takes place here
* Section Listeners for displaying relavent details of the selected student.
*/
package Student_Details;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class tree_generation extends JPanel
{
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
public String studDetailsTxtbox_disp[] = new String[10];
public tree_generation()
{
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("Click for Student Details");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener()
{
#Override
public void valueChanged(TreeSelectionEvent e)
{
studDetailsTxtbox_disp[0]= tree.getLastSelectedPathComponent().toString();
Main_frame db = new Main_frame();
db.dbaction(studDetailsTxtbox_disp[0]);
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child)
{
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
}
else
{
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
{
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,
boolean shouldBeVisible)
{
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null)
{
parent = rootNode;
}
//It is key to invoke this on the TreeModel
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the new node.
if (shouldBeVisible)
{
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
static void loadit()
{
tree_generation.treeModel.reload();
//i tried this too//
//treePanel = new tree_generation();
// populateTree(treePanel);
}
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
/*
* If the event lists children, then the changed
* node is the child of the node we've already
* gotten. Otherwise, the changed node and the
* specified node are the same.
*/
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)(node.getChildAt(index));
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
#Override
public void treeStructureChanged(TreeModelEvent e)
{
System.out.println("tree sturct changed") ;
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
tree.updateUI();
e.getTreePath();
}
}
}
Queries - DATABASE NAME : treedata2
create table student_details(student_name varchar(20),student_address varchar(30),student_school varchar(20));
insert into student_details values('suraj','mangalore','dps');
insert into student_details values('prassana','Bangalore lalbagh 23/16 2nd main road','dps');
insert into student_details values('deepika','Mangalore kadri park , 177b','dav');
insert into student_details values('sujith','delhi , rajinder nagar, d black','dav');
insert into student_details values('sanjay','bombay marina drive, 12/34','dav');
insert into student_details values('suresh','jaipur , lalbagh cjhowki','kv');
insert into student_details values('manu','surat, pune warior house','kv');
insert into student_details values('tarun','chennai, glof club','salwan');
insert into student_details values('vinay','haryana, indutrial area','hindu senior');
insert into student_details values('veeru','trivendrum, kottayam 12/77','canara')
Ok, I think I found what's not working in your code, but you should probably try it yourself and confirm.
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
In this code, you indeed update the database but you don't update the model of the tree. You are calling the static method loadit() but that method does not contain any code. In order to worker you should probably refresh/reload your TreeModel. There are different ways to do that. One would be to directly spot the TreeNode to refresh and update it with the new values. Another would be to recreate your entire TreeModel (but this can be costly if your tree is big). Using an object-mapping model (for instance JPA/Hibernate) you could have something much cleaner with an appropriate MVC-pattern and a model notifying the views of the updated values, but it requires extra-effort to set up.
For what it is worth, you should consider dropping those static keywords as they are not necessary nor appropriately used. Whenever possible, you should try to avoid using that keyword (unless it is used in conjunction with finalto describe a constant value).
One more thing, try to use appropriate LayoutManager's instead of using absolute-positionning. Using appropriate layout manager makes your code easier to maintain and more portable across different platforms/look and feels.
I am a bit new to swings, And i was trying to cough up some code involving Jtable.
I find that even though i have added the scrollbar policy the vertical scrollbar does not seem to appear. THe code is pretty shabby.(warning u before hand). But could you please indicate where I need to put in the scrollbar policy. I have tried adding it at a lot of places and it just does not seem to appear.
the other question is how do i make an empty table. As in every time the process button is clicked, i would like to refresh the table. Could u point me in this direction as well.
The directions for usage: just enter a number in the regular nodes textfield like 5 or 10
and click on the process button.
My code :
package ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import utils.ThroughputUtility;
/**
* #author Nathan
*
*/
public class EntryPoint extends JPanel{
public boolean isProcesed =false;
static JFrame frame;
JTabbedPane jTabbedPane = new JTabbedPane();
private static final long serialVersionUID = -6490905886388876629L;
public String messageTobeSent = null;
public int regularNodeCount =0;
public static final String MESSAGE_TO_BE_SENT =" Please Enter the message to be sent. ";
protected static final String ONE = "1";
Map<String,Double> regNodeThroughputMap ;
static JTable tableOfValues;
Object columnNames[] = { "<html><b>Regular Node Name</b></htm>", "<html><b>Throughput Value Obtained</b></html>"};
Object rowData[][] = null;
public EntryPoint() {
jTabbedPane.setTabPlacement(JTabbedPane.NORTH);
Font font = new Font("Verdana", Font.BOLD, 12);
jTabbedPane.setFont(font);
//Server Side Panel.
JPanel serverPanel = getServerPanel();
jTabbedPane.addTab("Server", serverPanel);
//Client side Panel.
JPanel clientPanel = getClientPanel();
jTabbedPane.addTab("Client", clientPanel);
}
private JPanel getClientPanel() {
//Heading Label
JPanel clientPanel = new JPanel();
JLabel RegularNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
RegularNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
RegularNodeLabel.setForeground(new Color(176,23,31));
clientPanel.add(RegularNodeLabel);
return clientPanel;
}
/**Server Side Code
* #return
*/
private JPanel getServerPanel() {
//Heading Label
JPanel serverPanel = new JPanel(new FlowLayout());
final Box verticalBox1 = Box.createVerticalBox();
Box horozontalBox1 = Box.createHorizontalBox();
Box verticalBox2forsep = Box.createVerticalBox();
Box horozontalBox2 = Box.createHorizontalBox();
JPanel heading = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel backBoneNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
backBoneNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
backBoneNodeLabel.setForeground(new Color(176,23,31));
backBoneNodeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Indication of BackBone Node
JPanel body = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel backBoneNodeID = new JLabel("Fixed BackBone Node");
backBoneNodeID.setFont(new Font("Algerian",Font.BOLD,16));
backBoneNodeID.setForeground(new Color(176,23,31));
backBoneNodeID.setAlignmentX(Component.CENTER_ALIGNMENT);
//Seperator
JLabel seperator = new JLabel(" ");
seperator.setFont(new Font("Algerian",Font.BOLD,20));
seperator.setForeground(new Color(176,23,31));
verticalBox2forsep.add(seperator);
//Message label
JLabel messageLabel = new JLabel("Please enter the Message to be sent: ");
messageLabel.setFont(new Font("Algerian",Font.BOLD,16));
messageLabel.setForeground(new Color(176,23,31));
messageLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Message Text
final JTextField messageText = new JTextField(MESSAGE_TO_BE_SENT,25);
messageText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent arg0) {
if(messageText.getText().trim().equalsIgnoreCase(MESSAGE_TO_BE_SENT.trim())){
messageText.setText("");
}
}
});
horozontalBox1.add(messageLabel);
horozontalBox1.add(messageText);
//Regular node attached to backbone nodes.
JLabel regularNodelabel = new JLabel("Number of Regular nodes to be attached to the backbone node. ");
regularNodelabel.setFont(new Font("Algerian",Font.BOLD,16));
regularNodelabel.setForeground(new Color(176,23,31));
regularNodelabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Regular Node text
final JTextField regularNodeText = new JTextField(ONE,5);
regularNodeText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
if(regularNodeText.getText().trim().equalsIgnoreCase(ONE.trim())){
regularNodeText.setText("");
tableOfValues = new JTable(0,0);
}
}
});
horozontalBox2.add(regularNodelabel);
horozontalBox2.add(regularNodeText);
//Button for Processing.
JButton processbutton = new JButton("Process");
processbutton.setFont(new Font("Algerian",Font.BOLD,16));
processbutton.setForeground(new Color(176,23,31));
processbutton.setAlignmentX(Component.CENTER_ALIGNMENT);
//Processing on clciking process button
processbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isProcesed=false;
Runnable runThread = new Runnable() {
#Override
public void run() {
while(!isProcesed){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
verticalBox1.add(tableOfValues);
isProcesed =false;
}
};
Thread processThread= new Thread(runThread);
processThread.start();
regularNodeCount = Integer.parseInt(regularNodeText.getText().trim());
regNodeThroughputMap = getThroughPutValues(regularNodeText.getText().trim());
System.out.println("Map obtained = "+regNodeThroughputMap);
tableOfValues = populateTable(regNodeThroughputMap);
isProcesed=true;
JScrollPane scrollPane = new JScrollPane(tableOfValues);
scrollPane.add(tableOfValues);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
verticalBox1.add(scrollPane,BorderLayout.CENTER);
// verticalBox1.add(scrollPane);
}
});
verticalBox1.add(backBoneNodeID);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox1);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox2);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(processbutton);
heading.add(backBoneNodeLabel);
//body.add(backBoneNodeID);
body.add(verticalBox1);
serverPanel.add(heading);
serverPanel.add(body);
return serverPanel;
}
protected JTable populateTable(Map<String,Double> regNodeThroughputMap) {
/*{ { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" } }*/
rowData = new Object[regularNodeCount+1][2];
Set<Map.Entry<String, Double>> set = regNodeThroughputMap.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.println("key ="+me.getKey());
System.out.println("Value ="+me.getValue());
}
String[] keys = new String[regularNodeCount+2];
String[] values = new String[regularNodeCount+2];
List<String> keyList = new LinkedList<String>();
List<String> valueList = new LinkedList<String>();
keyList.add("");
valueList.add("");
for(String key:regNodeThroughputMap.keySet()){
keyList.add(key);
}
for(double value:regNodeThroughputMap.values()){
System.out.println(value);
valueList.add(Double.toString(value));
}
keyList.toArray(keys);
valueList.toArray(values);
System.out.println(Arrays.asList(keys));
System.out.println(Arrays.asList(values));
rowData[0][0] =columnNames[0];
rowData[0][1] =columnNames[1];
for(int i=1;i<=regularNodeCount;i++){
for(int j=0;j<2;j++){
if(j==0)
rowData[i][j]=keys[i];
if(j==1)
rowData[i][j]=values[i];
}
}
return new JTable(rowData, columnNames);
//Printing the array
/* for (int i =0; i < regularNodeCount; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(" " + rowData[i][j]);
}
System.out.println("");
}
*/
}
protected Map<String, Double> getThroughPutValues(String regularNodeInput) {
return ThroughputUtility.generateMapofNodeAndThroughput(regularNodeInput);
}
protected static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Throughput Optimization for Mobile BackBone Networks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EntryPoint splitPaneDemo = new EntryPoint();
frame.getContentPane().add(splitPaneDemo.jTabbedPane);
JScrollPane sp = new JScrollPane(tableOfValues);
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane .HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.setResizable(false);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(800,600);
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Adding ThroughputUtility.java
package utils;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* #author Nathan
*
*/
public class ThroughputUtility {
public static double MIN =5000;
public static double MAX =10000;
public static final double e =Math.E;
public static final double epsilon = 8.854187 *Math.pow(10,-12);
static int regularNodeCount;
static int counter ;
/**Generates the map of Node and ThroughPut values
* #param regularNodeInput
*/
public static Map<String,Double> generateMapofNodeAndThroughput(String regularNodeInput){
regularNodeCount = Integer.parseInt(regularNodeInput);
List<Double> randNodeDistances =getRandDistanceOfNodes(regularNodeCount);
Map<String,Double> nodeAndThroughputmap = getThroughputValuesForNodes(randNodeDistances);
System.out.println(nodeAndThroughputmap);
return nodeAndThroughputmap;
}
/** Obtains the throughput value based on the distances between
* the regular nodes and the backend Nodes.
* #param randNodeDistances
* #return
*/
private static Map<String, Double> getThroughputValuesForNodes(
List<Double> randNodeDistances) {
Map<String,Double> nodeAndThroughputmap = new LinkedHashMap<String, Double>();
for(double i : randNodeDistances){
double throughputValue = calculateThroughPut(i);
nodeAndThroughputmap.put("RegularNode :"+counter, throughputValue);
counter++;
}
return nodeAndThroughputmap;
}
private static double calculateThroughPut(double distanceij) {
double throughput = 1 /(e*regularNodeCount*distanceij*epsilon);
return throughput;
}
/**Generates the distance dij .
* #param regularNodeCount
* #return
*/
private static List<Double> getRandDistanceOfNodes(int regularNodeCount) {
List<Double> distnodeNumbers = new LinkedList<Double>();
for(int i=0;i<regularNodeCount;i++){
double randnodeNumber = MIN + (double)(Math.random() * ((MAX - MIN) + 1));
distnodeNumbers.add(randnodeNumber);
}
return distnodeNumbers;
}
public static void main(String[] args) {
ThroughputUtility.generateMapofNodeAndThroughput("5");
/*System.out.println(e);
System.out.println(epsilon);*/
}
}
The main problem why you can't see the scroll bar is that you add the table to multiple containers.
when clicking the button, you recreate a lot of swing objects (why?), then you start a thread to add the table to the box (why?? be careful with swing and multithreading if you don't know what you are doing). after that (or before, depending on how long the thread is running) you add the table to the scrollpane.
the scrollpane does not contain your table, because you can only use it once.
A quick fix would be something like this:
create all you GUI stuff once, leave it out of any action listeners and stuff. if you start the application, it should just show an empty table. don't add the same object into multiple containers! you can control the size of your table and scrollpane by using
table.setPreferredSize(new Dimension(width, height));
if you click the button (that is in your action listener), get all the new data and add it it to the table. e.g. by using something like this.
tableOfValues.getModel().setValueAt(value, row, column);
or create a new table model if you have to:
tableOfValues.setModel(new DefaultTableModel(rowData, columnNames));
That's all I can tell you for now by looking at the code...
edit:
in the method populateTable(...) don't create a new table! use the above code to set a new model instead if you have to, or use an existing one and modify its values.
You never at the scroll pane to the JFrame as far as I could tell on
a quick look
You change the data in the TableModel (or replace the TableModel of
the JTable)
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
I had the same problem, just set JTable preferredsize to null and the scrollbar will show up.
Hope it helps