Updating multiple GUI classes
Hi,
I'm wondering how it would be possible to have a class (class1) used for information, then two new classes (class2, class3) both used to display the same information from class1 in two seperate ways.
So far I've put a variable in class2 and again in class3 that can be initialised to class1 at construction, so then all I do is just use class1's get() methods to get the information to display in class2 and class3.
The problem is, I'm not sure how to make class2 and class3 update themselves every time the information in class1 changes.
The GUI classes should register with the data class as change listeners. You'd typically create your own subclass of EventListener and EventObject. Add addXXXListner(), removeXXXListener and fireXXXListener methods to the data object. When the data changes the data objects first all the registered listeners, which can then query the new data in the normal way.
Similar Messages
-
Updating a GUI component from a runnable class that doesn't know that GUI
Hi. I have a problem that I think isn't solvable in an elegant way, but I'd like to get confirmation before I do it the dirty way.
My application allows the user to save (and load) his work in sessions files. I implemented this by a serializable class "Session" that basically stores all the information that the user created or the settings he made in its member variables.
Now, I obviously want the session files created by this to be as small as possible and therefore I made sure that no GUI components are stored in this class.
When the user has made all his settings, he can basically "run" his project, which may last for a long time (minutes, hours or days, depending on what the user wants to do....). Therefore I need to update the GUI with information on the progress/outcome of the running project. This is not just a matter of updating one single GUI component, but of a dynamic number of different internal frames and panels. So I'd need a reference to a GUI component that knows all these subcomponents to run a method that does the update work.
How do I do that? I cannot pass the reference to that component through the method's argument that "runs" the project, because that needs to be a seperate thread, meaning that the method is just the run() method of that thread which has no arguments (which I cannot modify if I'm not mistaken).
So the only thing I can think of is passing the reference through the constructor of the runnable class (which in turn must be stored in the session because it contains critical information on the user's work). As a result, all components that need to be incorporated in that updating process would be part of the session and go into the exported file, which is exactly what I wanted to avoid.
I hope this description makes sense...
Thanks in advance!Thanks for the quick answer! Though to be honest I am not sure how it relates to my question. Which is probably my fault rather than yours :-)
But sometimes all it takes me to solve my problem is posting it to a forum and reading it through again :)
Now I wrote a seperate class "Runner" that extends thread and has the gui components as members (passed through its constructor). I create and start() that object in the run method of the original runnable class (which isn't runnable anymore) so I can pass the gui component reference through that run method's argument.
Not sure if this is elegant, but at least it allows me to avoid saving gui components to the session file :-)
I am realizing that probably this post shouldn't have gone into the swing forum... -
In the code below, how do I update the GUI with the random number that is generated? I cannot use a static method because I may need multiple instances of the GUI and each instance needs to have it's own unique output displayed. I can't combine the two class together because I want to serialize the Controller but NOT the GUI.
public class Controller{
public void makeNums(){
// creates random numbers at random times
public class Gui{
private Controller control;
public Gui(Controller control){
this.control = control;
openGui(); // this method creates all the components of the GUI
control.makeNums();
}How can the Controller update the GUI after the random number has been generated?SquareBox wrote:
DrClap wrote:
It's pretty trivial:Thanks. I will give that a try. Just one final question here. Is it dangerous to use "this" in the Constructor? Thanks so much for the tip. I will give it a try right now.It's generally a bad idea to let the "this" reference escape from the c'tor before the object is fully initialized. You don't want some other class or method to be using your object before it's in a fully valid state. In this case, however, the object in question has already been fully initialized before you leak the reference, so you should be fine.
Having said that, however, I'm not 100% sure that there's not a potential for memory inconsistency in a multithreaded context. I think in this particular case you're okay, but another approach might be to have an external method create the Gui and then call control.setGui(gui). -
How do you update multiple items in a JSP that are only checked...
I have list of items in my jsp pages and that are being generated by the following code
and I want to be able to update multiple records that have a checkbox checked:
I have a method to update the status and employee name that uses hibernate that takes the taskID
as a paratmeter to update associated status and comments, but my issue is how to do it with multiple records:
private void updateTaskList(Long taskId, String status, String comments) {
TaskList taskList = (TaskList) HibernateUtil.getSessionFactory()
.getCurrentSession().load(TaskList.class, personId);
taskList.setStatus(status);
taskList.setComment(comments);
HibernateUtil.getSessionFactory().getCurrentSession().update(taskList);
HibernateUtil.getSessionFactory().getCurrentSession().save(taskList);
<table border="0" cellpadding="2" cellspacing="2" width="98%" class="border">
<tr align="left">
<th></th>
<th>Employee Name</th>
<th>Status</th>
<th>Comment</th>
</tr>
<%
List result = (List) request.getAttribute("result");
%>
<%
for (Iterator itr=searchresult.iterator(); itr.hasNext(); )
com.dao.hibernate.TaskList taskList = (com.dao.hibernate.TaskList)itr.next();
%>
<tr>
<td> <input type="checkbox" name="taskID" value=""> </td>
<td>
<%=taskList.empName()%> </td>
<td>
<select value="Status">
<option value="<%=taskList.getStatus()%>"><%=taskList.getStatus()%></option>
<option value="New">New</option>
<option value="Fixed">Fixed</option>
<option value="Closed">Closed</option>
</select>
</td>
<td>
<input type="text" name="Comments" MAXLENGTH="20" size="20"
value="<%=taskList.getComments()%>"></td>
</tr>
<%}%>
_________________________________________________________________org.hibernate.exception.GenericJDBCException: could not load an entity: [com.dao.hibernate.WorkList#2486]
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:91)
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:79)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
org.hibernate.loader.Loader.loadEntity(Loader.java:1799)
org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:93)
org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:81)
org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:161)
org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:87)
org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:889)
org.hibernate.impl.SessionImpl.load(SessionImpl.java:808)
org.hibernate.impl.SessionImpl.load(SessionImpl.java:801)
com.web.UpdateWorkListAction.execute(Unknown Source)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
before I was running a single update as below and it worked fine:
session.beginTransaction();
int taskId = Integer.parseInt(request.getParameter("taskId"));
String action_taken = request.getParameter("action_taken");
WorkListErrors worklistErrors
= (WorkListErrors) session.load(WorkListErrors.class, new Integer(taskId));
worklistErrors.setAction_taken(action_taken);
session.update(worklistErrors);
session.save(worklistErrors);
session.getTransaction().commit();
but when I try an an update on multiple records it does work when I have a check box checked :
session.beginTransaction();
int taskId = Integer.parseInt(request.getParameter("taskId"));
String action_taken = request.getParameter("action_taken");
WorkListErrors worklistErrors
= (WorkListErrors) session.load(WorkListErrors.class, new Integer(taskId));
worklistErrors.setAction_taken(action_taken);
session.update(worklistErrors);
session.save(worklistErrors);
session.getTransaction().commit();
session.beginTransaction();
String[] tickedTaskId = request.getParameterValues("tickedTaskId");
String[] taskId = request.getParameterValues("taskId");
String[] action_taken = request.getParameterValues("action_taken");
for(int i=0; i<tickedTaskId.length; i++) {
for(int j = 0; j < taskId.length; j++) {
if(tickedTaskId.equals(taskId[j])) {
WorkListErrors worklistErrors
= (WorkListErrors) session.load(WorkListErrors.class, tickedTaskId[i]);
worklistErrors.setAction_taken(action_taken[j]);
session.update(worklistErrors);
session.save(worklistErrors);
session.getTransaction().commit();
/*Close session */
session.close(); -
I want to update multiple record in database which is based on condition
hi all,
I am using Jdev 11.1.2.1.0
I have one table named(Pay_apply_det) in this table i want to update one column named(Hierarchy) every time and according to change i want to update or i want to maintain my log table named(pay_apply_appr).It based on level wise approval when the lowest person approve the record show on next level but if the second
level person back it will be show only previous level hierarchy.And when the final approval happen the Posting_tag column of pay_apply_det will be updated too with hierarchy column.
i have drag pay_apply_det's data control as a table in my .jsf page and add one column approve status in UI .in the approve status i used radio group which return A for approve B for back R for reject through value binding i make it get or set method in it baking bean.
in backing bean class i have written code
public void approveMethod(ActionEvent actionEvent) {
ViewObject v9=new UtilClass().getView("PayApplyDetView1Iterator");
int h5=0;
Row rw9= v9.getCurrentRow();
String x=(String) rw9.getAttribute("RemarkNew1");
System.out.println(x);
String z=getR2();
System.out.println(z);
if(( z.equals("R") || z.equals("B") )&& x==null)
FacesMessage fm1 = new FacesMessage("Plz Insert Remark Feild");
fm1.setSeverity(FacesMessage.SEVERITY_INFO);
FacesContext context1 = FacesContext.getCurrentInstance();
context1.addMessage(null, fm1);
else{
ADFContext.getCurrent().getSessionScope().put("Radio",getR2().toString());
String LogValue=(String)ADFContext.getCurrent().getSessionScope().get("logid");
ViewObject voH=new UtilClass().getView("PayEmpTaskDeptView1Iterator");
voH.setWhereClause("task_cd='449' and subtask_cd='01' and empcd='"+LogValue+"'");
voH.executeQuery();
Row row1= voH.first();
int h1=(Integer)row1.getAttribute("Hierarchy");
System.out.println("Login Person Hierarchy on save button press.."+h1);
ViewObject vo9=new UtilClass().getView("PayApplyDetView1Iterator");
Row row9= vo9.getCurrentRow();
if(getR2().equals("A")&& h1!=1)
row9.setAttribute ("ApprHier",h1);
row9.setAttribute("IsClaimed","N");
row9.setAttribute("ClaimedBy",null);
row9.setAttribute("ClaimedOn", null);
else if(getR2().equals("B") ) {
ViewObject voO=new UtilClass().getView("LoHierViewObj1Iterator");
voO.setNamedWhereClauseParam("QHVO", LogValue);
Row rowO = voO.first();
h5=(Integer)rowO.getAttribute("LPrehier");
System.out.println("Back lower hier..."+h5);
row9.setAttribute ("ApprHier",h5);
row9.setAttribute("IsClaimed","N");
row9.setAttribute("ClaimedBy",null);
row9.setAttribute("ClaimedOn", null);
else if((h1==1) &&(getR2().equals("A")) )
row9.setAttribute ("PostingTag","Y");
row9. setAttribute ("ApprHier", h1);
row9.setAttribute("IsClaimed","N");
row9.setAttribute("ClaimedBy",null);
row9.setAttribute("ClaimedOn", null);
else if(getR2().equals("R"))
row9.setAttribute ("ApprHier",-1);
row9.setAttribute("IsClaimed","N");
row9.setAttribute("ClaimedBy",null);
row9.setAttribute("ClaimedOn", null);
BindingContext BC=BindingContext.getCurrent();
BindingContainer ac=BC.getCurrentBindingsEntry();
OperationBinding ob=ac.getOperationBinding("Commit");
ob.execute();
vo9.executeQuery();
FacesMessage fm = new FacesMessage("Your Data Successfully Commited..");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, fm);
}here i put my approve status radio value in session variable because i also want to update my pay_apply_appr table which code i written in pay_apply_det IMPL class.
Every thing is running well when i update single record but when i want to update multiple record then my current row only updated in pay_apply_det but log table( pay_apply_appr) created for all record.
so is there any solution plz help me.
thanks
RAFATHi Rafat,
If you are able to insert into, all you need to do is iterate through the rows. For this , before the first IF condition
if(getR2().equals("A")&& h1!=1)Get the row count using int numRows =vo9.getRowCount(); , and then write it before the IF condition
if (int i=0;i<numRows;i++} After
row9.setAttribute("ClaimedOn", null);
}write vo9.next(); to iterate to next row,
Hope this will work.
Nigel. -
Update multiple rows in a dynamic table Dreamweaver CS5.5
hello there
i want to update multiple rows which comes from a dynamic table in Dreamweaver CS5 (a loop in php) here is my Mysql table :
sql code
CREATE TABLE `register`.`s_lessons` (
`lid` int( 5 ) NOT NULL ,
`sid` int( 9 ) NOT NULL ,
`term` int( 5 ) NOT NULL ,
`tid` int( 5 ) NOT NULL ,
`point` double NOT NULL DEFAULT '0',
PRIMARY KEY ( `lid` , `sid` , `term` ) ,
KEY `tid` ( `tid` ) ,
KEY `point` ( `point` )
) ENGINE = MYISAM DEFAULT CHARSET = utf8 COLLATE = utf8_persian_ci;
and this is my page source code:
php file
<?php require_once('../Connections/register.php'); ?>
<?php
session_start();
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
return $theValue;
$colname1_rs1 = "-1";
if (isset($_GET['term'])) {
$colname1_rs1 = $_GET['term'];
$colname_rs1 = "-1";
if (isset($_GET['lid'])) {
$colname_rs1 = $_GET['lid'];
$colname2_rs1 = "-1";
if (isset($_SESSION['tid'])) {
$colname2_rs1 = $_SESSION['tid'];
mysql_select_db($database_register, $register);
$query_rs1 = sprintf("SELECT s_lessons.sid, s_lessons.lid, s_lessons.term, s_lessons.tid, s_lessons.point FROM s_lessons WHERE s_lessons.lid = %s AND s_lessons.term = %s AND s_lessons.tid = %s", GetSQLValueString($colname_rs1, "int"),GetSQLValueString($colname1_rs1, "int"),GetSQLValueString($colname2_rs1, "int"));
$rs1 = mysql_query($query_rs1, $register) or die(mysql_error());
$row_rs1 = mysql_fetch_assoc($rs1);
$totalRows_rs1 = mysql_num_rows($rs1);
$count=mysql_num_rows($rs1);
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
for ($j = 0, $len = count($_POST['lid']); $j < $len; $j++) {
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE s_lessons SET point=%s WHERE tid=%s, lid=%s, sid=%s, term=%s",
GetSQLValueString($_POST['point'] [$j], "double"),
GetSQLValueString($_SESSION['tid'], "int"),
GetSQLValueString($_POST['lid'] [$j], "int"),
GetSQLValueString($_POST['sid'] [$j], "int"),
GetSQLValueString($_POST['term'] [$j], "int"));
mysql_select_db($database_register, $register);
$Result1 = mysql_query($updateSQL, $register) or die(mysql_error());
$updateGoTo = "student_lists.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
header(sprintf("Location: %s", $updateGoTo));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>r</title>
<link href="styles/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="styles/in_styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrapper">
<div id="header-wrapper">
</div>
<!-- end #header -->
<div id="page">
<div id="page-bgtop">
<div id="page-bgbtm">
<div id="content">
<div class="post">
<div style="clear: both;">
<form name="form1" id="form1" method="post" action="<?php echo $editFormAction; ?>">
<table border="1" align="center">
<tr>
<th>Student ID</th>
<th>Lesson ID</th>
<th>Semester</th>
<th>Point</th>
</tr>
<?php do { ?>
<tr>
<td class="data"><label for="sid[]"></label>
<input name="sid[]" type="text" id="sid[]" value="<?php echo $row_rs1['sid']; ?>" size="9" readonly="readonly" /></td>
<td class="data"><label for="lid[]"></label>
<input name="lid[]" type="text" id="lid[]" value="<?php echo $row_rs1['lid']; ?>" size="5" readonly="readonly" /></td>
<td class="data"><label for="term[]"></label>
<input name="term[]" type="text" id="term[]" value="<?php echo $row_rs1['term']; ?>" size="4" readonly="readonly" /></td>
<td><label for="point[]"></label>
<input name="point[]" type="text" id="point[]" value="<?php echo $row_rs1['point']; ?>" size="4" />
</tr>
<?php } while ($row_rs1 = mysql_fetch_assoc($rs1)); ?>
</table>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="hidden" name="MM_update" value="form1" />
</p>
</form>
</div>
</div>
<div style="clear: both;">
</div>
</div>
<!-- end #content -->
<!-- end #sidebar -->
<div style="clear: both;"> </div>
</div>
</div>
</div>
<!-- end #page -->
</div>
<!-- end #footer -->
</body>
</html>
<?php
mysql_free_result($rs1);
?>
All i want is that when users click on SUBMIT button values of point column in s_lessons(database table) be updated by new entries from user.
i did my best and result with that code is :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' lid=888, sid=860935422, term=902' at line 1
I would appreciate any idea.
with prior thanksGo to the Row Properties, and in the Visibility tab, you have "Show or hide based on an expression". You can use this to write an expression that resolves to true if the row should be hidden, false otherwise.
Additionally, in the Matrix properties you should take a look at the filters section, perhaps you can achieve what you wish to achieve through there by removing the unnecessary rows instead of just hiding them.
It's only so much I can help you with the limited information. If you require further help, please provide us with more information such as what data are you displaying, what's the criteria to hiding rows, etc...
Regards
Andrew Borg Cardona -
How do you monitor a background thread and update the GUI
Hello,
I have a thread which makes its output available on PipedInputStreams. I should like to have other threads monitor the input streams and update a JTextArea embedded in a JScrollPane using the append() method.
According to the Swing tutorial, the JTextArea must be updated on the Event Dispatch Thread. When I use SwingUtilities.invokeLater () to run my monitor threads, the component is not redrawn until the thread exits, so you don't see the progression. If I add a paint () method, the output is choppy and the scrollbar doesn't appear until the thread exits.
Ironically, if I create and start new threads instead of using invokeLater(), I get the desired result.
What is the correct architecture to accomplish my goal without violating Swing rules?
Thanks,
Brad
Code follows:
import java.lang.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
public class SystemCommand implements Runnable
private String[] command;
private PipedOutputStream pipeout;
private PipedOutputStream pipeerr;
public SystemCommand ( String[] cmd )
command = cmd;
pipeout = null;
pipeerr = null;
public void run ()
exec ();
public void exec ()
// --- Local class to redirect the process input stream to a piped output stream
class OutputMonitor implements Runnable
InputStream is;
PipedOutputStream pout;
public OutputMonitor ( InputStream i, PipedOutputStream p )
is = i;
pout = p;
public void run ()
try
int inputChar;
for ( ;; )
inputChar = is.read();
if ( inputChar == -1 ) { break; }
if ( pout == null )
System.out.write ( inputChar );
else
pout.write ( inputChar );
if ( pout != null )
pout.flush ();
pout.close ();
else
System.out.flush();
catch ( Exception e ) { e.printStackTrace (); }
try
Runtime r = Runtime.getRuntime ();
Process p = r.exec ( command );
OutputMonitor out = new OutputMonitor ( p.getInputStream (), pipeout );
OutputMonitor err = new OutputMonitor ( p.getErrorStream (), pipeerr );
Thread t1 = new Thread ( out );
Thread t2 = new Thread ( err );
t1.start ();
t2.start ();
//p.waitFor ();
catch ( Exception e ) { e.printStackTrace (); }
public PipedInputStream getInputStream () throws IOException
pipeout = new PipedOutputStream ();
return new PipedInputStream ( pipeout );
public PipedInputStream getErrorStream () throws IOException
pipeerr = new PipedOutputStream ();
return new PipedInputStream ( pipeerr );
public void execInThread ()
Thread t = new Thread ( this );
t.start ();
public static JPanel getContentPane ( JTextArea ta )
JPanel p = new JPanel ( new BorderLayout () );
JPanel bottom = new JPanel ( new FlowLayout () );
JButton button = new JButton ( "Exit" );
button.addActionListener ( new ActionListener ( )
public void actionPerformed ( ActionEvent e )
System.exit ( 0 );
bottom.add ( button );
p.add ( new JScrollPane ( ta ), BorderLayout.CENTER );
p.add ( bottom, BorderLayout.SOUTH );
p.setPreferredSize ( new Dimension ( 640,480 ) );
return p;
public static void main ( String[] argv )
// --- Local class to run on the event dispatch thread to update the Swing GUI
class GuiUpdate implements Runnable
private PipedInputStream pin;
private PipedInputStream perr;
private JTextArea outputArea;
GuiUpdate ( JTextArea textArea, PipedInputStream in )
pin = in;
outputArea = textArea;
public void run ()
try
// --- Reads whole file before displaying...takes too long
//outputArea.read ( new InputStreamReader ( pin ), null );
BufferedReader r = new BufferedReader ( new InputStreamReader ( pin ) );
String line;
for ( ;; )
line = r.readLine ();
if ( line == null ) { break; }
outputArea.append ( line + "\n" );
// outputArea.paint ( outputArea.getGraphics());
catch ( Exception e ) { e.printStackTrace (); }
// --- Create and realize the GUI
JFrame f = new JFrame ( "Output Capture" );
f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
JTextArea textOutput = new JTextArea ();
f.getContentPane().add ( getContentPane ( textOutput ) );
f.pack();
f.show ();
// --- Start the command and capture the output in the scrollable text area
try
// --- Create the command and setup the pipes
SystemCommand s = new SystemCommand ( argv );
PipedInputStream stdout_pipe = s.getInputStream ();
PipedInputStream stderr_pipe = s.getErrorStream ();
// --- Launch
s.execInThread ( );
//s.exec ();
// --- Watch the results
SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stdout_pipe ) );
SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stderr_pipe ) );
//Thread t1 = new Thread ( new GuiUpdate ( textOutput, stdout_pipe ) );
//Thread t2 = new Thread ( new GuiUpdate ( textOutput, stderr_pipe ) );
//t1.start ();
//t2.start ();
catch ( Exception e ) { e.printStackTrace (); }
Thanks for pointing out the SwingWorker class. I didn't use it directly, but the documentation gave me some ideas that helped.
Instead of using invokeLater on the long-running pipe-reader object, I run it on a normal thread and let it consume the output from the background thread that is running the system command. Inside the reader thread I create a tiny Runnable object for each line that is read from the pipe, and queue that object with invokeLater (), then yield() the reader thread.
Seems like a lot of runnable objects, but it works ok. -
Listen for events in another Gui class
Most of the GUIs I have written to date have consisted of either a single class or multiple self-contained classes - mainly extensions of JPanel with JButtons etc to perform certain tasks.
Now I want to be able to click a JButton in one class which will invoke a method in another.
The code is too lengthy to post here but this is the general layout:
JFrame Simulation_GUI contains a JPanel (panelMain) which is set as the content pane
panelMain contains two GUI classes which extend JPanel;
buttonPane > contains a number of JButtons, including the one I want to click
loadingPane > contains the method (which takes a Hastable as an argument) I want to run
All three panels are declared in the main class which extends JFrame, so I know that from there I can simply call;
loadingPanel.runLoads(htData); but how do I do this from the JButton on the buttonPane.
Any assistance greatly appreciated as I have little enough hair at the moment and can't afford to tear much more out.
Thanks in advanceClass GUI1 {
//Display all the buttons.
public void init() {
Button.addActionListener(new
ener(new SomeClass(this));
Class SomeClass implements ActionListener {
GUI1 gui = null;
SomeClass(GUI1 gui) {
this.gui = gui;
public void actionPerformed(ActionEvent e) {
//Do all your process here
gui.setTable(table); //table would be ur
ould be ur hashtable
}Cheers
-PThis didn't fully answer my question but did two things:
1. Told me that it is at least possible and it is just me having a senior moment,
2. Sent me on the right road to finding a solution
With additional help from the following post I have sorted my problem. Basically I had to centrallise the event handling into a different class. This was instantiated by the main GUI class and passed to the other GUI components as an argument.
http://forum.java.sun.com/thread.jspa?threadID=576012&messageID=2881969
Simple when you know how...!
prashanth_kuppur - have some Duke Dollars on me and thanks for the poke in the right direction. -
Making middle teir accessible to all gui class objects.
I'm designing a user interface at the moment for a
3 tier application. I've got a good knowledge of Java
but have never written a complicated gui with Swing.....
User Interface (GUI) --> Business Logic (JDBC classes) --> MYSQL DB
As the diagram shows, I want to keep the business logic separate
from the user interface.
My problem is that I'm not sure the best way to give all the GUI's action listeners
access to the business logic object's methods which will call and return information
from the database to the UI.
Had there just been one UI class it would be easy to create an instance of the
business logic class from the UI class, but
the GUI is made up of many class objects with larger componets being made
up of several smaller component classes and so on. What I guess I'm unsure of
is what the standard practice is in this situation. Is a case of getting the GUI creation class
to create an instance of the business logic object and then pass it down through the many
GUI class constructors so that each GUI class object can reference it?
You thoughts are appreciated, many thanks,
Andrew.The commom practice here is to use some design patterns.
The ones you need are Proxy and DTO (Data Transfer Object).
The reasons behind using a proxy patters are that your DB could
change location, and you could have multiple GUI's using the
same DB
You will have several DTO's which will contain the data from your
database. These DTO's are used to group data common to one use
case, so that in order to complete the use case, you only need to
remotely access the DB once. These Dto's are regular Java objects
with just getter and setter methods.
Your GUI uses a Proxy object to request a DTO.
someting like... you need some data to fill a form or a table?
GUIProxy proxy = ProxyServices.getGUIProxy();
FormDataDto dto = proxy.getFormData();
JTexField nameField = new JTextField();
nameField.setText(dto.getCustomerName());
etc...
Notice how your GUI has no idea where the data lives,
how its stored, etc. It just knows how to request it. -
Support of multiple GUI clients
Hi,
Currently, we have an application which partially supports multiple
GUI clients. When a GUI first launches, it will pop up a dialog box
to select "Read" or "Read/Write" access mode. Once "Read/Write"
is selected, others can only select "Read" mode until "Read/Write" mode is released. There is a timer to automatically release the mode, if "Read/Write" is holding up for too long.
Now., we have to fully support multiple clients. The "Read" and "Read/
Write" modes have to be removed. That means, mutliple clients can
send update requests at the same time. Does anyone have ideas how
to support multiple clients? Is there any "models" out there where
I can based on to support it?
Thanks,
PinMark, we came out with 8.1.7.4.0 precisely for the reasons you have stated. There is no longer a Windows NT Oracle Service For MTS per database. The logic to enlist Oracle connections in MTS transactions, and the logic to subsequently commit/abort these transactions is fully contained within the middle-tier dlls i.e. ORAMTS.DLL. This removes the single point-of-failure in pre 8.1.7.4.0 versions, and also makes the solution more scalable.
-
What is the best way to get another object's method to update my GUI?
package stuff;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame{
private static JButton ProcessButton = new JButton();
private static JLabel jLabel2 = new JLabel();
public static void main( String args []){
Test f = new Test();
f.setSize(500,500);
Container c = f.getContentPane();
ProcessButton.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
jLabel2.setText("Connecting to DB");
//Connection connection = Tools.setUpConnectionToDB(url,userName,pwd);
c.add(ProcessButton, BorderLayout.NORTH);
jLabel2.setText("My Label");
c.add(jLabel2, BorderLayout.SOUTH);
f.setVisible(true);
{\code]
The method setUpConnectionToDB can take 1 - 10 mins to complete. By this time a user will prob have quit my app thinking
it's crashed because it doesn't update the GUI with a progress status. :(
What is the best way to get this method to update the GUI of the app which calls it?
Something like Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
ie this being a reference to the GUI's JFrame is what I'm trying to use?A handy class to know about but not really what I'm after.
I need the method call
Tools.setUpConnectionToDB(url,userName,pwd);
to be able to update a component ( The JLabel ) on the GUI
Connection connection = Tools.setUpConnectionToDB(url,userName,pwd, this);
[\code]
method defn:public static Connection setUpConnectionToDB( String url, String user, String pwd, JFrame f ){
//Why doesn't this code below modify the GUI on the calling App?
f.jLabel2.setText("Setting UP DB Connection");
f.repaint();
Connection c = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection(url,user,pwd);
catch(ClassNotFoundException e){
JOptionPane.showMessageDialog(null , "Error loading DB driver");
System.exit(0);
catch(Exception e){
JOptionPane.showMessageDialog(null , "Error connecting to DB, check config file");
System.exit(0);
return c;
}[\code] -
How to update multiple records checked by check box
I have list of items in my jsp pages and that are being generated by the following code
and I want to be able to update multiple records that have a checkbox checked:
I have a method to update the status and employee name that uses hibernate that takes the taskID
as a paratmeter to update associated status and comments, but my issue is how to do it with multiple records:
private void updateTaskList(Long taskId, String status, String comments) {
TaskList taskList = (TaskList) HibernateUtil.getSessionFactory()
.getCurrentSession().load(TaskList.class, personId);
taskList.setStatus(status);
taskList.setComment(comments);
HibernateUtil.getSessionFactory().getCurrentSession().update(taskList);
HibernateUtil.getSessionFactory().getCurrentSession().save(taskList);
<table border="0" cellpadding="2" cellspacing="2" width="98%" class="border">
<tr align="left">
<th></th>
<th>Employee Name</th>
<th>Status</th>
<th>Comment</th>
</tr>
<%
List result = (List) request.getAttribute("result");
%>
<%
for (Iterator itr=searchresult.iterator(); itr.hasNext(); )
com.dao.hibernate.TaskList taskList = (com.dao.hibernate.TaskList)itr.next();
%>
<tr>
<td> <input type="checkbox" name="taskID" value=""> </td>
<td>
<%=taskList.empName()%> </td>
<td>
<select value="Status">
<option value="<%=taskList.getStatus()%>"><%=taskList.getStatus()%></option>
<option value="New">New</option>
<option value="Fixed">Fixed</option>
<option value="Closed">Closed</option>
</select>
</td>
<td>
<input type="text" name="Comments" MAXLENGTH="20" size="20"
value="<%=taskList.getComments()%>"></td>
</tr>
<%}%>
_________________________________________________________________I solved it by making changes in the occurrence parameter of data type ...:-)
-
Update multiple records on one page php/mysql
Hi folks,
I am trying to adapt a page to offer the option to update multiple records on one page.
The intention is to edit FAQ categories which are contained in a table with just two fields - the category and an id.
The page lists each categories in a form with a submit button which is then repeated for each record in the recordset.
Unfortunately my plan didn't work and only the first record updates as intended.
Can anyone suggest how I can make it work?
Here's the code I have so far.
************** The Update Code *****************
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
if (!isset($mm_abort_edit) || !$mm_abort_edit) {
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
$updateSQL = sprintf("UPDATE faq_categories SET category=%s WHERE id=%s",
GetSQLValueString($_POST['category'], "text"),
GetSQLValueString($_POST['id'], "int"));
mysql_select_db($database_con_mysite, $con_mysite);
$Result1 = mysql_query($updateSQL, $con_mysite) or die(mysql_error());
$updateGoTo = "faq-category-edit.php
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
header(sprintf("Location: %s", $updateGoTo));
************** Update Code Ends *****************
************** The Form *****************
<form name="frm_editcategory" id="frm_editcategory" method="POST" action="<?php echo $editFormAction; ?>">
<?php do { ?>
<fieldset>
<input name="id" type="hidden" value="<?php echo $row_rs_faqcategory['id']; ?>" />
<input name="category" type="text" class="formrightcolumn" value="<?php echo $row_rs_faqcategory['category']; ?>" />
<input name="save" type="submit" class="submitbutton" id="save" value="save" />
</fieldset>
<input type="hidden" name="MM_update" value="form1" />
<?php } while ($row_rs_faqcategory = mysql_fetch_assoc($rs_faqcategory)); ?>
</form>
************** The Form Ends *****************
Cheers
DaveWhat does debugging tell you? What's the value of each of the variables? Did you try using regular echo statements to monitor what's going on? That's what I always do whenever I am stuck in my PHP coding.
-
Updating multiple node in a single query
Hi
Shall I update multiple nodes (which satisfies the given condition) in a single query? From the prototype we suspect that all nodes in all document are not updated in the container.
Version: BDB XML 2.4 - Fedora core 4 Linux - C++ language
Query:
replace value of node collection()/File[@Id="57565C01327A"]//Entry[@Class="Measurement" and @Id="0"]/Attribute[@Name="apDlBhUtil"]/@Value with 8'
Result:
XmlException occurred with msg 'Error: Sequence does not match type node() - the sequence contains more than one item [err:XUTY0008], <query>:1:1'
We have tried running the query in both Lazy and Eager evaluation type. Please clarify that the issue is with the query/execution type or BDB XML doesn't support this feature?
Thanks
SanthoshSanthosh,
Try:
for $i in collection()/File[@Id="57565C01327A"]//Entry[@Class="Measurement" and @Id="0"]/Attribute[@Name="apDlBhUtil"]/@Value return replace value of node $i with 8'The problem with your original is that the argument for "replace value of" needs to be a single item, not a sequence.
Regards,
George -
How to update multiple Price conditions in FM CRM_ORDER_MAINTAIN
Hi All,
need to update multiple price conditions in a contract Thru FM CRM_ORDER_MAINTAIN.
please see the piece of code that am using...
am able to update single price condition...but not able to populate 2 or more .......i,e..ADD A Condition
i,e...DATA : ls_cond TYPE prct_cond_external_input,
lt_cond TYPE prct_cond_external_input_t.
DATA : ls_con TYPE PRCT_COND_DU,
lt_con TYPE PRCT_COND_DU_TAB.
Create Condition Type
*ls_con-KNUMV = lv_header_guid.
*ls_con-KPOSN = lv_item_guid.
ls_con-stunr = '134'.
IF Y EQ 1.
ls_con-ZAEHK = '001'.
ELSE.
ls_con-ZAEHK = '002'.
*ENDIF.
*ls_con-kschl = 'ZFP1'.
**ls_cond-waers = 'CNY'.
*ls_con-kbetr = '0.00'.
*ls_con-kpein = '1'.
ls_cond-kschl = 'ZFP1'.
ls_cond-waers = 'CNY'.
ls_cond-kbetr = '0'.
ls_cond-kpein = '1'.
ls_cond-knumh = lv_item_guid .
CLEAR ls_Price_doc.
ls_Price_doc-ref_guid = lv_item_guid.
ls_Price_doc-ref_kind = 'A'.
IF Y EQ 1.
ls_Price_doc-ref_handle = '000000001'.
ELSE.
ls_Price_doc-ref_handle = '000000002'.
ENDIF.
*ls_price_doc-PRIC_COND[] = lt_cond[].
*INSERT ls_con into table ls_price_doc-PRIC_COND.
INSERT ls_cond into table ls_price_doc-COND_ADD.
INSERT ls_price_doc INTO TABLE lt_price_doc.
ls_input_fields-ref_guid = lv_item_guid.
ls_input_field_names-fieldname = 'KNUMH'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'KPOSN'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'KSCHL'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'KPEIN'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'STUNR'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'ZAEHK'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'WAERS'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
ls_input_field_names-fieldname = 'KBETR'.
INSERT ls_input_fields INTO TABLE lt_input_fields.
CLEAR ls_input_fields.
Ls_input_fields-ref_guid = lv_item_guid.
ls_input_fields-ref_kind = 'B'.
ls_input_fields-objectname = 'PRIDOC'.
*ls_input_fields-logical_key = '0001'.
ls_input_fields-field_names = lt_input_field_names.
INSERT ls_input_fields INTO TABLE lt_input_fields.
CLEAR ls_input_fields.
CLEAR ls_Price_agreement.
Clear ls_cond.
I kept this under code. loop, for item records.....
Though the internal table lt_price_doc. is holding all the records, it is updating only one record. can you any one pls guide me ,This example works fine for me. Modify it according to your needs...
Price
IF it_item-value IS NOT INITIAL.
ls_cond-kschl = 'PR00'. " add price
ls_cond-kbetr = it_item-value.
ls_cond-waers = st_head-currency.
INSERT ls_cond INTO TABLE ls_pridoc_com-cond_add.
index_2 = 1.
CLEAR: ls_cond.
ENDIF.
Discount
IF it_item-discount IS NOT INITIAL.
ls_cond-kschl = 'ZPPP'. " add discount
wa_procent_calc = it_item-discount * 10.
ls_cond-kbetr = wa_procent_calc."it_item-discount.
ls_cond-waers = '%'."st_head-currency.
INSERT ls_cond INTO TABLE ls_pridoc_com-cond_add.
index_2 = 1.
CLEAR: ls_cond, wa_procent_calc.
ENDIF.
IF index_2 = 1.
ls_pridoc_com-ref_handle = counter.
ls_pridoc_com-ref_kind = 'B'.
INSERT ls_pridoc_com INTO TABLE gt_pridoc_com.
CLEAR: index_2,ls_pridoc_com.
ENDIF.
Maybe you are looking for
-
Spinning wheel of death is killing me. Have some info that might help.
Started occurring about a week ago. It happens whether I am running several applications or just surfing internet. Seems to get progressively worse the longer I have computer on. I usually eventually have to power off. Happens regardless of which use
-
Photo Stream not Working w/ipad2 and iphone4S
Photostream has been working fine and now I am not getting photos taken with my iphone to transfer to my ipad photstream.
-
Diskpart, drive letter removal using a wildcard
I am trying to write a diskpart script to automatically set a drive letter to "F" the disk is always plugged into the same port, but anytime the computer reboots it assigns a different drive letter, but it never hands out the "F" letter to any other
-
Convert Media 100 bin into FCP 4.5?
OK, this is a long shot but here it goes. I have an old project created on a Media 100. I now work with FCP 4.5. Put simply, I need to bring two media bins created in Media 100 into my FCP system so I can redigitize the media. This would save me a lo
-
Blinoz - Write to and read from memory address
How do I write to or read from a specific memory address such as Hex 378?