Changing JPanels at runtime
Hi guys,
I'm writing a turorial apllication. I want to break down the information into JPanels, however I can't seem to swap between JPanels at runtime. I've tried calling validate and revalidate and then repaint... but I cant seem to get it working.
This is probably a really common question but I couldn't find anything in the archives. Any help would be greatly appreciated.
Cheers
Stuart
I'm assuming you're removing the old one before adding the new, in which case there isn't normally a problem so we'd have to see some code. Something I find works quite well for this is the CardLayout - check the docs. It lets you add a load of panels on top of one another and refer to each with a string. You then just call CardLayout.show("name") and this component comes to the top.
hth
Similar Messages
-
Hi all,
I am trying change images at runtime and quite frankly it's driving me nuts. I'm pretty new to Java and don't understand some of the principles but I'm trying. I have this code below, that loads up a few images. I want to be able to change some/all of these images either on a timed even or on a button press, but all the things I've tried don't work. Can someone offer me some help....thanks in advance
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class bc extends JFrame implements ActionListener {
public static void main(String[] args) {new bc();}
bc() {
//setUndecorated(true); // - this removed the titlebar!
setTitle("BC...");
setSize(350,125);
setResizable(false);
setLocation(50,50);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(0,0,0));
getContentPane().setBackground(new Color(255,255,255));
JPanel hours = new JPanel();
hours.setLayout(new GridLayout(4,2));
hours.add(hour14);
hours.add(hour24);
hours.add(hour13);
hours.add(hour23);
hours.add(hour12);
hours.add(hour22);
hours.add(hour11);
hours.add(hour21);
JPanel mins = new JPanel();
mins.setLayout(new GridLayout(4,2));
mins.add(min14);
mins.add(min24);
mins.add(min13);
mins.add(min23);
mins.add(min12);
mins.add(min22);
mins.add(min11);
mins.add(min21);
JPanel secs = new JPanel();
secs.setLayout(new GridLayout(4,2));
secs.add(sec14);
secs.add(sec24);
secs.add(sec13);
secs.add(sec23);
secs.add(sec12);
secs.add(sec22);
secs.add(sec11);
secs.add(sec21);
JPanel helptext = new JPanel();
helptext.setLayout(new GridLayout(4,2));
helptext.add(new JLabel("8"));
helptext.add(new JLabel("4"));
helptext.add(new JLabel("2"));
helptext.add(new JLabel("1"));
//add action listenters
changeImg.addActionListener(this);
JPanel cp = new JPanel();
cp.setLayout(new GridLayout(1,6));
cp.setBackground(new Color(255,255,255));
cp.add(hours);
cp.add(mins);
cp.add(secs);
cp.add(helptext);
cp.add(changeImg);
setContentPane(cp);
setVisible(true);
public void actionPerformed(ActionEvent ae) {
hour11.PaintOff(1);
//JOptionPane.showMessageDialog(this, "changed");
repaint();
JPanel hour11 = new PaintOff(0);
JPanel hour12 = new PaintOff(0);
JPanel hour13 = new PaintBlank();
JPanel hour14 = new PaintBlank();
JPanel hour21 = new PaintOff(0);
JPanel hour22 = new PaintOff(0);
JPanel hour23 = new PaintBlank();
JPanel hour24 = new PaintBlank();
JPanel min11 = new PaintOff(0);
JPanel min12 = new PaintOff(0);
JPanel min13 = new PaintOff(0);
JPanel min14 = new PaintOff(0);
JPanel min21 = new PaintOff(0);
JPanel min22 = new PaintOff(0);
JPanel min23 = new PaintOff(0);
JPanel min24 = new PaintOff(0);
JPanel sec11 = new PaintOff(0);
JPanel sec12 = new PaintOff(0);
JPanel sec13 = new PaintOff(0);
JPanel sec14 = new PaintOff(0);
JPanel sec21 = new PaintOff(0);
JPanel sec22 = new PaintOff(0);
JPanel sec23 = new PaintOff(0);
JPanel sec24 = new PaintOff(0);
JButton changeImg = new JButton("change");
}///---------This is my PaintOff class ---------------\\\
import javax.swing.*;
import java.awt.*;
import java.awt.Image.*;
public class PaintOff extends JPanel {
Toolkit tk = Toolkit.getDefaultToolkit();
public Image imgOff = tk.getImage("off.jpg");
public Image imgOn = tk.getImage("on.jpg");
public Image paintMe = tk.getImage("off.jpg");
PaintOff(int a) {
if(a == 1) {
vOn();
} else {
vOff();
public void vOn() {
paintMe = imgOn;
//JOptionPane.showMessageDialog(new bc(), "shown");
public void vOff() {
paintMe = imgOff;
public void paintComponent(Graphics g) {
g.drawImage(paintMe,0,0,this);
}PaintBlank class is not included here, it's basically just the same as PaintOff but only has one image inside.
When I try and compile this code, I get
C:\jdk1.4\bin\bclock>javac bc.java
bc.java:79: cannot resolve symbol
symbol : method PaintOff (int)
location: class javax.swing.JPanel
hour11.PaintOff(1);
^
1 error
I don't understand this either, I've tried replacing "PaintOff(1)" with "vOn()" but I get the same error. This is baffling to be, as I thought that the hour11 would have access to all the methods inside the PaintOff class?
Anyway, thanks for any help you guys give me!
Cheers
//Chris.Hi!
Your problem is that you've used a widening conversion to convert from PaintOff to a JPanel. JPanel has no such method, and so the compiler is complaining that it can't find it.
e.g
public class NoCompile{
public static void main(String args[]){
One one = new Two();
one.methTwo();
public class Two extends One{
public Two(){}
public void methTwo(){
System.out.println("Executed 2");
public class One{
public One(){}
public void meth1(){}
} will give you the same sort of error message. To make the compiler happy, use a cast.
Now this will compile and gives the right result.
public class NoCompile{
public static void main(String args[]){
One one = new Two();
((Two)one).methTwo();
}So in your case, you want to do
((PaintOff)hour11).vOn();
Does that help?
:) jen -
How to dynamically resize JPanel at runtime??
Hello Sir:
I met a problem, I need to resize a small JPanel called panel within a main Control JPanel (with null Layout) if I click the mouse then I can Drag and Resize this small JPanel Border to the size I need at runtime, I know I can use panel.setSize() or panel.setPreferredSize() methods at design time,
But I have no idea how to do it even I search this famous fourm,
How to dynamically resize JPanel at runtime??
Can any guru throw some light or good example??
ThanksWhy are you using a null layout? Wouldn't having a layout manager help you in this situation?
-
How to resize JPanel at Runtime ??
Hi,
Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
Please advice how to do that??
Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.*;
public class ResizeJPanels extends JPanel
protected JLabel label1, label2, label3, label4, labeltmp;
protected JLabel[] labels;
protected JPanel[] panels;
protected JPanel selectedJPanel;
protected JButton btn = new JButton("Move JPanel");
int cx, cy;
protected Vector order = new Vector();
public static void main(String[] args)
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new ResizeJPanels().GroupJLabels());
f.setSize(600,700);
f.setLocation(200,200);
f.setVisible(true);
private MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
JPanel jp = new JPanel();
jp.setLayout(null);
Component[] c = ((JPanel)e.getSource()).getComponents();
System.out.println("c.length = " + c.length);
for(int j = 0; j < c.length; j++) {
if(c[j].getBounds().contains(p)) {
if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
selectedJPanel = (JPanel)c[j];
selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
break;
add(jp);
revalidate();
public JPanel GroupJLabels ()
setLayout(null);
addLabels();
label1.setBounds( 125, 150, 125, 25);
label2.setBounds(425, 150, 125, 25);
label3.setBounds( 125, 575, 125, 25);
label4.setBounds(425, 575, 125, 25);
//add(btn);
btn.setBounds(10, 5, 205, 25);
add(btn);
determineCenterOfComponents();
ComponentMover mover = new ComponentMover();
ActionListener lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
ComponentMover mover = new ComponentMover();
addMouseListener(mover);
addMouseMotionListener(mover);
btn.addActionListener(lst);
addMouseListener(ml);
return this;
public void paintComponent(final Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Point[] p;
g2.setStroke(new BasicStroke(4f));
for(int i = 0 ; i < order.size()-1; i++) {
JPanel l1 = (JPanel)order.elementAt(i);
JPanel l2 = (JPanel)order.elementAt(i+1);
p = getCenterPoints(l1, l2);
g2.setColor(Color.black);
// g2.draw(new Line2D.Double(p[0], p[1]));
private Point[] getCenterPoints(Component c1, Component c2)
Point
p1 = new Point(),
p2 = new Point();
Rectangle
r1 = c1.getBounds(),
r2 = c2.getBounds();
p1.x = r1.x + r1.width/2;
p1.y = r1.y + r1.height/2;
p2.x = r2.x + r2.width/2;
p2.y = r2.y + r2.height/2;
return new Point[] {p1, p2};
private void determineCenterOfComponents()
int
xMin = Integer.MAX_VALUE,
yMin = Integer.MAX_VALUE,
xMax = 0,
yMax = 0;
for(int i = 0; i < labels.length; i++)
Rectangle r = labels.getBounds();
if(r.x < xMin)
xMin = r.x;
if(r.y < yMin)
yMin = r.y;
if(r.x + r.width > xMax)
xMax = r.x + r.width;
if(r.y + r.height > yMax)
yMax = r.y + r.height;
cx = xMin + (xMax - xMin)/2;
cy = yMin + (yMax - yMin)/2;
private class ComponentMover extends MouseInputAdapter
Point offsetP = new Point();
boolean dragging;
public void mousePressed(MouseEvent e)
Point p = e.getPoint();
for(int i = 0; i < panels.length; i++)
Rectangle r = panels[i].getBounds();
if(r.contains(p))
selectedJPanel = panels[i];
order.addElement(panels[i]);
offsetP.x = p.x - r.x;
offsetP.y = p.y - r.y;
dragging = true;
repaint(); //added
break;
public void mouseReleased(MouseEvent e)
dragging = false;
public void mouseDragged(MouseEvent e)
if(dragging)
Rectangle r = selectedJPanel.getBounds();
r.x = e.getX() - offsetP.x;
r.y = e.getY() - offsetP.y;
selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
//determineCenterOfComponents();
repaint();
private void addLabels()
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 3");
label4 = new JLabel("Label 4");
labels = new JLabel[] {
label1, label2, label3, label4
JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
jl.setBackground(Color.green);
jl.setOpaque(true);
jl.setFont(new Font("Helvetica", Font.BOLD, 18));
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
panels = new JPanel[]{jp};
jp.setBorder(new LineBorder(Color.black, 3, false));
jp.setPreferredSize(new Dimension(400,200));
jp.add(jl, BorderLayout.NORTH);
for(int i = 0; i < labels.length; i++)
labels[i].setHorizontalAlignment(SwingConstants.CENTER);
labels[i].setBorder(BorderFactory.createEtchedBorder());
jp.add(labels[i], BorderLayout.CENTER);
jp.setBounds(100, 100, 400,200);
add(jp);import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.MouseInputAdapter;
public class Resizing extends JPanel {
public Resizing() {
super(null);
addPanel();
PanelControlAdapter control = new PanelControlAdapter(this);
addMouseListener(control);
addMouseMotionListener(control);
private void addPanel() {
JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
jl.setBackground(Color.green);
jl.setOpaque(true);
jl.setFont(new Font("Helvetica", Font.BOLD, 18));
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.setBorder(new LineBorder(Color.black, 3, false));
jp.add(jl, BorderLayout.NORTH);
jp.setBounds(50,50,400,200);
add(jp);
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Resizing());
f.setSize(500,400);
f.setLocation(100,100);
f.setVisible(true);
class PanelControlAdapter extends MouseInputAdapter {
Resizing host;
Component selectedComponent;
LineBorder black;
LineBorder green;
Point offset = new Point();
Point start = new Point();
boolean dragging = false;
boolean resizing = false;
public PanelControlAdapter(Resizing r) {
host = r;
black = new LineBorder(Color.black, 3, false);
green = new LineBorder(Color.green, 3, false);
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
boolean hovering = false;
Component c = host.getComponent(0);
Rectangle r = c.getBounds();
if(r.contains(p)) {
hovering = true;
if(selectedComponent != c) {
if(selectedComponent != null) // reset
((JComponent)selectedComponent).setBorder(black);
selectedComponent = c;
((JComponent)selectedComponent).setBorder(green);
if(overBorder(p))
setCursor(p);
else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
selectedComponent.setCursor(Cursor.getDefaultCursor());
if(!hovering && selectedComponent != null) {
((JComponent)selectedComponent).setBorder(black);
selectedComponent = null;
private boolean overBorder(Point p) {
Rectangle r = selectedComponent.getBounds();
JComponent target = (JComponent)selectedComponent;
Insets insets = target.getBorder().getBorderInsets(target);
// Assume uniform border insets.
r.grow(-insets.left, -insets.top);
return !r.contains(p);
private void setCursor(Point p) {
JComponent target = (JComponent)selectedComponent;
AbstractBorder border = (AbstractBorder)target.getBorder();
Rectangle r = target.getBounds();
Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
int outcode = ir.outcode(p.x, p.y);
Cursor cursor;
switch(outcode) {
case Rectangle.OUT_TOP:
cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
break;
case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
break;
case Rectangle.OUT_LEFT:
cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
break;
case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
break;
case Rectangle.OUT_BOTTOM:
cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
break;
case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
break;
case Rectangle.OUT_RIGHT:
cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
break;
case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
break;
default:
cursor = Cursor.getDefaultCursor();
selectedComponent.setCursor(cursor);
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if(selectedComponent != null) {
Rectangle r = selectedComponent.getBounds();
if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
} else {
start = p;
resizing = true;
public void mouseReleased(MouseEvent e) {
dragging = false;
resizing = false;
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
if(dragging || resizing) {
Rectangle r = selectedComponent.getBounds();
if(dragging) {
r.x = p.x - offset.x;
r.y = p.y - offset.y;
selectedComponent.setLocation(r.x, r.y);
} else if(resizing) {
int type = selectedComponent.getCursor().getType();
switch(type) {
case Cursor.N_RESIZE_CURSOR:
r.height -= p.y - start.y;
r.y = p.y;
break;
case Cursor.NW_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
r.height -= p.y - start.y;
r.y = p.y;
break;
case Cursor.W_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
break;
case Cursor.SW_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
r.height += p.y - start.y;
break;
case Cursor.S_RESIZE_CURSOR:
r.height += p.y - start.y;
break;
case Cursor.SE_RESIZE_CURSOR:
r.width += p.x - start.x;
r.height += p.y - start.y;
break;
case Cursor.E_RESIZE_CURSOR:
r.width += p.x - start.x;
break;
case Cursor.NE_RESIZE_CURSOR:
r.width += p.x - start.x;
r.height -= p.y - start.y;
r.y = p.y;
break;
default:
System.out.println("Unexpected resize type: " + type);
selectedComponent.setBounds(r.x, r.y, r.width, r.height);
start = p;
} -
Changing picture at runtime using delphi
Post Author: iman_400
CA Forum: Other
Please help me, is there anyway we can change picture at runtime using delphi 7.0 and CRXIR2?Hi, Lee;
For the version of Crystal Reports that comes with .NET, you can use something like one of our samples shows:
https://smpdl.sap-ag.de/~sapidp/012002523100006252822008E/net_win_smpl.exe
Look for the sample, vbnet_win_DynamicImage.zip. It uses an ADO.NET dataset to change the image.
For Crystal Reports XI R2 and Crystal Reports 2008, you can more directly change the image location using built in functionality.
In the Designer, choose Insert > Picture. Choose a default image to show and save it. Right-click on it and select Format Graphic. Go to the Picture tab and click the formula button for Graphic location. Save the report.
Then, at runtime you can populate the Formula with the new location for your image, either a URL or disk file location.
See the following note for more information:
[Image|https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_boj_erq/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233313338333333373334%7D.do]
Best Regards,
Jonathan -
Change to the runtime the logon language with ABAP
Hello,
I have a question.
Is it possible to change to the runtime the logon language?
With the URL-parameter example it worked.
http://www.****bsp/sap/z_page/default.htm?sap-language=en
But I need this in the event handler with ABAP coding.
thanks Erenyou can either use
CL_HTTP_UTILITY->IF_HTTP_UTILITY~SET_REQUEST_URI
uri = sap-language=FR
or
CL_HTTP_REQUEST->IF_HTTP_ENTITY~SET_FORM_FIELD
name = sap-client
value = FR
or
use
SET LOCALE LANGUAGE 'S'. within your abap coding
Regards
Raja -
Redraw a JPanel during runtime
Hi there,
Im trying to redraw a whole JPanel during runtime.
So basically I have this panel:
public JPanel panel1 = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
}That panel is added to my JFrame during initialisation.
I added an actionListener to a JButton that creates a whole new JPanel
Then i try to set the default (panel1) to the new generated JPanel:
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(myButton)) {
JPanel newPanel = generateNewPanel();
panel1 = newPanel;
panel1.validate();
panel1.repaint();
}After i done all that, it didn't redraw the jpanel
Please advise on what I have gotten wrong.
Thanks
Edited by: Ruski on Mar 10, 2009 1:35 PMTo be honest i recommend not using netbeans to code gui for a long term project which relies on code. NetBeans is useful - only for creating gui stubs and for throwaway gui prototypes but not in the long run, which is of my own experience. To be fair i have many years of coding gui's way back in the days when awt only started up.
i know gui in java is "crap" because of it's repeated code and tedious mechanism to generate ui windows so to do that you might as well hard code it yourself using a proper or better IDE - "ECLIPSE" or any linux based code editors are good also. This way you learn much more about guis. -
[svn] 3839: Update the channel url to reflect the change in the runtime channel
Revision: 3839
Author: [email protected]
Date: 2008-10-23 07:42:37 -0700 (Thu, 23 Oct 2008)
Log Message:
Update the channel url to reflect the change in the runtime channel
Modified Paths:
blazeds/branches/3.0.x/qa/apps/qa-manual/ajax/messaging/TextMessageRuntimeDest.htmlMany ways to do this. The easiest is to have a method in one of your classes that reads the data from the database and creates all the proper structure under a RootNode and then returns that RootNode.
Whenever you want to refresh the tree, just call that method to recreate the root node (and all the underlying structure/nodes) and then re-set the root node of your tree model using the setRoot() method. That will cause it to refresh the display given the new root node.
Once you have that working, you can get fancier and make it more efficient (only updating/firing events for the nodes that actually changed, etc). -
To change table data runtime when dropdown item is changed
Hi,
I have two ui elements(Dropdown by index and table) in single view .
I need to display table as per drondown index item selection. Means i have to change table data runtime when dropdown item is changed.Please help me in that .Please provide code for same.
Regards,
gurprit BhatiaHello gurprit Bhatia,
On the view create a new action. Fill only the Name and Text and leave the other items default.
In this event you can populate the table fields.
Bound this newly created action (event) to the onSelect property of the 'DropDownByIndex'.
Regards,
Patrick Willems -
A question about how to change a button in a JPanel during runtime
I am a beginner of GUI. Now I am trying to change a specific component, a button, when the application is running. For example, I have 3 buttons in a JPanel. Each button has its onw icon. If I click one of them, it will change its icon, but the other two don't change. I don't know if there is any method for changing a specific component during runtime. If any one knows please let me know, I will appreciate that very much!!!
What you're going to have to do is loop inside the actionlistener but still have accessability to click while its looping. I don't know much about it, but I think you're going to need a thread. Try something like this... (it doesn't work yet, but I have to take off)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class buttonxdemo extends JFrame implements ActionListener{
Buttonx mybutton;
//set it all up, make it look pretty =]
public buttonxdemo()
mybutton = new Buttonx("default");
getContentPane().add(mybutton.thebutton);
mybutton.thebutton.addActionListener(this);
this.setDefaultCloseOperation(3);
this.setSize(200,200);
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == mybutton.thebutton)
if (mybutton.keepGoing)
mybutton.keepGoing = false;
else if (!mybutton.keepGoing)
mybutton.keepGoing = true;
mybutton = new Buttonx(/*Icon,*/"My Button");
//getContentPane().remove(mybutton);
//getContentPane().add(mybutton.thebutton);
mybutton.startstop();
}//actionperformed
static void main(String args[])
new buttonxdemo().show();
} //movingicondemo
class Buttonx extends Thread{
public boolean keepGoing;
//public Icon ICx; //perhaps an array, so you can loop through?
public String strbuttonx;
public JButton thebutton; //may have to extend JFrame?
public Buttonx(/*Icon IC,*/ String strbutton){
//ICx = IC;
strbuttonx = strbutton;
thebutton = new JButton(strbuttonx);
public void startstop()
int i = 0;
while (keepGoing)
thebutton.setLabel(strbuttonx.substring(0,i));
//if an array of Icons ICx
//thebutton.setIcon(ICx);
i++;
if (i > strbuttonx.length() - 1)
i = 0;
try
Thread.sleep(1000);
catch (InterruptedException ie)
System.out.println("sleep caught: " + ie);
}//startstop()
}//buttonx
kev -
Change UIDefaults values runtime.
Hi All,
I want to change UIDefaults settings values at runtime on pressing the button event.
setBackground() method works ok. but it changes only particular components color. i want to change the background of all the panels used in the application.
Is it possible??
Please help me.
Sample code is as belove...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
public class Test extends JFrame
public static void main(String args[]) throws Exception
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIDefaults defs = UIManager.getDefaults();
defs.put("Panel.background",Color.BLUE);
Test t = new Test();
t.setVisible(true);
public Test()
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,200);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("Amit"),BorderLayout.CENTER);
JButton button = new JButton("Change color...");
panel.setLayout(new BorderLayout());
button.addActionListener(new ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent e) {
UIDefaults defs = UIManager.getDefaults();
defs.put("Panel.background",Color.RED);
/// no effect.. :(
// Some code to give proper effect ...
panel.add(button,BorderLayout.SOUTH);
getContentPane().add(panel);
}Thanks in advance.
Amit Chudasama
Y! id : amit.chudasamaRead the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html]How to Set the Look and Feel. I believe you would need to use the following after changing the defaults in order for them to be applied to existing components:
SwingUtilities.updateComponentTreeUI(frame); -
How can I add an image to a project and change it at runtime?
I'm using JBuilder6 and I thought I saw a control to add images but I can't find it. I also wanted to be able to change the control at runtime. Also how should I specify the path so it knows how to use it? I hate to hard code one in. Since this is probably gonna be ported to other OS does Java have a way around this? I was going to put the images into my project's directory. For me to be able to just include the file w/the extension do I need to put it in the src folder or will the main directory be accessible?
To add an image, or other source file with JBuilder, you have a button call "Add to project", his icon is a folder with a green cross.
To call the Image os independant, I sugest you to put your images in a folder "image" in your project folder. Then to call them, you could use this :
image=new ImageIcon(AClass.class.getResource("image"+java.io.File.separator+imageName));Where AClass is a class of your project, in general, the class where you call getRessource;
"image" is the name of the under folder where are the image in your project folder;
imageName is a string with the name of the file witch contains the image, for exemple : "my image.gif"I hope I help you.
JHelp. -
I have an object in my java application, and I would like it to move to x,y, and z coordinates that are constantly changed. The problem is that createSceneGraph seems to be called only once, it isn't a constantly updating thing. Here is the code I have so far, does anyone have any ideas on how I could implement this?
The HeliListener interface calls onUpdate(Heli) whenever the position is changed.
import java.awt.GraphicsConfiguration;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.media.j3d.AmbientLight;
import javax.media.j3d.Background;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3f;
import org.Heli;
import org.HeliListener;
import com.sun.j3d.loaders.IncorrectFormatException;
import com.sun.j3d.loaders.ParsingErrorException;
import com.sun.j3d.loaders.Scene;
import com.sun.j3d.loaders.objectfile.ObjectFile;
import com.sun.j3d.utils.behaviors.mouse.MouseRotate;
import com.sun.j3d.utils.behaviors.mouse.MouseTranslate;
import com.sun.j3d.utils.behaviors.mouse.MouseZoom;
import com.sun.j3d.utils.geometry.ColorCube;
import com.sun.j3d.utils.geometry.Sphere;
import com.sun.j3d.utils.universe.PlatformGeometry;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.ViewingPlatform;
public class ObjLoad implements HeliListener {
private double creaseAngle = 60.0;
private URL filename = null;
private SimpleUniverse u;
private BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 600.0);
TransformGroup objTrans;
BranchGroup objRoot;
protected Canvas3D c;
//x, y, and z coordinates of Helicopter
private float x=0,
y=0,
z=1;
private static boolean isFreeLook = true;
public BranchGroup createSceneGraph()
// Create the root of the branch graph
objRoot = new BranchGroup();
// Create a Transformgroup to scale all objects so they
// appear in the scene.
TransformGroup objScale = new TransformGroup();
Transform3D t3d = new Transform3D();
t3d.setScale(0.7);
objScale.setTransform(t3d);
objRoot.addChild(objScale);
// Create the transform group node and initialize it to the
// identity. Enable the TRANSFORM_WRITE capability so that
// our behavior code can modify it at runtime. Add it to the
// root of the subgraph.
objTrans = new TransformGroup();
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
objScale.addChild(objTrans);
int flags = ObjectFile.RESIZE;
flags |= ObjectFile.TRIANGULATE;
//flags |= ObjectFile.STRIPIFY;
ObjectFile f = new ObjectFile(flags, (float)(creaseAngle * Math.PI / 180.0));
Scene s = null;
//Try to load the model
try {
s = f.load(filename);
catch (FileNotFoundException e) {
System.err.println(e);
System.exit(1);
catch (ParsingErrorException e) {
System.err.println(e);
System.exit(1);
catch (IncorrectFormatException e) {
System.err.println(e);
System.exit(1);
//Add the model
objTrans.addChild(s.getSceneGroup());
//Get the black and green grid and add it.
MapGrid grid = new MapGrid();
objRoot.addChild(grid.getGrid());
//Create the background sphere that contains everything. default color is black
Background bg = new Background();
bg.setApplicationBounds(bounds);
BranchGroup backGeoBranch = new BranchGroup();
Sphere sphereObj = new Sphere(1.0f, Sphere.GENERATE_NORMALS |
Sphere.GENERATE_NORMALS_INWARD |
Sphere.GENERATE_TEXTURE_COORDS, 45);
backGeoBranch.addChild(sphereObj);
bg.setGeometry(backGeoBranch);
objTrans.addChild(bg);
//Sets a transform3D so we can modify the placement of the helicopter
Transform3D yAxis = new Transform3D();
objTrans.getTransform(yAxis);
Vector3f v3f = new Vector3f(x,z,y);
yAxis.set(v3f);
objTrans.setTransform(yAxis);
objRoot.compile();
return objRoot;
public ObjLoad(Heli heli)
heli.addListener(this);
//Try to get the full filename
if (filename == null)
try
String path = new File("").getAbsolutePath();
filename = new URL("file://" + path + "/models/Helicopter.obj");
catch (MalformedURLException e)
System.err.println(e);
System.exit(1);
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
c = new Canvas3D(config);
// Create a simple scene and attach it to the virtual universe
BranchGroup scene = createSceneGraph();
u = new SimpleUniverse(c);
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
ViewingPlatform viewingPlatform = u.getViewingPlatform();
viewingPlatform.setNominalViewingTransform();
TransformGroup viewTrans = viewingPlatform.getViewPlatformTransform();
* The following code sets up the scene lighting
//Setup the scene geometry for the lights
PlatformGeometry pg = new PlatformGeometry();
// Set up the ambient light
Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
AmbientLight ambientLightNode = new AmbientLight(ambientColor);
ambientLightNode.setInfluencingBounds(bounds);
pg.addChild(ambientLightNode);
ambientLightNode.setInfluencingBounds(bounds);
// Set up the direction and color of directional lights
Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f);
Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f);
Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f);
//Make the first light
DirectionalLight light1
= new DirectionalLight(light1Color, light1Direction);
light1.setInfluencingBounds(bounds);
pg.addChild(light1);
//Make the second light
DirectionalLight light2
= new DirectionalLight(light2Color, light2Direction);
light2.setInfluencingBounds(bounds);
pg.addChild(light2);
//Add the Platform geometry (containing the lights) to the viewing platform
viewingPlatform.setPlatformGeometry( pg );
// This will move the ViewPlatform back a bit so the
// objects in the scene can be viewed.
viewingPlatform.setNominalViewingTransform();
//Create a branchgroup for the mouse movement
BranchGroup mouseGroup = new BranchGroup();
if(isFreeLook){
//Create the rotate behavior node
MouseRotate behavior1 = new MouseRotate(viewTrans);
behavior1.setSchedulingBounds(bounds);
System.out.println(behavior1.getXFactor() + " "+behavior1.getYFactor());
//Mouse becomes hard to control with default factor, so we scale it down a little, default is .03
behavior1.setFactor(.001,.001);
mouseGroup.addChild(behavior1);
// Create the zoom behavior node
MouseZoom behavior2 = new MouseZoom(viewTrans);
behavior2.setSchedulingBounds(bounds);
mouseGroup.addChild(behavior2);
// Create the translate behavior node
MouseTranslate behavior3 = new MouseTranslate(viewTrans);
behavior3.setSchedulingBounds(bounds);
mouseGroup.addChild(behavior3);
else //(is Centered view)
mouseGroup.compile();
scene.compile();
u.addBranchGraph(scene);
u.addBranchGraph(mouseGroup);
public Canvas3D getCanvas() {
return c;
public void onUpdate(Heli heli)
x = heli.getState().x;
y = heli.getState().y;
z = heli.getState().z;
update(9,9,3);
System.out.println("Entered...");
public void update(float x, float y, float z){
objRoot.removeChild(objTrans);
objTrans = null;
Transform3D yAxis = new Transform3D();
objTrans.getTransform(yAxis);
Vector3f v3f = new Vector3f(x, z, y);
yAxis.set(v3f);
objTrans.setTransform(yAxis);
objRoot.addChild(objTrans);
}Thanks for any help!and I would like it to move to x,y, and z coordinates that are constantly changedYou need to implement a Behavior and attach it to a Node that is a parent to the objects you want to animate. The Behavior framework is really easy to implement and for your implementation you might like to try a WakeupCriterion Object, ie WakeupOnElapsedFrames(0), and keep track of the position in a Transform.
The Behavior leaf node provides a framework for adding user-defined actions into the scene graph. Behavior is an abstract class that defines two methods that must be overridden by a subclass: An initialization method, called once when the behavior becomes "live," and a processStimulus method called whenever appropriate by the Java 3D behavior scheduler. The Behavior node also contains an enable flag, a scheduling region, a scheduling interval, and a wakeup condition.
See the javadoc for javax.media.j3d.Behavior. You might like to look at Alpha as well.
Hope that helps you out.
regards -
How to change line width runtime?
Hi,
I want to change line width dynamically or runtime depending on certain conditions.
I had written format trigger on line and used SRW.SET_BORDER_WIDTH but it does not work. so what is other possible solution for this?
Thanks in advance.In your variable vertical elasticity frame put several fixed vertical elesticity objects (lines, frames, etc.) of different heights. In the runtime, suppress all the objects in their format triggers, but one with the height you need. The objects need to be made invisible by setting their color to white.
-
How to change Labels in runtime ?
Hello,
Is it possible to change the labels in a view dynamically at runtime, based on some conditions?
Regards
AjayHi Sam,
Yes, one way is to use multiple view configuration loaded based on the configuration. Can be done at DO_CONFIG_DETERMINATION method of IMPL class.
Regards,
Harish P M
Maybe you are looking for
-
HT4847 can you share icloud storage space with a family member?
I used to have MobileMe family, and my wife and I are now both receiving alerts that we are running out of icloud space. Can you buy a shared icloud plan? Thanks
-
I've been having a problem forwarding ports in my router...
I've been having a problem forwarding ports in my router WRT160N I enable the ports I want to use for my applications, just after clicking save settings I go back to my port's forwarding section and I don't see any application I add being saved. Plea
-
I purchased a new iMac, I have an old iPod mini I am trying to sync my iTunes library on my new Mac with my iPod. I purchsed additional music yesterday but I cannot get it to sync to load the music from my computer to my iPod.
-
Variable pop-up using Button Group in WAD
Hi experts, I've created a button group in WAD to execute a 'Copy' function developed in IP. This copy function has the following variables: Order From: Order To: Version From: Version To: This button group was created as it should referencing my cop
-
I have exported & imported my developer profile into Xcode. I have rectified the Bundle ID. I cannot get this App to get into distribute mode. Can someone please help me? This is my first time submitting an app and it is starting to get frustrating