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
Related
I am trying to create a program in java that makes the letters of a string appear one at a time into a JLabel, but the text just appears all at once every time. The more the delay on the Thread.Sleep();, the longer it takes to appear. I think what is happening is that it is writing it all out and then printing it into the Label, but i still don't know what to do to fix it. The code is here:
package uiTesting;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class ScrollingText extends JFrame {
private JPanel contentPane;
//Variables and values
public static String ThingToBePrinted = "You look down the gigantic hallway, the cold breath of spirits breathing down your neck. "
+ "Its nothing you haven't felt before. The spirits of those long past were always closer here, where many of them met"
+ " their end. Maybe you would be one of them, someday. But not today. Today, there was still too much to be done to rest.";
public static String ThingPrinted = "";
public static int Mili = 100;
public String html1 = "<html><body style='width: ";
public String html2 = "px'>";
/**
* Launch the application.
*/
public static void main(String[] args) {
System.out.println(ThingToBePrinted.length());
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScrollingText frame = new ScrollingText();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ScrollingText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 719, 504);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//The only Label
JLabel Scrolling_L1 = new JLabel("");
Scrolling_L1.setFont(new Font("Tahoma", Font.PLAIN, 15));
Scrolling_L1.setVerticalAlignment(SwingConstants.TOP);
Scrolling_L1.setBounds(10, 11, 693, 354);
contentPane.add(Scrolling_L1);
//The only Button
JButton Master_B1 = new JButton("Print Text");
Master_B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
//scrolling function
for (int i = 0; i < ThingToBePrinted.length(); i++) {
String x = String.valueOf(ThingToBePrinted.charAt(i));
ThingPrinted = ThingPrinted + x;
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); //Html for wrapping text
Thread.sleep(Mili); //Delay between letters
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
});
Master_B1.setFont(new Font("Tahoma", Font.PLAIN, 25));
Master_B1.setBounds(164, 385, 375, 70);
contentPane.add(Master_B1);
}
}
I would really appreciate any solution at this point, I've been troubleshooting for hours
Your problem is related to how concurrency works in Swing. One (imperfect) solution is to use a SwingWorker. You could change your action listener to this:
Master_B1.addActionListener(event -> {
SwingWorker<Object, Void> worker = new SwingWorker<Object, Void>() {
#Override
protected String doInBackground() throws InterruptedException {
for (int i = 0; i < ThingToBePrinted.length(); i++) {
ThingPrinted += ThingToBePrinted.charAt(i);
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); // Html for wrapping text
Thread.sleep(Mili); //Delay between letters
}
return null;
}
};
worker.execute();
});
Read this tutorial: Lesson: Concurrency in Swing to get a better understanding of the topic. (You might want to read up on concurrency in Java in general also, see this tutorial for example).
It is because you are updating the JLabel in the UI thread itself from the event handler. Better way is to start a new thread in the event handler and then update the JLabel from this new thread. Following is the section you need to use in your code. I have tested it, it works.
Master_B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try { // Start new thread here for updating JLabel.
new Thread() {
public void run() {
//scrolling function
for (int i = 0; i < ThingToBePrinted.length(); i++) {
String x = String.valueOf(ThingToBePrinted.charAt(i));
ThingPrinted = ThingPrinted + x;
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); //Html for wrapping text
try {
Thread.sleep(Mili); // Delay between letters
} catch (Exception e) {
}
}
}
}.start();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
});
What is the Java Swing component that would be suitable for creating a filterable list like seen below?
This type of filtering is most easily done using a single column JTable. A table has inbuilt functionality to add a RowSorter which:
..provides the basis for sorting and filtering.
See also How to Use Tables: Sorting and Filtering.
Here is an example for filtering the font family names:
On the left is a more 'list looking' component, while the right hand side shows a component that is clearly a table.
Code
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.text.Document;
import javax.swing.table.TableRowSorter;
public class FontFilter {
private JComponent ui = null;
JTextField filterText;
TableRowSorter sorter;
FontFilter(boolean listLike) {
initUI(listLike);
}
public void initUI(boolean listLike) {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
GraphicsEnvironment ge
= GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
String[][] tableData = new String[fonts.length][1];
for (int i = 0; i < fonts.length; i++) {
tableData[i][0] = fonts[i];
}
String[] header = {"Fonts"};
JTable table = new JTable(tableData, header);
if (listLike) {
Dimension d = table.getPreferredScrollableViewportSize();
table.setPreferredScrollableViewportSize(new Dimension(d.width/2,d.height));
table.setShowGrid(false);
table.setTableHeader(null);
table.setFillsViewportHeight(true);
}
ui.add(new JScrollPane(table));
sorter = new TableRowSorter(table.getModel());
table.setRowSorter(sorter);
filterText = new JTextField(10);
ui.add(filterText, BorderLayout.PAGE_START);
Document doc = filterText.getDocument();
DocumentListener listener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
newFilter();
}
#Override
public void removeUpdate(DocumentEvent e) {
newFilter();
}
#Override
public void changedUpdate(DocumentEvent e) {
newFilter();
}
};
doc.addDocumentListener(listener);
}
private void newFilter() {
RowFilter rf = null;
//If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(), 0);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FontFilter o1 = new FontFilter(true);
FontFilter o2 = new FontFilter(false);
JFrame f = new JFrame("Font Filter");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(o1.getUI(), BorderLayout.LINE_START);
f.add(o2.getUI(), BorderLayout.CENTER);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If you want or have to use only standard Swing components then the method described by #AndrewThompson is the way to go.
But if you are able to use third-party libraries then a good alternative is JXList component included in SwingX project. This component is a JList extension and provides the ability to sort and filter its content plus other interesting features (check SwingLabs Demos).
The following snippet is the basis to make it work:
JXList list = new JXList(listModel);
list.setAutoCreateRowSorter(true);
This is enough to create and install a RowSorter<ListModel, Integer> instance as the list's row sorter which can be retrieved by calling getRowSorter() method. The actual object returned by this method is a ListSortController which inherits from DefaultRowSorter and also implements the non-standard SortController interface.
It is important to keep this class hierarchy in mind because it's possible to supply a RowFilter in different ways. All the following alternatives assume the row sorter is auto-created.
Note: IMO the first method is the preferred one because we can delegate the dirty work of down-casting the row sorter to supply a row filter to the component.
1. Set the row filter directly on the list
list.setRowFilter(rowFilter);
This is a convenience method to set the row filter. However it is required by contract that the actual list's row sorter be a SortController compliant instance. Otherwise the setRowFilter(...) call has no effect.
2. Cast the row sorter as SortController
SortController<ListModel> sortController
= (SortController<ListModel>)list.getRowSorter();
sortController.setRowFilter(rowFilter);
The SortController interface provides a method to set the row filter which is used to by-pass the row filter in the method # 1.
3. Cast the row sorter as DefaultRowSorter
DefaultRowSorter<ListModel, Integer> sorter
= (DefaultRowSorter<ListModel, Integer>)list.getRowSorter();
sorter.setRowFilter(rowFilter);
This method is the same than when we are working with JTable.
Example
Here is a simple demo about filtering with JXList. Once again please check SingLabs Demos for better examples.
import java.awt.BorderLayout;
import java.awt.GraphicsEnvironment;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.jdesktop.swingx.JXList;
public class FilterListDemo {
private JXList list;
private void createAndShowGui() {
final JTextField filterText = new JTextField(30);
filterText.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
FilterListDemo.this.createFilter(filterText.getText(), false);
}
#Override
public void removeUpdate(DocumentEvent e) {
FilterListDemo.this.createFilter(filterText.getText(), false);
}
#Override
public void changedUpdate(DocumentEvent e) {
FilterListDemo.this.createFilter(filterText.getText(), false);
}
});
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
list = new JXList(fonts);
list.setAutoCreateRowSorter(true);
JPanel content = new JPanel(new BorderLayout(8,8));
content.add(filterText, BorderLayout.PAGE_START);
content.add(new JScrollPane(list), BorderLayout.CENTER);
content.setBorder(BorderFactory.createEmptyBorder(8,8,8,8));
JFrame frame = new JFrame("Filter List Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(content);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createFilter(String text, final boolean caseSensitive) {
final String filterText = caseSensitive ? text : text.toUpperCase();
list.setRowFilter(new RowFilter<ListModel, Integer>() {
#Override
public boolean include(RowFilter.Entry<? extends ListModel
, ? extends Integer> entry) {
String entryValue = caseSensitive
? entry.getStringValue(0)
: entry.getStringValue(0).toUpperCase();
return filterText == null
|| filterText.trim().isEmpty()
|| entryValue.contains(filterText.trim());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FilterListDemo().createAndShowGui();
}
});
}
}
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");
}
}
I am attempting to print to my JTextArea from another class. I have the class ActivityLogger call method Alert inside of my main class Risk_Mgnt_Manager which is where the JTextArea is located. I am able to pass the string into this method and print to counsel but it won't append or setText to the JTextArea. What am I missing?
My goal is to have different classes send messages to the class ActivityLogger which in turn sends it to the JTextArea.
Any examples are appreciated and Thank you in advance.
Main class
package risk_mgnt_manager;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class Risk_Mgnt_Manager extends JFrame{
boolean begin = false;
String message = null;
JTextArea text = new JTextArea();
JButton Start = new JButton("Start");//exit program button
JButton End = new JButton("End");//Ok button executes message creation
JButton Exit = new JButton("Exit Program");
public void Alert(String a){
System.out.println(a); // This is printing correctly
text.append(a + "\n"); // why won't this display the string?
}
public Risk_Mgnt_Manager(){
text.setEditable(false);
text.setWrapStyleWord(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
setLayout(new GridLayout(2, 3, 5, 5)); //LayoutManager Setup
JPanel myPanel = new JPanel(new GridLayout(3,0));
//JPanel myPanel2 = new JPanel(new GridLayout(1, 1));
//JPanel myPanel3 = new JPanel(new GridLayout(1, 1));
JPanel myPanel4 = new JPanel(new GridLayout(1, 1));
myPanel.add(new JLabel("Start Automated Processes: "));
myPanel.add(Start);
myPanel.add(new JLabel("End Automated Processes: "));
myPanel.add(End);
myPanel.add(new JLabel(" "));
myPanel.add(Exit);
myPanel4.add(text);
Start.addActionListener(new startActions());//Listener for button 1
End.addActionListener(new stopActions());//Listener for button 2
Exit.addActionListener(new Quit());//Listener for button 2
add(myPanel);
//add(myPanel2);
//add(myPanel3);
add(myPanel4);
}
public void StartAutomation(boolean start) throws SAXException, ParserConfigurationException, IOException, SQLException{
//calls test class
Test t = new Test();
t.mainTest(begin);
//ignore these classes
// Step one import settlement data from FIX 1 settlement tables
ImportSettles tbl = new ImportSettles();
//tbl.DataTransfer(begin);
// Step two import Real-Time price data from t_span_price on FIX 1
ImportSpanPrice tbl2 = new ImportSpanPrice();
//tbl2.DataTransfer1(begin);
// Step three import from xml file
ImportTradeData tbl3 = new ImportTradeData();
//tbl3.parseXML(begin);
// Step four not used as of 11/26/2013
ImportFirmRpt tbl4 = new ImportFirmRpt();
// Step five import poew.csv file
ImportPOEW tbl5 = new ImportPOEW();
//tbl5.csvImportPOEW(begin);
// Step six import paycollect.csv file
ImportPaycollect tbl6 = new ImportPaycollect();
//tbl6.csvImportPaycollect(begin);
// Step seven import data from RISK 1
ImportSecDeposit tbl7 = new ImportSecDeposit();
//tbl7.DataTransfer2(begin);
// Step 8 import FCM financial info, WinJammer not used as of 11/26/2013
ImportFCM tbl8 = new ImportFCM();
// Step nine import CGM_post.csv file
ImportCGMPost tbl9 = new ImportCGMPost();
//tbl9.csvImportCGMPost(begin);
// Step ten import RM_Intraday_paycollect.csv
ImportIntraday tbl10 = new ImportIntraday();
//tbl10.csvImportIntra(begin);
}
private static void ProjectFrame(){
Risk_Mgnt_Manager projectFrame = new Risk_Mgnt_Manager();
projectFrame.setSize(500, 300); //JFrame size set
projectFrame.setLocationRelativeTo(null); //JFrame centered to center of screen
projectFrame.setTitle("Automation Control"); //JFrame Title
projectFrame.setVisible(true);//JFrame is visible upon start of program
projectFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
ProjectFrame();
}
static class Quit implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
System.exit(0);
}
}
public class startActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = true;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class stopActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = false;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Test class
package risk_mgnt_manager;
import java.util.Date;
/**
*
* #author bgilbert
*/
public class Test {
public void mainTest(boolean a){
ActivityLogger act = new ActivityLogger();
act.logger("Testing message reporting " + new Date(), 1, true);
}
}
ActivityLogger class
package risk_mgnt_manager;
/**
*
* #author MLaMeyer
*/
public class ActivityLogger{
private String message;
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
}
Your program prints out to the other class, just not in the object displayed:
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
When you create a new Risk_Mgnt_Manager, you do just that, create a new completely unique Risk_Mgnt_Manager object, one that is not displayed. Printing to it will have no effect on the displayed one.
A the solution is to pass in a reference to your logger class to the actual displayed Risk_Mgnt_Manager object.
public class ActivityLogger{
private String message;
private Risk_Mgnt_Manager m; // ***** added
public ActivityLogger(Risk_Mgnt_Manager m) {
this.m = m; // ****** added
}
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
// Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
m.Alert(message);
}
});
}
}
Whatever you do, don't attempt to solve this my making anything static as that road will lead to misery.
You need to update the UI in separate Thread, I mean UI related operations should run on the Event dispatch thread. Add constructor in your ActivityLogger class like Hovercraft's solution then try,
SwingUtilities.invokeLater(new Runnable() {
public void run() {
text.append(a+"\n");
}
});
First of all make the frame visible in your constructor.
public Risk_Mgnt_Manager(){
setVisible(true);
}
Then as per solution by Hovercraft pass by reference.
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.