Help with Dynamic GUI
I am trying to create a dynamic gui for a program that when given three names, it will make a list of matches ( wrestling ) against each other.. I got it so when you click foward once.. it brings up the specified amount of text fields.. but when i click previous, it does not pack it fully, and the buttonPanel does not go back to the minimal size, and keeps the whole frame long.
[code="face.java"]import java.awt.*;
import java.awt.Component.*;
import java.awt.event.*;
public class face extends GUIFrame implements WindowListener, ActionListener {
static TextField[] nameFields;
List howMany;
TextArea finish;
Button forward, back, startOver, print;
Panel mainPanel, buttonPanel, numberPanel, namePanel, matchesPanel;
GridBagLayout gbl;
GridBagConstraints gbc;
BorderLayout bpl, mpl;
CardLayout cl;
Choice numbers;
public face() {
super("Wrestling Order");
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
setLayout(gbl);
mainPanel = new Panel();
buttonPanel = new Panel();
bpl = new BorderLayout();
back = new Button("Previous");
back.setEnabled(false);
back.addActionListener(this);
back.setActionCommand("numOf");
buttonPanel.setLayout(bpl);
buttonPanel.add(back, BorderLayout.WEST);
forward = new Button("Forward");
forward.addActionListener(this);
forward.setActionCommand("names");
buttonPanel.add(forward, BorderLayout.EAST);
startOver = new Button("Start Over");
buttonPanel.add(startOver, BorderLayout.SOUTH);
//mainPanel
numberPanel = new Panel();
numbers = new Choice();
numbers.add("3");
numbers.add("4");
numbers.add("5");
numberPanel.setLayout(bpl);
numberPanel.add(numbers, BorderLayout.CENTER);
cl = new CardLayout();
mainPanel.setLayout(cl);
mainPanel.add("numbers", numberPanel);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(mainPanel, gbc);
add(mainPanel);
gbc.gridx = 0;
gbc.gridy = 5;
gbl.setConstraints(buttonPanel, gbc);
add(buttonPanel);
addWindowListener(this);
pack();
setVisible(true);
public Panel makeNamePanel(int numOfNames) {
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = GridBagConstraints.RELATIVE;
nameFields = new TextField[numOfNames];
Panel makePanel = new Panel();
for (int x=0; x < nameFields.length; x++) {
nameFields[x] = new TextField(20);
makePanel.add(nameFields[x]);
return makePanel;
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "names") {
namePanel = makeNamePanel(Integer.parseInt(numbers.getItem(numbers.getSelectedIndex())));
mainPanel.add("name", namePanel);
cl.next(mainPanel);
forward.setActionCommand("final");
pack();
back.setEnabled(true);
if (e.getActionCommand() == "numOf") {
cl.previous(mainPanel);
pack();
forward.setActionCommand("names");
back.setEnabled(false);
that is the face.java .. it extends GUIFrame.. which is as follows..
* GUIFrame
* An extension of Frame that uses a WindowAdapter to
* handle the WindowEvents and is centered.
import java.awt.*;
import java.awt.event.*;
public class GUIFrame extends Frame {
public GUIFrame(String title) {
super(title);
setBackground(SystemColor.control);
addWindowListener(new WindowAdapter() {
//only need to override the method needed
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
/* Centers the Frame when setVisible(true) is called */
public void setVisible(boolean visible) {
if (visible) {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((d.width - getWidth())/2,
(d.height - getHeight())/2);
super.setVisible(visible);
}If you could help me out.. Thanks..
Have you tried using some other layouts... GridBagLayout is a complicated thing to figure out... Might be easier to use some nested panels with different layouts... Particularly, look at SpringLayout.
Similar Messages
-
Help with dynamic GUI in NetBeans
Hey all,
I'm new here and was looking for help. I'm trying to create a GUI which is dynamic. I want a JPanel (I think this is the proper component) that will be dynamically populated with other modules, namely other JPanels defined as classes. This JPanel is within a JDialog. Ive been trying things like this:
myPanel.add(new myNewPanel)inside of a the index changed method but the panel is not being added. I feel like I'm doing something fundamentally wrong. Does anyone have any words of advice??
ThanksOf course JDialog has a pack() method.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting. -
Is it possible to make a search help with dynamic selection table?
Hi Experts,
Is it possible to create search helps with dynamic seletion tables means
i dont know the selection table names at the time of creation of search help.
These tables will be determined at runtime.
if yes, Please give an idea how to create and pass the table names at runtime.
Thanks
Yogesh GuptaHi Yogesh,
Create and fill your itab and show it with FM F4IF_INT_TABLE_VALUE_REQUEST
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
retfield = 'field to return from itab'
dynpprog = sy-repid
dynpnr = sy-dynnr
dynprofield = 'field on your screen to be filled'
stepl = sy-stepl
window_title = 'some text'
value_org = 'S'
TABLES
value_tab = itab
EXCEPTIONS
parameter_error = 1
no_values_found = 2
OTHERS = 3.
Darley -
Need help with Dynamic Excel File Name please.
I am try to output an excel file with dynamic date.
Here what I done.
I am using SQL 2012.
Create Execute SQL Task Connect Type: Excel
Create Data Flow Task set to DelayValidation: True
Create OLE DB Sourc
Create Data Converstion
Excel Destination
Excel Connection, Expression, select ExcelFilePath
@[User::sXLFilePath] + @[User::sFileName] + RIGHT("0" + (DT_WSTR, 2) DATEPART("DD", GETDATE()), 2)+ RIGHT("0" + (DT_WSTR, 2) DATEPART("MM", GETDATE()), 2) + RIGHT((DT_WSTR,
4) DATEPART("YYYY", GETDATE()), 2) +".csv"
C:\ExcelOutPut\SOX_CAM_SQL_Report_010215.xls
What I try to accomplish is output the file with each day append to it, date must be DDMMYY.
I google it and found many samples, tested it, and none of them is work for me.
Any suggestions or some examples to share is greatly appreciate.
I am new to SSIS. I found one poster have similar issue and inside the posted below, there was one suggestion to create variable and connection string but how do I bind that variable to Excel Connection manger.
Please help.
Thank you so much in advance.
Ex: SOX_CAM_SQL_Report _020215.csv
SOX_CAM_SQL_Report _030215.csv
--Similar issue:
https://social.msdn.microsoft.com/Forums/en-US/bda433aa-c8f8-47c9-9e56-efd20b8354ac/creating-a-dynamic-excel-file?forum=sqlintegrationservices
Suggestion in the above posted but where can bind this to Excel Connection Manger.
Please help provide step by step. Thanks.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\" + "ExcelTarget" + (DT_WSTR,4)DATEPART("yyyy",GETDATE()) +
".xls" + ";Extended Properties=\"EXCEL 8.0;HDR=YES\";"
And yes, as you were intimating, the delay validation on the dataflow should be set.Hi NguyenBL,
According to your description, you created ssis package to export data from database to excel, when the package runs, you want to create new excel and name the file with time stamp. If that is the case, we can achieve the goal by following steps:
Create a script task used to create excel files.
Create a data flow task to export data from database to excel.
Add OLE DB source to data flow task.
Add Excel Destination to data flow task.
Create connection manager for OLE DB and Excel.
Click Excel Connection Manager, in Properties window, click (…) button next to Expressions, then set ExcelFilePath with expression like below:
"C:\\ETL Lab\\CreateNewExcel\\ExportData_"+REPLACE((DT_STR, 20, 1252)(DT_DBTIMESTAMP)@[System::StartTime], ":", "")+".xls"
For detail information, please refer to the document:
https://sqljourney.wordpress.com/2013/01/12/ssis-create-new-excel-file-dynamically-to-export-data/
If you have any more questions, please feel free to ask.
Thanks,
Wendy Fu
Wendy Fu
TechNet Community Support -
Help with SAP GUI on Trial VMWare Edition
I currently have a trial version of NetWeaver installed (SAP NetWeaver 7.0.1 Java + ABAP Trial VMWare Edition), but having problems getting the GUI to work. The VM is using GNOME 2.12.2.
I'm currently having trouble with SAP GUI. According to SAP help, a requirement to run SAP GUI for HTML is Windows NT 4.0. Since I'm using GNOME, I tried to get the Java version to work.
When I try to launch SAP GUI, it gives me the following error:
http://i.imgur.com/0ZBVI.png
I wasn't able to troubleshoot the error, so I'm in the process of uninstalling this version of SAP GUI, and try installing again. However, I'm having trouble performing the uninstall. I did some reading, and it says to either run the SAPsweep.exe utility or NWSapSetup.exe. But I can't find either of them on my machine (tried doing a system search, no luck).
I found this thread to be helpful: Re: sapsweep.exe for SAPGUI 7.10 ?, but I'm not running on Windows.
Thanks in advance for any inputHello Anoop.
The error occurs because you have selected OLE DB for OLAP Provider in the Business Explorer selection.
You can tell this from the following line in your sapsetup
00:43:58 NwSapsAtlC 1W Marking package SAPGUI_7.30 ({57F4A687-AE41-4BEA-9553-F852C36F8C1E}) as disabled: selected node OLE DB for OLAP Provider ({5390360A-98D9-4377-BD41-9A147392D000}) has failing condition.
Since you don't have Office installed,you cannot use the Business Explorer modules.
Run the installation again only selecting the components you require.
Jude -
Help with dynamic page layouts
Hello JSP Gurus,
I'm attempting to dynamically generate the page layout for my site based on the organization a user belongs to. Basically, I'd have certain resources like navigation links, graphics, etc, that are modular. Then I'd like to construct the layout using these "moduls" in a dynamic fashion. Does anyone have any suggestions on techniques or technologies that would be useful? I'm not really looking at the portal/portlet model. Is this something that Cocoon could do by storing the layout for each customer as an XML file or something? Any ideas, suggestions, experiences would be helpful.
Thanks!How does Tiles differ from the JetSpeed apache
project? They both appear to be portal-like
frameworks, or am I incorrect about that? Which is
preferred?Frankly, I can't give you an in-depth answer to that. Maybe someone else can help with more details.
What I can tell you is that JetSpeed seems to be more of a real portal architecture. Emphasis is placed on the framework portion, interfacing with exisiting applications. Visual layout takes second seat to this.
Tiles on the other hand puts more emphasis on visual layout and reuse.
Just looking at JetSpeed's visual interfacing a little bit makes me really dislike it. You build tables and such inside of a servlet, so there's a tight coupling (or at least, much tighter than with Struts/Tiles) between the presentation and logic. (I'm basing this on a JavaWorld article at
http://www.javaworld.com/javaworld/jw-07-2001/jw-0727-jetspeed.html )
Based on your initial question, it would seem to me that tiles is much closer to what you're looking for (and likely easier to just pick up and use).
Anyway, take all this with a grain of salt; I'm not exactly an expert on JetSpeed. =) -
Help with dynamic text and and css !
My second question of the day.
I'm trying to build a feature in my app in which the user can
hide/reveal
bolding and or
italics and or
underlining. The text is being loaded in from an xml file
and I was thinking about styling it with css in order to get the
underlining. My problem is that the only way I can think about
pulling this off is to have a css style sheet that has a defined
bold,italic and underline class defined- - then another one that
just has a italic and underline class defined -- then another one
that has just a bold and underline class defined . . . and so on
and so on. You can see why I would prefer a much more streamlined
system. Unfortunately my experience with dynamic text styling is
somewhat limited. Hopefully someone can help me out here.Perfect. I knew it was some little snippet that I was
forgetting. I made a temporary fix of creating a 0% alpha box over
the button like a fake click area above the text, and that worked
but I know that it was a half-arsed way of working around it.
Thanks. -
URGENT: Help with dynamic borders!
Hello all -
I DESPERATLY need help with this! I am using the code from
kirupa's xml photo gallery with the thumbnails. right now the alpha
changes on mouseover, fine...but my client is demanding that it
draw a border instead. I have been at this for about a week and
have NO idea how to do this...i have looked at things like API's
and things...but my main issue is that the images and MC's are all
created on the fly and i dont know how to code in an on mouseover
draw a border type of function, no idea at all!
This is my code as it sits now, PLEASE SOMEONE HELP ME!!!
thank you in advance!really could use some help quick here guys
-
Help with dynamic statement returning values into collection
Hi All
I am trying to use dynamic statement to return values into a collection using the returning clause. However, I get an ORA-00933 error. Here is a simple setup:
create table t(
pk number,
id_batch varchar2(30),
date_created date,
constraint t_pk primary key ( pk )
create or replace type num_ntt is table of number;
create or replace type vc2_ntt is table of varchar2(30);
create or replace
package pkg
as
type rec is record(
pk num_ntt,
id_batch vc2_ntt
procedure p(
p_count in number,
p_rt out nocopy rec
end pkg;
create or replace
package body pkg
as
procedure p(
p_count in number,
p_rt out nocopy rec
is
begin
execute immediate '
insert into t
select level, ''x'' || level, sysdate
from dual
connect by level <= :p_count
returning pk, id_batch into :pk, :id_batch'
using p_count returning bulk collect into p_rt.pk, p_rt.id_batch;
end p;
end pkg;
declare
r pkg.rec;
begin
pkg.p( 5, r );
end;
/sanjeevchauhan wrote:
but I am working with dynamic statement and returning multiple fields into a collection.And using an INSERT...SELECT statement combined with a RETURNING INTO clause still does not work. Whether it's dynamic SQL or not: it doesn't work. The link describes a workaround.
By the way, I don't see why you are using dynamic SQL here. Static SQL will do just fine. And so you can literally copy Adrian's setup.
Regards,
Rob. -
Hello,
I have the following function that works ok:
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
cursor c is select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
'select high_value from all_tab_partitions where table_name='''
|| table_name
|| ''' and table_owner = '''
|| table_owner
|| ''' and partition_name = '''
|| partition_name
|| ''''),
'//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
open c;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
TYPE t1 IS REF CURSOR;
c t1;
sSql VARCHAR2(500);
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
sSql := 'select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
''select high_value from all_tab_partitions where table_name=''''
|| table_name
|| '''' and table_owner = ''''
|| table_owner
|| '''' and partition_name = ''''
|| partition_name
|| ''''''),
''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
OPEN c FOR sSql USING sTable, iImportIndex;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
Please advise,
Regards,
M.R.Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
SQL> var r refcursor
SQL> set autoprint on
SQL> declare
2 ctx dbms_xmlgen.ctxhandle;
3 v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
4 v_value NUMBER := 100;
5 begin
6 ctx := DBMS_XMLGEN.NEWCONTEXT
7 ('select table_name
8 , partition_name
9 , high_value hi_val
10 from dba_tab_partitions
11 where table_name = :table_name');
12 dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
13 open:r for
14 with x as
15 (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
16 from dual)
17 select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
18 , extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
19 , extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
20 from x
21 , TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
22 where extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
23 end;
24 /
PL/SQL procedure successfully completed.
TABLE_NAME
PARTITION_NAME
HI_VAL
LOGMNR_USER$
P_LESSTHAN100
100
SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat. -
Help with dynamic playlist for mpd
Hi guys,
I use mpd with sonata for playing my music, and after trying exaile there is one thing id really like for mpd, and that is the dynamic playlist function.
When you're playing a song in exaile with dynamic playlist enabled, it queries audioscrobbler and automatically adds similar artists/songs to your playlist (if you have them on your pc).
I dont want to use exaile as it just feels too big and slow and bloated (not KISS ), i know a little bit of python so i thought i'll try and make my own little script/program as Sonata has audioscrobbler support, but i dont think there is anyway to query similar artists.
I think im going to try and make this as a daemon type program that will run in the background adding songs to the playlist.
Ive found the code from the exaile source (audioscrobbler.py) which queries lastfm e.g.
>>> lips = AudioScrobblerQuery(artist='The Flaming Lips')
>>> for artist in lips.similar():
... print artist.name, artist.mbid
This will print a list of similar artists to the flaming lips.
I've not done much with python so i thought this would be a good way to try and improve.
Does anyone have any suggestions as to what the best way to go about searching and comparing the results to my mpd database, would the best way just to be to search the mpd.db?
And if anyone else has any ideas/comments id like to hear them.
Edit:
I just found this too, so i may only need to change some things to integrate it with mpd rather than amarok
http://www.kde-apps.org/content/show.php?content=31920
Thanks
Last edited by Kane (2008-06-05 13:24:33)well i just modified the patch into a little script, it does what i need
its here if anyone wants it
import audioscrobbler
import mpd
import random
import time
lastsong = {}
def timer_control():
get_similar()
time.sleep(10)
timer_control()
def get_similar():
audioscrobbler
client = mpd.MPDClient()
client.connect("localhost", 6600)
mpdstatus = client.status()
prevsonginfo = client.currentsong()
global lastsong
if mpdstatus['state'] == "stop": return
if prevsonginfo == lastsong: return
lastsong = prevsonginfo
similarartists = ""
song = prevsonginfo
#if not song: break #No song, do nothing
prevartist = song['artist']
# Is the info already cached?
similar_cache = {}
if similar_cache.has_key(prevartist):
similarartists = similar_cache[prevartist]
else:
#Not cached so fetch from Audioscrobbler
try:
similarartists = [artist.name for artist in audioscrobbler.AudioScrobblerQuery(artist=prevartist).similar()]
# Cache search results and save some time next search
similar_cache[prevartist] = similarartists
except audioscrobbler.AudioScrobblerError:
similar_cache[prevartist] = None # Empty cache
return # Do nothing!
if not similarartists: return # Empty list
# Split list in half and sort upper half
# this means good matches will have priority
# but makes sure artist A does not always result in artist B
half_idx = len(similarartists)/2
upperhalf = similarartists[:half_idx]
lowerhalf = similarartists[half_idx:]
random.shuffle(upperhalf)
artistlist = upperhalf
artistlist.extend(lowerhalf)
# Try each artist in order
for artist in artistlist:
try:
print "Trying:",artist
songs = client.search("artist", artist)
if not songs: continue
selected_song = random.sample(songs, 1)[0]
client.add(selected_song['file'])
print "Added", selected_song['title'],"by",selected_song['artist']
# Delete old song from playlist?
break
except mpd.MPDError, e:
print "MPDError", e.message
continue
except ValueError, e:
print "ValueError:",e.message
continue
timer_control()
Last edited by Kane (2008-06-06 16:22:49) -
It's the ever popular Inventory program again! I'm creating a GUI to display the information contained within an array of objects which, in this case, represent compact discs. I've received some good help from other's posts on this project since it seems there's a few of us working on the same one but now, since each person working on this project has programmed theirs differently, I'm stuck. I'm not sure how to proceed with my ActionListeners for the buttons I've created.
Here's my code:
// GUICDInventory.java
// uses CD class
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUICDInventory extends JFrame
protected JPanel panel; //panel to hold buttons
protected JPanel cdImage; // panel to hold image
int displayElement = 0;
public String display(int element)
return CD2[element].toString();
}//end method
public static void main( String args[] )
new GUICDInventory();
}// end main
public GUICDInventory()
CD completeCDInventory[] = new CD2[ 5 ]; // creates a new 5 element array
// populates array with objects that implement CD
completeCDInventory[ 0 ] = new CD2( "Sixpence None the Richer" , "D121401" , 12 , 11.99, 1990 );
completeCDInventory[ 1 ] = new CD2( "Clear" , "D126413" , 10 , 10.99, 1998 );
completeCDInventory[ 2 ] = new CD2( "NewsBoys: Love Liberty Disco" , "2438-51720-2" , 10 , 12.99, 1999 );
completeCDInventory[ 3 ] = new CD2( "Skillet: Hey You, I Love Your Soul" , "D122966" , 9 , 9.99, 1998 );
completeCDInventory[ 4 ] = new CD2( "Michael Sweet: Real" , "020831-1376-204" , 15 , 12.99, 1995 );
//declares totalInventoryValue variable
double totalInventoryValue = CD.calculateTotalInventory( completeCDInventory );
final JTextArea textArea = new JTextArea(display(displayElement));
final JButton prevBtn = new JButton("Previous");
final JButton nextBtn = new JButton("Next");
final JButton lastBtn = new JButton("Last");
final JButton firstBtn = new JButton("First");
prevBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
displayElement = (//what goe here? ) % //what goes here?
textArea.setText(display(displayElement));// <--is this right?
nextBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
displayElement = (//what goes here? ) % //what goes here?
textArea.setText(display(displayElement));// <--is this right?
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
displayElement = 0;
textArea.setText(display(displayElement));// <--is this right?
lastBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
displayElement = //what goes here?;
textArea.setText(display(displayElement));// <--is this right?
JPanel panel = new JPanel(new GridLayout(1,2));
panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);
JPanel cdImage = new JPanel(new BorderLayout());
cdImage.setPreferredSize(new Dimension(600,400));
JFrame cdFrame = new JFrame();
cdFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
cdFrame.getContentPane().add(panel,BorderLayout.SOUTH);
cdFrame.getContentPane().add(new JLabel("",new ImageIcon("cd.gif"),JLabel.CENTER),BorderLayout.NORTH);
cdFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cdFrame.pack();
cdFrame.setSize(500,200);
cdFrame.setTitle("Compact Disc Inventory");
cdFrame.setLocationRelativeTo(null);
cdFrame.setVisible(true);
}//end GUICDInventory constructor
} // end class GUICDInventory
// CD2.java
// subclass of CD
public class CD2 extends CD
protected int copyrightDate; // CDs copyright date variable declaration
private double price2;
// constructor
public CD2( String title, String prodNumber, double numStock, double price, int copyrightDate )
// explicit call to superclass CD constructor
super( title, prodNumber, numStock, price );
this.copyrightDate = copyrightDate;
}// end constructor
public double getInventoryValue() // modified subclass method to add restocking fee
price2 = price + price * 0.05;
return numStock * price2;
} //end getInventoryValue
// Returns a formated String contains the information about any particular item of inventory
public String displayInventory() // modified subclass display method
return String.format("\n%-22s%s\n%-22s%d\n%-22s%s\n%-22s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n \n" ,
"CD Title:", title, "Copyright Date:", copyrightDate, "Product Number:", prodNumber , "Number in Stock:",
numStock , "CD Price:" , "$" , price , "Restocking fee (5%):", "$", price*0.05, "Inventory Value:" , "$" ,
getInventoryValue() );
} // end method
}//end class CD2
// CD.java
// Represents a compact disc object
import java.util.Arrays;
class CD implements Comparable
protected String title; // CD title (name of product)
protected String prodNumber; // CD product number
protected double numStock; // CD stock number
protected double price; // price of CD
protected double inventoryValue; //number of units in stock times price of each unit
// constructor initializes CD information
public CD( String title, String prodNumber, double numStock, double price )
this.title = title; // Artist: album name
this.prodNumber = prodNumber; //product number
this.numStock = numStock; // number of CDs in stock
this.price = price; //price per CD
} // end constructor
public double getInventoryValue()
return numStock * price;
} //end getInventoryValue
//Returns a formated String contains the information about any particular item of inventory
public String displayInventory()
//return the formated String containing the complete information about CD
return String.format("\n%-22s%s\n%-22s%s\n%-22s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n%-22s%s%.2f\n \n" ,
"CD Title:", title, "Product Number:", prodNumber , "Number in Stock:",
numStock , "CD Price:" , "$" , price , "Restocking fee (5%):", "$", price*0.05, "Inventory Value:" , "$" ,
getInventoryValue() );
} // end method
//method to calculate the total inventory of the array of objects
public static double calculateTotalInventory( CD completeCDInventory[] )
double totalInventoryValue = 0;
for ( int count = 0; count < completeCDInventory.length; count++ )
totalInventoryValue += completeCDInventory[count].getInventoryValue();
} // end for
return totalInventoryValue;
} // end calculateTotalInventory
// Method to return the String containing the Information about Inventory's Item
//as appear in array (non-sorted)
public static String displayTotalInventory( CD completeCDInventory[] )
//string which is to be returned from the method containing the complete inventory's information
String retInfo = "\nInventory of CDs (unsorted):\n";
//loop to go through complete array
for ( int count = 0; count < completeCDInventory.length; count++ )
retInfo = retInfo + "Item# " + (count + 1); //add the item number in String
retInfo = retInfo + completeCDInventory[count].displayInventory(); //add the inventory detail in String
}// end for
return retInfo; //return the String containing complete detail of Inventory
}// end displayTotalInventory
public int compareTo( Object obj ) //overlaod compareTo method
CD tmp = ( CD )obj;
if( this.title.compareTo( tmp.title ) < 0 )
return -1; //instance lt received
else if( this.title.compareTo( tmp.title ) > 0 )
return 1; //instance gt received
return 0; //instance == received
}// end compareTo method
//Method to return the String containing the Information about Inventory's Item
// in sorted order (sorted by title)
public static String sortedCDInventory( CD completeCDInventory[] )
//string which is to be returned from the method containing the complete inventory's information
String retInfo = "\nInventory of CDs (sorted by title):\n";
Arrays.sort( completeCDInventory ); // sort array
//loop to go through complete array
for( int count = 0; count < completeCDInventory.length; count++ )
retInfo = retInfo + "Item# " + (count + 1); //add the item number in String
retInfo = retInfo + completeCDInventory[count].displayInventory(); //add the inventory detail in String
return retInfo; //return the String containing complete detail of Inventory
} // end method sortedCDInventory
} // end class CDnextBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
displayElement = (//what goes here? ) % //what goes here?
textArea.setText(display(displayElement));// <--is this right?
});Above is your code for the "Next" button.
You ask the question "What goes here"? Well what do you think goes there?
If you are looking at item 1 and you press the "Next" button do you not want to look at item 2?
So the obvious solution would be to add 1 to the previous item value. Does that not make sense? What problem do you have when you try that code?????
Next you say "Is this right"? Well how are we supposed to know? You wrote the code. We don't know what the code is supposed to do. Again you try it. If it doesn't work then describe the problem you are having. I for one can't execute your code because I don't use JDK5. So looking at the code it looks reasonable, but I can't tell by looking at it what is wrong. Only you can add debug statements in the code to see whats happening.
If you want help learn to as a proper question and doen't expect us to spoon feed the code to you. This is your assignment, not ours. We are under no obligation to debug and write the code for you. The sooner you learn that, the more help you will receive. -
I need help with my GUI Photo Album.
Hello! I'm still learning bits about GUI and I need some assistance to make my basic program work. I've searched the forums to look at past Photo Album projects; they didn't help much or maybe I'm overlooking some things. Every time I click the "Next" button the image doesn't change. It may be a simple task to solve, but I'm really stumped! Sorry if it's such a stupid thing to ask. Thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class PhotoAlbum extends JPanel {
int i = 1;
JFrame frame = new JFrame("Photo Album");
JButton next = new JButton("Next");
ImageIcon icon = new ImageIcon("../Images/" + i + ".jpg");
JLabel picture = new JLabel(icon);
ButtonListener buttonListener = new ButtonListener();
public PhotoAlbum() {
frame.setSize(700, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(5,5));
frame.getContentPane().add(picture, BorderLayout.CENTER);
frame.getContentPane().add(next, BorderLayout.SOUTH);
next.addActionListener(buttonListener);
frame.setVisible(true);
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == next){
++i;
}WafflesNSyrup wrote:
int i = 1;
ImageIcon icon = new ImageIcon("../Images/" + i + ".jpg");
++i;
So I understand that you originally thought incrementing (i) would somehow update (icon) since it uses (i) in an expression. But now you hopefully know this is not a magical expression language.
I bet you would have also thought that this:
int x = 1;
int y = 2;
int z = x + y;
x = 42;
y = 58;would have ended up with z having the value 100? It doesn't. It did the math once, when it executed the expression (x + y) and stored it in the variable (z). So z == 3, regardless of what happens to x or y after the fact. -
Hello, could someone help me why after creating the dynamic calc member below, our calc script somehow get stuck/ ran very very slow...
Below is currently our Hierararchy for Division dimension:
Division Dimension
Division Rollup ( Never Share)
Division 1 ( Never Share)
Division a (Never Share) level 0
Division b (Never Share) level 0
Division c (Never Share) level 0
Division 2 (Never Share)
Division d ( Never Share) level 0
Alt_Division without cd (Dynamic Calc) ...and the member formula I did is
="Division Rollup" - "Division c" - "Division d" ;
After I refresh, the Alt_Division without cd went fine, calculated correctly when I retreive in Essbase Escel , however, the big problem was, when we run our aregular Essbase calc scripts, it somehow got stuck with Alt_Division without cd member and the calc went very very slow almost to the point that it just stopped calcing.
Could you please let me know if there is something wrong with my dynamic calc member above... Should the Alt_Division dynamic calc should not be a sibling of the Division Rollup member? or I could not use the "Division Rollup" member .
Could you please recommend a better way of writing the dynamic calc member ( and it's position in the Hierarchy) ... without me aggregarting the dbase ...( I like dynamic calc since it aggs on the fly).
Please advise.
Thanks.Few Things...
I am assuming Division is a sparse Dimension. A Dynamic Calc member formula on a Sparse dimension member will surely take lots of time.
Suggestion 1:
Create an Alternate hierarchy sharing c and d. Change the consolidation operators to get the C - D at Alt_Hierarchy.
Suggestion 2:
Make the member Store and put the desired calculation in a Calculation script rather than having it as a dynamic calc member formula.
Hope this helps.
Madhavi -
Hi All,
New to Flex and wanted to get some help from the public.
Basically, here's what I want to do.
I have a tab navigator with multiple tabs. Each tab has a
datagrid on it. When you click the tab, the grid should update to
new data based on the tab clicked. That's no problem. The problem
I'm running into is that because the data is taking a while to
retreive from the server, users are getting the previous's tabs
datagrid until the information is updated. I wanted to do two
things:
1) Change the cursor to a "thinking" or "processing" icon
where clicks can't be done until the full data has been retreived
and updated. This is a nice to have; i haven't the slightlest clue
on how to accomplish this.
2) In lieu/addition to #1, i wanted the datagrid to be
dynamic. Meaning, if you go to the tab, it'll add dynamically the
datagrid to the tab and then show the data.
Here's my code, but it doesn't work very well. Any help i can
get from you guys would be great:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="horizontal" initialize="createDataGrid()">
<mx:Script>
<![CDATA[
import mx.controls.DataGrid;
import mx.managers.PopUpManager;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.containers.HBox;
import mx.containers.TabNavigator;
[Bindable]
private var infoDataGrid:ArrayCollection;
[Bindable]
private var currentID:String;
[Bindable]
private var dynDataGrid:DataGrid;
private function createDataGrid():void {
dynDataGrid = new DataGrid;
dynDataGrid.dataProvider=infoDataGrid;
dynDataGrid.width=80;
private function getDataFromServer(event:ResultEvent):void {
var numOfRecords:int = event.result.result_set.num_rows;
if (numOfRecords > 0 ) {
infoDataGrid = event.result.result_set.results.result as
ArrayCollection;
} else {
// no information retrieved worry about this later
private function mainBuilder( event:Event ):void {
var tabNavigator:TabNavigator = TabNavigator( event.target
var pattern:RegExp = /\D/gi;
if (tabNavigator.selectedChild.id != "NewTab") {
// Remove all non-digits from LID
var str:String = tabNavigator.selectedChild.id;
currentID=(str.replace(pattern, ""));
phpHTTPService.send();
// loop through all children and remove any datagrids while
adding to the current one
for (y=0; y<tabNavigator.numChildren; y++) {
var tmpNavID:String = tabNavigator.childDescriptors[y].id
if ((tmpNavID == tabNavigator.selectedChild.id) &&
(tmpNavID != "")) {
// this does not work as intended...
tabNavigator.selectedChild.addChild(dynDataGrid);
} else {
// this does not work.
//How do you access something directly with an ID but
represented by a variable?
// tmpNavID.removeChildAt(0);
} else {
// New Tab selected, do something here
]]>
</mx:Script>
<mx:HTTPService id="phpHTTPService"
url="/flex/php/AssetsInLocation.php" useProxy="false" method="GET"
result="getDataFromServer(event)">
<mx:request xmlns="">
<lid>{currentID}</lid>
</mx:request>
</mx:HTTPService>
<mx:TabNavigator id="tabNav"
creationComplete="tabNav.selectedIndex=0;mainBuilder(event)"
width="100%" change="mainBuilder(event);">
<mx:HBox id="LID2345" label="Tab 1" width="100%"
height="100%" horizontalAlign="center">
<!-- <mx:DataGrid dataProvider="{infoDataGrid}"
width="80%"/> -->
</mx:HBox>
<mx:HBox id="LID1111" label="Tab 2" width="100%"
height="100%" horizontalAlign="center">
<!-- <mx:DataGrid dataProvider="{infoDataGrid}"
width="80%"/> -->
</mx:HBox>
<mx:HBox id="LID1234" label="Tab 3" width="100%"
height="100%" horizontalAlign="center">
<!-- <mx:DataGrid dataProvider="{infoDataGrid}"
width="80%"/> -->
</mx:HBox>
<mx:Canvas id="NewTab" label="New..." width="100%"
height="100%">
</mx:Canvas>
</mx:TabNavigator>
</mx:Application>
Thanks all for your assistance.I think Ned is on the right track, but the specific form of
the command may be off. If the ProgressEvent handler is defined on
MC_Holder_Image, then the command to get the
MC_Holder_Preload_TextField object should be something like:
var oTextField:TextField =
this.parent.parent.MC_Holder_Preload.getChildByName(childname);
oTextField.text = "some text";
The first "parent" references MC_Holder_Sprite, the second
MC_Holder. If there are several instances of MC_Holder_Preload,
then the above would have to be modified to account for that by
first using the getChildByName method to acquire the appropriate
instance like so:
var oMC:MovieClip =
this.parent.parent.getChildByName(HolderPreloadName);
var oTextField:TextField = oMC.getChildByName(TextFieldName);
Hope this (a) makes sense, (b) helps and (c) actually works.
Regards
Dave Spaar
Maybe you are looking for
-
Returning from a JSF flow with faces-redirect
I'm using Glassfish 4.1 with JSF 2.2.9. I can't figure out how to return from a JSF flow with a redirect. I've tried this in the flow definition xml: <flow-return id="returnFromFlow"> <from-outcome>/index.xhtml?faces-redirect=true</from-outcome>
-
How can I fix a corrupted iPhone 4 video file?
I have a video that i recorded back in October with my iPhone 4, but for some reason now it won't play. It says "The movie could not be opened. The file is not a movie file. I have tried a bunch of different corrupted video repair software programs..
-
Problem printing Report with Image in BI Publisher 11g
I am working with BI publisher *11g* but I have problem printing images. Everything works fine if I do not include any images however when I add a image I get following problems. When I tried printing PDF in output I get Type /Xobject subtype /Image
-
Disk error when downloading Vuze torrent
Helloooo. Twice now while downloading a Vuze torrent I get a note saying there's a disk reading error. This occurs at just about the half way stage. On these downloads I have been downloading continuously. Is this significant? Is there anything I can
-
some body help me? I lost my notes, but i need recover them in my computer, no in my iphone. I prefeer in Spanish...sorry, well I don´t lost,, I have a backup in the pc, but I don´t know how recover.