BorderLayout not working??
here is the code i am having trouble with:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JPaint extends JFrame{
static Palette plt;
/** Creates a new instance of JPaint */
public JPaint() {
super("JPaint");
Container c = this.getContentPane();
PaintPanel p = new PaintPanel();//create test panel to paint on
plt = new Palette();//colour palette
c.add(plt, BorderLayout.SOUTH);
c.add(p, BorderLayout.CENTER);
public static void main(String[] args){
JPaint frm = new JPaint();
frm.setSize(640, 480);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}for some reason the BorderLayout isn't working.
only the component placed in BorderLayout.CENTER is showing up.
when i switch the two components around, still only the one in CENTER shows up so i know it isnt to do with the component.
this has never happened before, whats going on?
Ok this really is as simple as i can make it:
Class: JPaint
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
public class JPaint extends JFrame{
Palette plt;
/** Creates a new instance of JPaint */
public JPaint() {
super("JPaint");
Container c = this.getContentPane();
plt = new Palette();//colour palette
PaintPanel p = new PaintPanel(plt);//create test panel to paint on
p.setBorder(new LineBorder(Color.GRAY, 1));
c.add(plt, BorderLayout.SOUTH);
c.add(p, BorderLayout.CENTER);
public static void main(String[] args){
JPaint frm = new JPaint();
frm.setSize(640, 480);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}Class PaintPanel:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PaintPanel extends JPanel implements MouseMotionListener, MouseListener{
int toolNum;
int pointNum;
int[] xPoints;
int[] yPoints;
Point point;
int mouseButton;
Palette plt;
public PaintPanel(Palette plt) {
this.plt = plt;
toolNum = 0;
mouseButton = 0;
pointNum = 0;
xPoints = new int[1000];//array of ypoints and xpoints for freehand lines
yPoints = new int[1000];
addMouseListener(this);//add listeners
addMouseMotionListener(this);
public void mouseMoved(MouseEvent e){
public void mouseDragged(MouseEvent e){
point = e.getPoint();
if(SwingUtilities.isLeftMouseButton(e)){
mouseButton = 0;
} else{
mouseButton = 1;
if(toolNum == 0) {//freehand line
try{
xPoints[pointNum] = point.x;//add this point to xpoints/ypoints
yPoints[pointNum] = point.y;
pointNum++;//add 1 to number of points
} catch(ArrayIndexOutOfBoundsException ex){//if exceeds 1000 points
pointNum = pointNum-1;
mouseReleased(e);//call mouse released to reset
repaint();
public void mouseExited(MouseEvent e){
public void mouseEntered(MouseEvent e){
public void mouseReleased(MouseEvent e){
if(toolNum == 0) {
pointNum = 0;//reset point nums, xpoints and ypoints
xPoints = new int[1000];
yPoints = new int[1000];
repaint();
public void mouseClicked(MouseEvent e){
public void mousePressed(MouseEvent e){
public void paintComponent(Graphics g){
if(mouseButton ==0){
g.setColor(plt.getCurrentColor());//for drawing while dragging
} else{
g.setColor(plt.getSecondColor());
g.drawPolyline(xPoints, yPoints, pointNum);
}class: Palette
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Palette extends JPanel {
Color current;//current colour
Color secondary;
JButton addButton, removeButton;
JPanel gridPanel;
public Palette(){
current = Color.BLACK;
secondary = Color.WHITE;
gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(2, 10));
this.setLayout(null);
this.setSize(100, 100);
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i = gridPanel.getComponentCount();
addButton.setContentAreaFilled(false);
removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
removeButton.setContentAreaFilled(false);
resizeGrid();
gridPanel.setLocation(20, 5);
addButton.setSize(80, 15);
addButton.setLocation(20, 35);
removeButton.setSize(100, 15);
removeButton.setLocation(100, 35);
add(gridPanel);
add(addButton);
add(removeButton);
public void setCurrentColor(Color c){
current = c;
public Color getCurrentColor(){
return current;
public void setSecondColor(Color c){
secondary = c;
public Color getSecondColor(){
return secondary;
public void resizeGrid(){
int i = gridPanel.getComponentCount();
if(i%2 == 0) {
gridPanel.setSize((i/2)*15, 30);
} else{
gridPanel.setSize(((i+1)/2)*15, 30);
}
Similar Messages
-
Swing components in applet not working in web browser
Hi Guys,
I've created an applet which makes use of some swing components, but unfortunately, not all of them function properly in my web browser (internet explorer or Mozilla Firefox). Its mainly the buttons; the last buttons works and displays the correct file within the broswer, but the first 5 buttons do not work...
any help please on how I can sort this problem out?
Heres the code for my applet:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class MainAppWindow extends JApplet
int gapBetweenButtons = 5;
final JPanel displayPanel = new JPanel(new BorderLayout());
public void init()
//Panel for overall display in applet window.
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/smalllogo2.gif"))),BorderLayout.NORTH);
//sub mainPanel which holds all mainPanels together.
JPanel holdingPanel = new JPanel(new BorderLayout());
//Panel for displaying all slide show and applications in.
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon(getClass().getResource("images/IntroPage.jpg"))),BorderLayout.CENTER);
displayPanel.setPreferredSize(new Dimension(590,400));
JPanel buttonPanel = new JPanel(new GridLayout(6,1,0,gapBetweenButtons));
buttonPanel.setBackground(Color.white);
JButton button1 = new JButton("User guide");
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll(); // If there are any components in the mainPanel, remove them and then add label
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/UserGuide.jpg")));
displayPanel.revalidate(); // Validates displayPanel to allow changes to occur onto it, allowing to add different number images/applicaions to it.
JButton button2 = new JButton("What is a Stack?");
button2.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/WhatIsAStack.jpg")));
displayPanel.revalidate();
JButton button3 = new JButton("STACK(ADT)");
button3.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/StackADT.jpg")));
displayPanel.revalidate();
JButton button4 = new JButton("Stacks in the Real World");
button4.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
displayPanel.setBackground(Color.white);
displayPanel.add(new JLabel(new ImageIcon("images/StacksInTheRealWorld.jpg")));
displayPanel.revalidate();
JButton button5 = new JButton("DEMONSTRATION");
button5.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
Demonstration app = new Demonstration();
JPanel appPanel = app.createComponents();//gets the created components from Demonstration application.
appPanel.setBackground(Color.pink);
displayPanel.add(appPanel);
displayPanel.revalidate();
JButton button6 = new JButton("Towers Of Hanoi");
button6.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
if(displayPanel.getComponents().length > 0)displayPanel.removeAll();
TowerOfHanoi app = new TowerOfHanoi();
JPanel appPanel = app.createComponents();//gets the created components from Towers of Hanoi
JPanel mainPanel = new JPanel();//panel used to centralise the application in center
mainPanel.add(appPanel);
mainPanel.setBackground(Color.pink); //sets mainPanel's background color for 'Towers Of Hanoi'
displayPanel.add(mainPanel);
displayPanel.revalidate();
//adding buttons to the buttonPanel.
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(button4);
buttonPanel.add(button5);
buttonPanel.add(button6);
JPanel p = new JPanel(); // Used so that the buttons maintain their default shape
p.setBackground(Color.white);
p.add(buttonPanel);
holdingPanel.add(p,BorderLayout.WEST);
holdingPanel.add(displayPanel,BorderLayout.CENTER);
//Positioning of holdingPanel in mainPanel.
mainPanel.add(holdingPanel,BorderLayout.CENTER);
//indent mainPanel so that its not touching the applet window frame.
mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
mainPanel.setBackground(Color.white);
mainPanel.setPreferredSize(new Dimension(850,600)); //size of applet window
mainPanel.setOpaque(false); // Needed for Applet
this.setContentPane(mainPanel);
}Thanks for the response. I don't quite understand what you're talking about though. I have, in my humble knowledge, done nothing with packages. I have put the applet class (WiaRekenToolActiz.class is the applet class) in the jar file wia_actiz_archive.jar. From what I read on the tutorial, java looks for the applet class in all the jar files specified. Since I put my CODEBASE as the main url, I thought it baiscally didn't matter where you out the html file.
I shall include the complete html page complete with applet tag to perhaps illuminate a bit more what I mean...
<html>
<head>
<title>Wia Rekenmodule hello!</title>
</head>
<body bgcolor="#C0C0C0">
<applet
CODEBASE= "http://www.creativemathsolutions.nl/test"
ARCHIVE= "Actiz/wia_actiz_archive.jar, Generic/wia_archive.jar"
CODE="WiaRekenToolActiz.class"
WIDTH=915 HEIGHT=555
>
<PARAM NAME = naam VALUE = "Piet Janssen">
<PARAM NAME = gebdag VALUE = "01">
<PARAM NAME = gebmaand VALUE = "06">
<PARAM NAME = gebjaar VALUE = "1970">
<PARAM NAME = geslacht VALUE = "man">
<PARAM NAME = dienstjaren VALUE = "10">
<PARAM NAME = salaris VALUE = "56500">
<PARAM NAME = deeltijdpercentage VALUE = "100">
<PARAM NAME = accountnaam VALUE = "Zorginstelling 'De Zonnebloem'">
</applet>
</body>
</html> -
Links not working in executable jar
I have a problem with my java application
html and images files do not work in executable jar
though the application works normally
I tried some suggestion but I received an exception thread indicating problem at
ImageIcon iChing = new ImageIcon(imageURL);
Please could you help me thank you so much
here is the class
public class Main extends JFrame
* objects required for the GUI: JFrame,JLabel, JButton, ImageIcon, JPanel,
* Dimension
private static final long serialVersionUID = 1L;
JButton jbEnter;
ImageIcon iChing, logo;
JPanel buttonPanel, ImagePanel;
JLabel jlbIching;
Dimension dim;
URL imageURL;
File fileName;
// Class constructor to create the GUI
public Main()
Container container = getContentPane();
URL imageURL = this.getClass().getClassLoader().getResource("src/myFiles/iching.gif");
ImageIcon iChing = new ImageIcon(imageURL);
jlbIching = new JLabel(iChing);
// button to go to the Title class
jbEnter = new JButton("Enter ");
jbEnter.setBorderPainted(false);
jbEnter.setFont(new Font("Edwardian Script ITC", Font.BOLD, 42));
jbEnter.setBackground(new Color(0, 0, 50));
jbEnter.setForeground(Color.YELLOW);
jbEnter.addActionListener(new ActionListener() {
// method to render the current frame invisible and trigger the
// Welcome Menu
public void actionPerformed(ActionEvent e)
setVisible(false);
// this line does not work...............
new Title();
} // close the actionPerformed(ActionEvent e) Method
}); // close the addActionListener(new ActionListener() method
// Panel holding the decorative image and Button
ImagePanel = new JPanel();
ImagePanel.add(jlbIching);
ImagePanel.setBackground(new Color(0, 0, 50));
buttonPanel = new JPanel();
buttonPanel.add(jbEnter);
buttonPanel.setBackground(new Color(0, 0, 50));
// setting up of the panels position
container.add(ImagePanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.SOUTH);
dim = Toolkit.getDefaultToolkit().getScreenSize();
dim.width = dim.width / 2 - 300;
dim.height = dim.height / 2 - 250;
setBounds(dim.width, dim.height, 400, 400);
setSize(600, 500);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//To set the icon for the application. Top left hand corner.
//this.setIconImage(Image);
setIconImage(new ImageIcon("src/myFiles/ichingRose.gif").getImage());
} // close the Constructor
* the main method for the program.
* @param args
* The command-line arguments.
public static void main(String[] args)
new Main();
} // close the main method
} // close the Main classThank you very much for your quick reply and really hope you can help me a little more
it's so frustrating
I do not really know about the relative path but here is my xml file
<?xml version="1.0" encoding="UTF-8" ?>
<project default="jar">
<!-- Compile and zip the source code into a jar -->
<target name="jar">
<!-- Make the folders we'll need -->
<mkdir dir="ant"/>
<mkdir dir="work"/>
<mkdir dir="ant/myFiles"/
<!--
Compile all the .java files into .class files
debug = yes Include debug information in the .class files
destdir Where to put the .class files
source and target Use Java version 1.6.0_06
-->
<javac
debug="yes"
destdir="ant"
source="1.6"
target="1.6">
<!-- Folders that have trees of .java files to compile -->
<src path="src"/>
</javac>
<copy todir="ant/myFiles"><fileset dir="src/myFiles"></fileset></copy>
<!--
Zip files together to make a jar
jarfile Where to make the .jar file, overwrite something there
basedir Find the files to zip in the jar here
-->
<jar
jarfile="work/BookOfChanges.jar"
basedir="ant"
>
<!-- Write a manifest inside the jar -->
<manifest>
<!-- The class Java will run when the user double-clicks the jar -->
<attribute name="Main-Class" value="iChing.Main"/>
</manifest>
</jar>
</target>
</project> -
Web Cam applet is not working in great consistency
Hi... My video capturing applet is not working very well.
The image stream is displayed on the web page in JPEG format with 0.5 quality. However, it crashes after a while and the it does not release the vfw resource.
I have to restart my machine in order to execute it again.
Can anyone please help?
Thanks.
CarterOk. Thanks.
Sender Applet
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="myGUIApplet.class" width="300" height="300"></applet>*/
public class myGUIApplet extends JApplet implements ActionListener
private JPanel bottom=new JPanel();
private JPanel centVisual=new JPanel();
private JPanel connectionAddress=new JPanel();
private JButton capture=new JButton("Start Capturing");
private JButton stops=new JButton("Stop");
private JMenuBar menubar=new JMenuBar();
private JMenu file=new JMenu("file");
private JMenuItem fileItem1=new JMenuItem("Exit");
private JLabel serverip=new JLabel("Server IP");
private JTextField setIP=new JTextField();
public static JTextField ServerInfo=new JTextField();
private MyTransmitter mytrans;
private String ip;
public static final String DEFAULT_MULTICAST_IP="226.10.10.20";
public static final String DEFAULT_PORT="80";
public void init()
//setSize(400,400);
setLayout(new BorderLayout());
menubar.add(file);
file.add(fileItem1);
bottom.setLayout(new BorderLayout());
bottom.setBackground(Color.black);
bottom.add("West",capture);
bottom.add("East",stops);
connectionAddress.setLayout(new BorderLayout());
connectionAddress.add("North",serverip);
connectionAddress.add("South",setIP);
ServerInfo.setEditable(false);
connectionAddress.add("Center",ServerInfo);
setIP.addActionListener(this);
setIP.setText("");
capture.setBackground(Color.lightGray);
capture.addActionListener(this);
stops.addActionListener(this);
fileItem1.addActionListener(this);
add("South",bottom);
add("North",menubar);
add("Center",connectionAddress);
public void actionPerformed(ActionEvent ae){
Object source=ae.getSource();
if(source==capture){
if(setIP.getText().equals(""))
ip=DEFAULT_MULTICAST_IP;
else{
ip=setIP.getText();
if(mytrans!=null){
mytrans.stopTransmitter();
mytrans=null;
System.out.println(" - Connecting to "+ip+" port: "+DEFAULT_PORT);
ServerInfo.setText(" - Connecting to "+ip+" port: "+DEFAULT_PORT);
mytrans=new MyTransmitter(ip,DEFAULT_PORT,ServerInfo);
mytrans.start();
if(source==stops){
if(mytrans!=null)
mytrans.stopTransmitter();
System.exit(0);
if(source==fileItem1){
if(mytrans!=null)
mytrans.stopTransmitter();
System.exit(0);
public void destroy(){
if(mytrans!=null){
mytrans.stopTransmitter();
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;
import javax.media.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.format.*;
import javax.media.control.TrackControl;
import javax.media.control.QualityControl;
import javax.media.rtp.*;
import javax.media.rtp.rtcp.*;
import javax.media.rtp.*;
import java.io.InputStream;
import javax.media.rtp.RTPManager;
public class MyTransmitter extends Thread
private MediaLocator videoLocator;
private String ipAddress;
private int basePort;
private Integer stateLock=new Integer(0);
private boolean failure;
private Processor processor;
private DataSource videoDataInput,videoDataOutput;
private RTPManager rtpMgrs[];
private VideoFormat JPEG_VIDEO=new VideoFormat(VideoFormat.JPEG_RTP);
private SendStream sendStream;
private SourceDescription descriptionList[];
private JTextField infoField;
public MyTransmitter(String ips,String ports,JTextField ServerInfo){
infoField=ServerInfo;
ipAddress=ips;
Integer bPort=Integer.valueOf(ports);
if(bPort!=null)
basePort=bPort.intValue();
public void run()
initializeVideo();
if(videoLocator!=null){
createMyProcessor();
createMyManager();
// May be should put inside the if..else statements
//createMyTransmitter();
// Initailize the video
public void initializeVideo()
// Stre the devices in a vector
VideoFormat format=new VideoFormat(VideoFormat.RGB);
Vector deviceList=CaptureDeviceManager.getDeviceList(format);
CaptureDeviceInfo deviceInfo=null;
// If there is more than one device detected
if(deviceList.size()>0){
// Set the first device to device Info
// GEt the media locator of the devie
deviceInfo=(CaptureDeviceInfo)deviceList.elementAt(0);
videoLocator=deviceInfo.getLocator();
}else{
System.out.println(" --X No device found...");
infoField.setText(" --X No device found...");
public void createMyProcessor()
boolean result=false;
DataSource ds=null;
// Check if the media locator is null
if(videoLocator==null){
System.out.println(" --X No video locator..");
infoField.setText(" --X No video locator...");
System.out.println(" - Trying to create a Processor..");
infoField.setText(" - Trying to create a Processor..");
// Attempt to create DataSource from media locator
try{
ds=Manager.createDataSource(videoLocator);
}catch(Exception ex){
System.out.println(" --X Unable to create dataSource : "+ex.getMessage());
System.out.println(" - Video data source is created..");
infoField.setText(" - Video data source is created..");
// Try to create Processor from DataSource
try{
processor=Manager.createProcessor(ds);
}catch(NoProcessorException npe){
System.out.println(" --X Unable to create Processor: "+npe.getMessage());
infoField.setText(" --X Unable to create Processor: "+npe.getMessage());
catch(IOException ioe){
System.out.println(" --X IOException creating Processor..");
infoField.setText(" --X IOException creating Processor..");
// Wait for the processor to be configured
result=waitForState(processor,Processor.Configured);
if(result==false){
System.out.println(" --X Could not configure processor..");
infoField.setText(" --X Could not configure processor..");
// Set the track controls for processor
TrackControl []tracks=processor.getTrackControls();
if(tracks==null || tracks.length<1){
System.err.println(" --X No track is found..");
infoField.setText(" --X No track is found..");
// Set the content description of processor to RAW_RTP format
// This will limit the supported formats to reported from
// Track.getSupportedFormats() to valid RTP format
ContentDescriptor cdes=new ContentDescriptor(ContentDescriptor.RAW_RTP);
processor.setContentDescriptor(cdes);
Format []supported;
Format chosen=null;
boolean atLeastOneTrack=false;
for(int i=0;i<tracks.length;i++){
Format format=tracks.getFormat();
if(tracks[i].isEnabled()){
supported=tracks[i].getSupportedFormats();
// WE've set the output content to RAW_RTP.
// So, all the supporte formats should work with RAW_RTP.
// We will pick the first one.
if(supported.length>0){
if(supported[0] instanceof VideoFormat){
chosen=checkVideoSize(tracks[i].getFormat(),supported[0]);
}else
chosen=supported[0];
tracks[i].setFormat(chosen);
System.out.println(" Track "+i+" is transmitted in "+chosen+" format.. ");
infoField.setText(" Track "+i+" is transmitted in "+chosen+" format.. ");
atLeastOneTrack=true;
}else{
// If no format is suitable, track is disabled
tracks[i].setEnabled(false);
}else
tracks[i].setEnabled(false);
if(!atLeastOneTrack)
System.out.println("atLeastOneTrack: "+atLeastOneTrack);
System.out.println(" --X Could Not find track to RTP format..");
infoField.setText("atLeastOneTrack: "+atLeastOneTrack);
infoField.setText(" --X Could Not find track to RTP format..");
result=waitForState(processor,Controller.Realized);
if(result==false){
System.out.println(" --X Could NOT realize processor...");
infoField.setText(" --X Could NOT realize processor...");
// Set the JPEG Quality to value 0.5
setJPEGQuality(processor,0.5f);
// Set the output Data Source
videoDataOutput=processor.getDataOutput();
//Start the processor
processor.start();
public void setJPEGQuality(Processor p,float values)
Control []cs=p.getControls();
QualityControl qc=null;
VideoFormat JPEGFmt=new VideoFormat(VideoFormat.JPEG);
// Loop through the ocntrols to find the Quality control for the JPEG encoder
for(int i=0;i<cs.length;i++){
if(cs[i] instanceof QualityControl && cs[i] instanceof Owned){
Object owner=((Owned)cs[i]).getOwner();
// Check if the owner is the Codec
// Check the format of output as well
if(owner instanceof Codec){
Format fmts[]=((Codec)owner).getSupportedOutputFormats(null);
// Loop through the supported format and set the quality to 0.5
for(int j=0;j<fmts.length;j++){
qc=(QualityControl)cs[i];
qc.setQuality(values);
System.out.println(" - Quality is set to "+values+" on "+qc);
infoField.setText(" - Quality is set to "+values+" on "+qc);
break;
if(qc!=null)
break;
public Format checkVideoSize(Format originalFormat,Format supported)
int width,height;
Dimension size=((VideoFormat)originalFormat).getSize();
Format jpegFormat=new Format(VideoFormat.JPEG_RTP);
Format h263fmt=new Format(VideoFormat.H263_RTP);
if(supported.matches(jpegFormat)){
width=(size.width%8 == 0 ? size.width:(int)(size.width%8)*8);
height=(size.height%8 == 0 ? size.height:(int)(size.height%8)*8);
}else if(supported.matches(h263fmt)){
if(size.width<128){
width=128;
height=96;
}else if(size.width<176){
width=176;
height=144;
}else{
width=352;
height=288;
}else{
// Unknown format, just return it.
return supported;
return (new VideoFormat(null,new Dimension(width,height),Format.NOT_SPECIFIED,null,Format.NOT_SPECIFIED)).intersects(supported);
public boolean waitForState(Processor p,Integer status)
p.addControllerListener(new StateListener());
failure=false;
if(status==Processor.Configured){
p.configure();
}else if(status==Processor.Realized){
p.realize();
//Wait until an event that confirms the success of the method, or failure of an event
while(p.getState()<status && !failure){
synchronized(getStateLock()){
try{
// Wait
getStateLock().wait();
}catch(InterruptedException ie){
return false;
if(failure)
return false;
else
return true;
public Integer getStateLock(){
return stateLock;
public void setFailure(){
failure=true;
public void createMyManager()
SessionAddress destAddress;
InetAddress ipAddr;
int port;
SourceDescription srcDesList[];
PushBufferDataSource pbds=(PushBufferDataSource)videoDataOutput;
PushBufferStream pbss[]=pbds.getStreams();
rtpMgrs=new RTPManager[pbss.length];
for(int a=0;a<pbss.length;a++){
try{
// RTP Managers or RTP Manager?????
rtpMgrs[a]=RTPManager.newInstance();
port=basePort;
ipAddr=InetAddress.getByName(ipAddress);
SessionAddress localAddr=new SessionAddress(InetAddress.getLocalHost(),port+20);
destAddress=new SessionAddress(ipAddr,port,1);
Integer myipprefix=Integer.valueOf(ipAddress.substring(0,3));
if((myipprefix.intValue()>223) && (myipprefix.intValue()<240)){
rtpMgrs[a].initialize(destAddress);
}else{
rtpMgrs[a].initialize(localAddr);
rtpMgrs[a].addTarget(destAddress);
System.out.println(" Created RTP session: "+ipAddress+" "+port+" to "+destAddress);
infoField.setText(" Created RTP session: "+ipAddress+" "+port+" to "+destAddress);
if(videoDataOutput!=null){
sendStream=rtpMgrs[a].createSendStream(videoDataOutput,0);
sendStream.start();
System.out.println(" RTP stream is started..");
infoField.setText(" RTP stream is started..");
}catch(UnsupportedFormatException ex){
System.out.println(" --X Unsupported Format : "+ex);
infoField.setText(" --X Unsupported Format : "+ex);
catch(IOException ioe){
System.out.println(" --X IOException : "+ioe.getMessage());
infoField.setText(" --X IOException : "+ioe.getMessage());
catch(Exception ex){
System.out.println(" --X Unable to create RTP Manager...");
System.out.println(ex.getMessage());
infoField.setText(" --X Unable to create RTP Manager..."+ex.getMessage());
/*public void createMyTransmitter()
try{
if(videoDataOutput!=null){
sendStream=rtpMgrs[i].createSendStream(videoDataOutput,0);
sendStream.start();
}catch(UnsupportedFormatException ex){
System.out.println(" --X Unsupported Format : "+ex);
infoField.setText(" --X Unsupported Format : "+ex);
catch(IOException ioe){
System.out.println(" --X IOException : "+ioe.getMessage());
infoField.setText(" --X IOException : "+ioe.getMessage());
public void stopTransmitter(){
if(processor!=null){
processor.stop();
processor.close();
processor=null;
// Loop through RTP Managers and close all managers..
// Dispose them for garbage collection
for(int i=0;i<rtpMgrs.length;i++){
rtpmgrs[i].removeSendStream(this);
rtpMgrs[i].removeTargets("Session ended..");
rtpMgrs[i].dispose();
//rtpMgrs.removeTargets("Session ended..");
//rtpMgrs.dispose();
* StateListener class to handle Controller events
class StateListener implements ControllerListener{
public void controllerUpdate(ControllerEvent ce){
if(ce instanceof ControllerClosedEvent){
processor.close();
/* Handle all controller events and notify all
waiting thread in waitForState method */
if(ce instanceof ControllerEvent){
synchronized(getStateLock()){
getStateLock().notifyAll();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Client Applet
import javax.media.*;
import javax.media.protocol.*;
import javax.media.protocol.DataSource;
import javax.media.control.BufferControl;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.rtp.*;
import javax.media.rtp.rtcp.*;
import javax.media.rtp.event.*;
import com.sun.media.rtp.RTPSessionMgr;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.net.URL;
import java.net.Socket;
/*<applet code="clientPlayerApplet.class" width="400" height="300">
<param name=ServerIPS value="192.168.0.9">
<param name=ServerPort value="80">
<param name=TimeToLive value="1">
<param name=archive value="clientPlayerApplet.jar">
</applet> */
public class clientPlayerApplet extends JApplet implements ControllerListener, ReceiveStreamListener,SessionListener
String sessions[]=null;
RTPManager rtpmgrs[]=null;
boolean dataReceived=false;
Object myDataSync=new Object();
private Player player;
//private String serveripadd="226.10.10.20";
//private int serverPort=2020;
//private int timeToLive=1;
private JPanel panel;
private Vector currentParticipant;
public void init()
panel=new JPanel();
setLayout(new BorderLayout());
add("Center",panel);
//String[] urls;
/*urls[0]=getParameter("ServerIPS");
urls[1]="/";
urls[2]=getParameter("ServerPort");*/
String []urls={new String(getParameter("ServerIPS")+"/"+getParameter("ServerPort")+"/"+getParameter("TimeToLive"))};
sessions=urls;
initializePlayer();
public void initializePlayer(){
try{
InetAddress ipAddr;
SessionAddress localAddr=new SessionAddress();
SessionAddress destAddr;
rtpmgrs=new RTPManager[sessions.length];
currentParticipant=new Vector();
//rtpmgrs=new RTPManager();
SessionLabel session=null;
//Open RTP session
for(int i=0;i<sessions.length;i++){
try{
session=new SessionLabel(sessions[i]);
//session=new SessionLabel(sessions);
}catch(IllegalArgumentException iae){
System.out.println(" --X Unable to parse the sesion address given");
System.out.println(" - Open RTP session for "+session.port);
rtpmgrs[i]=(RTPManager) RTPManager.newInstance();
rtpmgrs[i].addSessionListener(this);
rtpmgrs[i].addReceiveStreamListener(this);
ipAddr=InetAddress.getByName(session.addr);
if(ipAddr.isMulticastAddress()){
localAddr=new SessionAddress(ipAddr,session.port,session.ttl);
destAddr=new SessionAddress(ipAddr,session.port,session.ttl);
}else{
localAddr=new SessionAddress(InetAddress.getLocalHost(),session.port);
destAddr=new SessionAddress(ipAddr,session.port);
rtpmgrs[i].initialize(localAddr);
BufferControl bc=(BufferControl)rtpmgrs[i].getControl("javax.media.control.BufferControl");
if(bc!=null)
bc.setBufferLength(600);
rtpmgrs[i].addTarget(destAddr);
}catch(Exception ex){
System.out.println(" --X Cannot create RTP Session "+ex.getMessage());
long currentTime=System.currentTimeMillis();
long waitingDuration=10000;
try{
synchronized(myDataSync){
while(!dataReceived && (System.currentTimeMillis() - currentTime < waitingDuration)){
if(!dataReceived){
myDataSync.wait(1000);
}catch(Exception ex){
System.out.println(" --X myDataSync interrupted...");
if(!dataReceived){
System.out.println(" No RTP Stream Data is received.." );
public void destroy()
for(int i=0;i<currentParticipant.size();i++){
//if(player!=null)
((MyPlayList)currentParticipant.elementAt(i)).close();
// Loop through the RTP Managers
// -> Remove the stream listener
// -> Remove the target address
// -> Dispose the RTP Manager for garbage collection
currentParticipant.removeAllElements();
for(int i=0;i<rtpmgrs.length;i++){
if(rtpmgrs[i]!=null){
rtpmgrs[i].removeReceiveStreamListener(this);
rtpmgrs[i].removeTargets(" Closing session..");
rtpmgrs[i].dispose();
rtpmgrs[i]=null;
MyPlayList find(Player pl){
for(int i=0;i<currentParticipant.size();i++){
MyPlayList mpl=(MyPlayList)currentParticipant.elementAt(i);
if(mpl.clientPlay==pl)
return mpl;
return null;
MyPlayList find(ReceiveStream rs){
for(int i=0;i<currentParticipant.size();i++){
MyPlayList mpl=(MyPlayList)currentParticipant.elementAt(i);
if(mpl.stream==rs)
return mpl;
return null;
* ReceiveStream Listener function *
public synchronized void update(ReceiveStreamEvent rse)
RTPManager mgr=(RTPManager)rse.getSource();
ReceiveStream stream=rse.getReceiveStream();
Participant participant=rse.getParticipant();
if(rse instanceof RemotePayloadChangeEvent){
System.out.println(" -- Received Payload Change Event..");
System.out.println(" Sorry, no payload change is allowed.");
}else if(rse instanceof NewReceiveStreamEvent){
try{
// Once the new stream is detected, create the datasource
stream=((NewReceiveStreamEvent)rse).getReceiveStream();
DataSource outputDS=stream.getDataSource();
// Get RTP Controller to find the format
RTPControl rtpctl=(RTPControl)outputDS.getControl("javax.media.rtp.RTPControl");
if(rtpctl!=null){
System.out.println(" -> Received new rtP stream: "+rtpctl.getFormat());
}else
System.out.println(" -> Received new RTP stream");
if(participant!=null){
System.out.println(" -> New stream received from: "+participant.getCNAME());
}else{
System.out.println(" -> New stream detected... ");
player=Manager.createPlayer(outputDS);
if(player==null)
return;
System.out.println(" - Player is created...");
player.addControllerListener(this);
player.realize();
// Helper class to identify the player and stream
MyPlayList mpl=new MyPlayList(player,stream);
// Add the helper class object to Vector
currentParticipant.addElement(mpl);
// Notify initializePlayer() that a new stream has arrived
synchronized(myDataSync){
dataReceived=true;
myDataSync.notifyAll();
}catch(Exception ex){
System.out.println(" --X NewReceiveStream Exception: "+ex.getMessage());
return;
}else if(rse instanceof ByeEvent){
System.out.println(" - BYE packet received from "+participant.getCNAME());
MyPlayList mpls=find(stream);
if(player!=mpls){
mpls.close();
currentParticipant.removeElement(mpls);
if(mgr!=null){
mgr.removeReceiveStreamListener(this);
mgr.removeTargets(" Closing session..");
mgr.dispose();
mgr=null;
}else if(rse instanceof StreamMappedEvent){
if(stream!=null && stream.getDataSource()!=null){
DataSource myds=stream.getDataSource();
RTPControl rtpctrl=(RTPControl)myds.getControl("javax.media.rtp.RTPControl");
System.out.println(" -> The previously unidentified stream ");
if(rtpctrl!=null)
System.out.println(" "+rtpctrl.getFormat());
System.out.println(" has been identified as sent by :"+participant.getCNAME());
* Session Listener
public void update(SessionEvent sesevt)
if(sesevt instanceof NewParticipantEvent){
Participant part=((NewParticipantEvent)sesevt).getParticipant();
System.out.println(" -> A new partcipant has joined :"+part.getCNAME());
* ControllerListener for Players
public synchronized void controllerUpdate(ControllerEvent ce)
Player p=(Player)ce.getSource();
if(p==null)
return;
if(ce instanceof RealizeCompleteEvent){
MyPlayList mpls=find(p);
if(mpls!=null){
p.start();
if(p.getVisualComponent()!=null){
panel.add(player.getVisualComponent());
panel.validate();
if(ce instanceof ControllerErrorEvent){
p.removeControllerListener(this);
MyPlayList mpls=find(p);
if(mpls!=null){
// Close the player
// Remove the player helper class object from the list
p.close();
currentParticipant.removeElement(mpls);
System.out.println("Receiver internal error: "+ce);
class SessionLabel{
public String addr=null;
public int port;
public int ttl;
SessionLabel(String session) throws IllegalArgumentException
int off;
String portStr=null;
String ttlStr=null;
if(session!=null && session.length() >0){
while(session.length()>1 && session.charAt(0)=='/')
session=session.substring(1);
off=session.indexOf('/');
if(off==-1){
if(!session.equals(""))
addr=session;
}else{
addr=session.substring(0,off);
session=session.substring(off+1);
off=session.indexOf('/');
if(off==-1){
if(!session.equals(""))
portStr=session;
}else{
portStr=session.substring(0,off);
session=session.substring(off+1);
off=session.indexOf('/');
if(off==-1){
if(!session.equals(""))
ttlStr=session;
}else{
ttlStr=session.substring(0,off);
if(addr==null)
throw new IllegalArgumentException();
if(portStr!=null)
try{
Integer ints=Integer.valueOf(portStr);
if(ints!=null)
port=ints.intValue();
}catch(Throwable t){
System.out.println(" --X PortStr Error..");
throw new IllegalArgumentException();
}else
throw new IllegalArgumentException();
if(ttlStr!=null){
try{
Integer intsttl=Integer.valueOf(ttlStr);
if(intsttl!=null)
ttl=intsttl.intValue();
}catch(Throwable t){
System.out.println(" --X PortStr Error..");
throw new IllegalArgumentException();
class MyPlayList{
Player clientPlay;
ReceiveStream stream;
MyPlayList(Player p,ReceiveStream rs){
clientPlay=p;
stream=rs;
public void close()
clientPlay.close(); -
Why table getWidth and setWidth is not working when resize column the table
hi all,
i want to know why the setWidth is not working in the following code,
try to uncomment the code in columnMarginChanged method and run it wont resize the table.
i cont set width(using setWidth) of the other table column using getWidth of the main table column.
and i want to resize the right side columns only (you can check when you resize the any column the left and right side columns also resizing)
any suggestions could be helpful.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumnModel;
public class SynTableResize extends JFrame implements TableColumnModelListener, ActionListener
JTable table1 = new JTable(5, 5);
JTable table2 = new JTable(5, 5);
JTable table3 = new JTable(5, 5);
JButton btn = new JButton("refresh");
JPanel pnlcontainer = new JPanel();
public SynTableResize()
setLayout(new BorderLayout());
pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
pnlcontainer.add(table1.getTableHeader());
pnlcontainer.add(Box.createVerticalStrut(5));
pnlcontainer.add(table2);
pnlcontainer.add(Box.createVerticalStrut(5));
pnlcontainer.add(table3);
table2.setTableHeader(null);
table3.setTableHeader(null);
table1.getColumnModel().addColumnModelListener(this);
table3.setColumnModel(table1.getColumnModel());
table2.setColumnModel(table1.getColumnModel());
table2.getColumnModel().addColumnModelListener(table1);
table3.getColumnModel().addColumnModelListener(table1);
btn.addActionListener(this);
getContentPane().add(pnlcontainer, BorderLayout.CENTER);
getContentPane().add(btn, BorderLayout.SOUTH);
setSize(new Dimension(400, 400));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String[] args)
new SynTableResize();
public void columnAdded(TableColumnModelEvent e)
public void columnMarginChanged(ChangeEvent e)
TableColumnModel tcm = table1.getColumnModel();
int columns = tcm.getColumnCount();
for (int i = 0; i < columns; i++)
table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getWidth());
// the following commented code wont work.
// table2.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
// table3.getColumnModel().getColumn(i).setPreferredWidth(tcm.getColumn(i).getPreferredWidth());
// table2.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
// table3.getColumnModel().getColumn(i).setWidth(tcm.getColumn(i).getWidth());
SwingUtilities.invokeLater(new Runnable()
public void run()
table2.revalidate();
table3.revalidate();
public void columnMoved(TableColumnModelEvent e)
public void columnRemoved(TableColumnModelEvent e)
public void columnSelectionChanged(ListSelectionEvent e)
public void actionPerformed(ActionEvent e)
JTable table = new JTable(5, 5);
table.setColumnModel(table1.getColumnModel());
table.getColumnModel().addColumnModelListener(table1);
pnlcontainer.add(Box.createVerticalStrut(5));
pnlcontainer.add(table);
pnlcontainer.validate();
pnlcontainer.repaint();
}thanks
dayananda b vhi,
thanks for your replay,
yes i know that, you can check the following code it works fine.
actually what i want is, when i resize table column it shold not automaticaly reszie when table resized and i dont want horizontal scroll bar, meaning that all table columns should resize with in the table size(say width 300)
if i make table autoresize off than horizontal scroll bar will appear and the other columns moved and i want scroll to view other columns.
please suggest me some way doing it, i tried with doLayout() no help,
doLayout() method only can be used when table resizes. first off all i want to restrict table resizing with in the limited size
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableColumnModel;
public class TempSycnTable extends JFrame
JTable table1 = new JTable(5, 5);
MyTable table2 = new MyTable(5, 5);
MyTable table3 = new MyTable(5, 5);
JPanel pnlcontainer = new JPanel();
public TempSycnTable()
JScrollPane src2 = new JScrollPane(table2);
JScrollPane src3 = new JScrollPane(table3);
// table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// src2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// src3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
table2.setTableHeader(null);
table3.setTableHeader(null);
table3.setColumnModel(table1.getColumnModel());
table2.setColumnModel(table1.getColumnModel());
table2.getColumnModel().addColumnModelListener(table1);
table3.getColumnModel().addColumnModelListener(table1);
table2.setTableHeader(null);
table3.setTableHeader(null);
setLayout(new BorderLayout());
pnlcontainer.setLayout(new BoxLayout(pnlcontainer, BoxLayout.Y_AXIS));
pnlcontainer.add(table1.getTableHeader());
pnlcontainer.add(Box.createVerticalStrut(5));
pnlcontainer.add(src2);
pnlcontainer.add(Box.createVerticalStrut(5));
pnlcontainer.add(src3);
getContentPane().add(pnlcontainer, BorderLayout.CENTER);
setSize(new Dimension(300, 300));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String[] args)
new TempSycnTable();
class MyTable extends JTable
public MyTable()
super();
public MyTable(int numRows, int numColumns)
super(numRows, numColumns);
public void columnMarginChanged(ChangeEvent event)
final TableColumnModel eventModel = table1.getColumnModel();
final TableColumnModel thisModel = getColumnModel();
final int columnCount = eventModel.getColumnCount();
for (int i = 0; i < columnCount; i++)
thisModel.getColumn(i).setWidth(eventModel.getColumn(i).getWidth());
repaint();
}thanks
daya -
Serialization not working in one way
I tried to serialize a String object from and to an applet. The servlet to applet communication is working properly. But applet to servlet serialization is not working, but no exceptions are thrown. Please help me. Thank you very much.(I have given the complete source code bellow)
=================================
APPLET SOURCE CODE
=================================
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TestApplet extends Applet {
Button send = new Button();
Button receive = new Button();
TextArea textarea = new TextArea();
BorderLayout borderLayout1 = new BorderLayout();
public void init() {
send.setLabel("send");
send.addActionListener(new Send_Listener());
receive.setLabel("receive");
receive.addActionListener(new Receive_Listener());
this.setLayout(borderLayout1);
this.add(send, BorderLayout.NORTH);
this.add(textarea, BorderLayout.CENTER);
this.add(receive, BorderLayout.SOUTH);
void sendObject(){
try{
URL url = new URL(getCodeBase(), "/servlets/testservlet");
URLConnection servletConnection = url.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
servletConnection.setRequestProperty ("Content-Type", "application/octet-stream");
ObjectOutputStream outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
outputToServlet.writeObject("some string here");
outputToServlet.flush();
outputToServlet.close();
textarea.append("aplet has send the object to the servlet\n");
}catch(Exception e){
textarea.append("EXCEPTION THROWN IN THE APPLET IN SENDOBJECT\n");
void getObject(){
try{
URL url =new URL(getCodeBase(), "/servlets/testservlet");
URLConnection servletConnection = url.openConnection();
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches(false);
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
String aString=(String)inputFromServlet.readObject();
textarea.append(aString+"\n");
textarea.append("aplet has received the object from the servlet\n");
}catch(Exception e){
textarea.setText("EXCEPTION THROWN IN THE APPLET IN GETOBJECT\n");
class Send_Listener implements ActionListener{
public void actionPerformed(java.awt.event.ActionEvent e){
sendObject();
class Receive_Listener implements ActionListener{
public void actionPerformed(java.awt.event.ActionEvent e){
getObject();
===================================
SERVLET SOURCE CODE
===================================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
ObjectOutputStream outputToApplet = new ObjectOutputStream(response.getOutputStream());
String aString= (String) request.getSession().getAttribute("ID");
outputToApplet.writeObject("this is the string object: "+aString);
outputToApplet.flush();
outputToApplet.close();
System.out.println("object send to applet:"+aString+"\n");
catch (IOException e)
System.out.println("EXCEPTION IN DOGET\n");
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
String aString = (String) inputFromApplet.readObject();
request.getSession().setAttribute("ID", aString);
inputFromApplet.close();
System.out.println("object received from applet:"+aString+"\n");
catch(Exception e)
System.out.println("EXCEPTION IN DOPOST\n");There are some things in Java which can't be serialized. When contained within a higher-level class such as Buttons. A button can be associated with an Action Listener. Now, you can serialize a button; however you can't serialize an action listener - for what should be to you obvious reasons. This is NOT an error and so there is no need to throw an exception when serializing the button.
Basically: Applet sends servlet button, but not listener. -
'NAVIGATE_ABSOLUTE' method is not working in UWL
We are working on Portal 7.0.
Recently We have upgraded from SP 13-0 To 13-5.
After this upgradation We are facing some problems, following is the scenario:
1. We have a ABAP Web DynPro Application say 'A', which has button "View Details".
2. On Clicking of "View_Details" We navigate to other ABAP Web DynPro Application say 'B' .
This was done using the 'NAVIGATE_ABSOLUTE' method of the 'IF_WD_PORTAL_INTEGRATION'.
3. Now The Same Application 'A' is being send as the Workitem to Approver's inbox.
4. Approver also was able to click on 'View_Details' button and Application 'B' used to call using 'NAVIGATE_ABSOLUTE'.
5. After upgradation, Point 2 is working fine. but point 4 is not working i.e. 'NAVIGATE_ABSOLUTE' functionality is not working when the application is send as workitem.
Please guide us for the above problem. Points assured for best solution.Hi
Thanks for your reply. Actually i wrote simple applets and those are working well.
So i did debug the code and i found that when i am running the following code in Apple MAC IE, nothing is happening in handleEvent method. Especially it is not going into the if statement (if (evt.id==401)). here i am checking for KEY_PRESS. I also tried with keyDown method but same problem in MAC IE.
I am pasting the code that is giving me problem.
import java.awt.*;
import java.applet.*;
public class testApplet extends Applet
public void init()
setLayout(new BorderLayout());
editableArea = new EditableArea();
editableArea.setBackground(Color.yellow);
add("Center", editableArea);
EditableArea editableArea;
import java.awt.*;
public class EditableArea extends Canvas
String s = "";
public boolean handleEvent(Event evt)
if (evt.id==401)
if(evt.key >= 32 && evt.key <= 255)
char c = (char)evt.key;
s = s + c;
repaint();
return super.handleEvent(evt);
public void paint( Graphics g )
g.setColor(Color.blue);
g.drawString( s,5,15);
-------------------------------------------------------------------- -
Comm.jar not working in Applet but works in Eclipse
Hello,
Please help me to read serial port data from Java Applet.
The below code working well and get data from weighing machine when we run in eclipse(Run Applet). But it now working when we use class file in Applet.
I think its security issue, but i still could not understand what we need to do.
I put the JOptionPane.showDialog and found that the code is crashing in line CommPortIdentifier.getPortIdentifiers(); (Not understood why try catch not working.)
I am using in Windows 7 environment.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.comm.*;
import javax.swing.*;
public class SimpleApplet extends JApplet {
public void init() {
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(SimpleApplet.this, "hello");
JOptionPane.showMessageDialog(SimpleApplet.this, Getdata());
add(button, BorderLayout.CENTER);
setBackground(Color.GRAY);
public String Getdata()
try
String drivername = "com.sun.comm.Win32Driver";
try
CommDriver driver = (CommDriver) Class.forName(drivername).newInstance();
driver.initialize();
catch (Exception e) { //just do nothing, it doesn't really matter
Enumeration portList=null;
CommPortIdentifier portId;
SerialPort serialPort;
OutputStream outputStream;
try
portList = CommPortIdentifier.getPortIdentifiers();
}catch(Exception ex)
JOptionPane.showMessageDialog(SimpleApplet.this, "erorr:" + ex.getStackTrace().toString());
JOptionPane.showMessageDialog(SimpleApplet.this, "get port lsit");
while(portList.hasMoreElements())
portId = (CommPortIdentifier) portList.nextElement();
if(portId.getPortType()== CommPortIdentifier.PORT_SERIAL)
if(portId.getName().equals("COM1"))
try
serialPort = (SerialPort) portId.open("WeightMachine",200);
serialPort.setSerialPortParams(1200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
outputStream = serialPort.getOutputStream();
InputStream mInputFromPort = serialPort.getInputStream();
outputStream.write("W".getBytes());
outputStream.flush();
Thread.sleep(500);
byte mBytesIn [] = new byte[20];
mInputFromPort.read(mBytesIn);
//mInputFromPort.read(mBytesIn);
String value = new String(mBytesIn);
mInputFromPort.close();
serialPort.close();
return value.replace("+00", "").replace(" Kg", "");
}catch(Exception ex)
return ex.getMessage();
}catch(Exception ex)
JOptionPane.showMessageDialog(SimpleApplet.this, "erorr last:" + ex.getStackTrace().toString());
return "Not found";
Thanks in advance.
Avinash959817 wrote:EJP wrote:959817 wrote:
it now working when we use class file in Applet.Define 'not working'.But when i run applet from browser from same machine its not working.That's not an answer. That's just a vague and pointless restatement of the original vague and pointless statement that I asked you to clarify.
When you take your car to a mechanic, do you just tell him it's 'not working'? -
KeyListener on combobox calander not working?
Am trying to add keylistener on this combobox calander, but somehow its not working right. The calendar is added to a JTable and the keyListener on it works, when i gets focus, but when the popup is visible it looses the keylistener? Can someone help me with this?
import com.sun.java.swing.plaf.motif.*;
import com.sun.java.swing.plaf.windows.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
import javax.swing.table.*;
public class DateComboBox extends JComboBox
public DateComboBox()
public DateComboBox(int raekke,DefaultTableModel model,JTable tabel)
this.raekke=raekke;
this.model=model;
this.tabel=tabel;
public void setDateFormat(SimpleDateFormat dateFormat)
this.dateFormat = dateFormat;
public void setSelectedItem(Object item)
// Could put extra logic here or in renderer when item is instanceof Date, Calendar, or String
// Dont keep a list ... just the currently selected item
removeAllItems(); // hides the popup if visible
addItem(item);
super.setSelectedItem(item);
public void setText(String texte)
setSelectedItem(texte);
public String getText()
return (String)this.getSelectedItem();
public void setRaekke(int raekke)
this.raekke=raekke;
public void updateUI()
ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
if (cui instanceof MetalComboBoxUI)
cui = new MetalDateComboBoxUI();
} else if (cui instanceof MotifComboBoxUI)
cui = new MotifDateComboBoxUI();
} else if (cui instanceof WindowsComboBoxUI)
cui = new WindowsDateComboBoxUI();
setUI(cui);
// Inner classes are used purely to keep DateComboBox component in one file
// UI Inner classes -- one for each supported Look and Feel
class MetalDateComboBoxUI extends MetalComboBoxUI
protected ComboPopup createPopup()
return new DatePopup( comboBox );
class WindowsDateComboBoxUI extends WindowsComboBoxUI
protected ComboPopup createPopup()
return new DatePopup( comboBox );
class MotifDateComboBoxUI extends MotifComboBoxUI
protected ComboPopup createPopup()
return new DatePopup( comboBox );
// DatePopup inner class
class DatePopup implements
ComboPopup,
MouseMotionListener,
MouseListener,
KeyListener,
PopupMenuListener
public DatePopup(JComboBox comboBox)
this.comboBox = comboBox;
setFocusable(true);
addKeyListener(this);
calendar = Calendar.getInstance();
// check Look and Feel
background = UIManager.getColor("ComboBox.background");
foreground = UIManager.getColor("ComboBox.foreground");
selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
selectedForeground = UIManager.getColor("ComboBox.selectionForeground");
initializePopup();
//========================================
// begin ComboPopup method implementations
public void show()
try
// if setSelectedItem() was called with a valid date, adjust the calendar
calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
} catch (Exception e)
{e.printStackTrace();}
updatePopup();
popup.show(comboBox, 0, comboBox.getHeight());
public void hide()
popup.setVisible(false);
protected JList list = new JList();
public JList getList()
return list;
public MouseListener getMouseListener()
return this;
public MouseMotionListener getMouseMotionListener()
return this;
public KeyListener getKeyListener()
return null;
public boolean isVisible()
return popup.isVisible();
public void uninstallingUI()
popup.removePopupMenuListener(this);
// end ComboPopup method implementations
//======================================
//===================================================================
// begin Event Listeners
// MouseListener
public void mousePressed( MouseEvent e )
// something else registered for MousePressed
public void mouseClicked(MouseEvent e)
public void mouseReleased( MouseEvent e )
if (!SwingUtilities.isLeftMouseButton(e))
return;
if (!comboBox.isEnabled())
return;
if (comboBox.isEditable())
comboBox.getEditor().getEditorComponent().requestFocus();
else
comboBox.requestFocus();
togglePopup();
protected boolean mouseInside = false;
public void mouseEntered(MouseEvent e)
mouseInside = true;
public void mouseExited(MouseEvent e)
mouseInside = false;
// MouseMotionListener
public void mouseDragged(MouseEvent e)
public void mouseMoved(MouseEvent e)
public void keyPressed(KeyEvent e)
if(e.getSource()==this)
if(e.getKeyCode()==KeyEvent.VK_CONTROL)
System.out.println("keytyped1");
public void keyTyped(KeyEvent e)
public void keyReleased( KeyEvent e )
if(e.getKeyCode()==KeyEvent.VK_CONTROL)
System.out.println("keytyped2");
if ( e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER )
togglePopup();
* Variables hideNext and mouseInside are used to
* hide the popupMenu by clicking the mouse in the JComboBox
public void popupMenuCanceled(PopupMenuEvent e)
protected boolean hideNext = false;
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
hideNext = mouseInside;
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
// end Event Listeners
//=================================================================
//===================================================================
// begin Utility methods
protected void togglePopup()
if( isVisible() || hideNext)
hide();
else
show();
hideNext = false;
// end Utility methods
//=================================================================
// Note *** did not use JButton because Popup closes when pressed
protected JLabel createUpdateButton(final int field, final int amount)
final JLabel label = new JLabel();
final Border selectedBorder = new EtchedBorder();
final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
label.setBorder(unselectedBorder);
label.setForeground(foreground);
label.addMouseListener(new MouseAdapter()
public void mouseReleased(MouseEvent e)
calendar.add(field, amount);
updatePopup();
public void mouseEntered(MouseEvent e)
label.setBorder(selectedBorder);
public void mouseExited(MouseEvent e)
label.setBorder(unselectedBorder);
return label;
protected void initializePopup()
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
header.setBackground(background);
header.setOpaque(true);
JLabel label;
label = createUpdateButton(Calendar.YEAR, -1);
label.setText("<<");
label.setToolTipText("Sidste �r");
header.add(Box.createHorizontalStrut(12));
header.add(label);
header.add(Box.createHorizontalStrut(12));
label = createUpdateButton(Calendar.MONTH, -1);
label.setText("< ");
label.setToolTipText("Sidste m�ned");
header.add(label);
monthLabel = new JLabel("", JLabel.CENTER);
monthLabel.setForeground(foreground);
header.add(Box.createHorizontalGlue());
header.add(monthLabel);
header.add(Box.createHorizontalGlue());
label = createUpdateButton(Calendar.MONTH, 1);
label.setText(" >");
label.setToolTipText("N�ste m�ned");
header.add(label);
label = createUpdateButton(Calendar.YEAR, 1);
label.setText(">>");
label.setToolTipText("N�ste �r");
header.add(Box.createHorizontalStrut(12));
header.add(label);
header.add(Box.createHorizontalStrut(12));
popup = new JPopupMenu();
popup.setBorder(BorderFactory.createLineBorder(Color.black));
popup.setLayout(new BorderLayout());
popup.setBackground(background);
popup.addPopupMenuListener(this);
popup.add(BorderLayout.NORTH, header);
popup.getAccessibleContext().setAccessibleParent(comboBox);
// update the Popup when either the month or the year of the calendar has been changed
protected void updatePopup()
monthLabel.setText( monthFormat.format(calendar.getTime()) );
if (days != null)
popup.remove(days);
days = new JPanel(new GridLayout(0, 7));
days.setBackground(background);
days.setOpaque(true);
Calendar setupCalendar = (Calendar) calendar.clone();
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
for (int i = 0; i < 7; i++)
int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(foreground);
if (dayInt == Calendar.SUNDAY)
label.setText("s�n");
else if (dayInt == Calendar.MONDAY)
label.setText("man");
else if (dayInt == Calendar.TUESDAY)
label.setText("tir");
else if (dayInt == Calendar.WEDNESDAY)
label.setText("ons");
else if (dayInt == Calendar.THURSDAY)
label.setText("tor");
else if (dayInt == Calendar.FRIDAY)
label.setText("fre");
else if (dayInt == Calendar.SATURDAY)
label.setText("l�r");
// days.add(label);
setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
setupCalendar = (Calendar) calendar.clone();
setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < (first-2) ; i++)
days.add(new JLabel(""));
for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++)
final int day = i;
final JLabel label = new JLabel(String.valueOf(day));
label.setHorizontalAlignment(JLabel.CENTER);
label.setForeground(foreground);
label.addMouseListener(new MouseAdapter()
public void mouseReleased(MouseEvent e)
label.setOpaque(false);
label.setBackground(background);
label.setForeground(foreground);
calendar.set(Calendar.DAY_OF_MONTH, day);
hide();
comboBox.requestFocus();
if (tabel.isEditing())
tabel.getCellEditor(tabel.getEditingRow(),
tabel.getEditingColumn()).stopCellEditing();
model.setValueAt(dateFormat.format(calendar.getTime()),raekke,1);
tabel.requestFocus();
public void mouseEntered(MouseEvent e)
label.setOpaque(true);
label.setBackground(selectedBackground);
label.setForeground(selectedForeground);
public void mouseExited(MouseEvent e)
label.setOpaque(false);
label.setBackground(background);
label.setForeground(foreground);
days.add(label);
popup.add(BorderLayout.CENTER, days);
popup.pack();
private JComboBox comboBox;
private Calendar calendar;
private JPopupMenu popup;
private JLabel monthLabel;
private JPanel days = null;
private SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
// private int antaldage=1;
private Color selectedBackground;
private Color selectedForeground;
private Color background;
private Color foreground;
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
private int raekke=-1;
private DefaultTableModel model;
private JTable tabel;
}come on help plz....
-
This program is well compiled but does not work.
I would like to know why this program does not work properly:
the idea is :
1. the user introduces a text as a string
2.the progam creates a file (with a FileOutputStream)
3. then this file is encripted according to DES (using JCE, cipheroutputStream)
4.the new filw is an encripte file, whose content is introduced in a string (with a FileInputStream)
(gives no probles of compilation!!)
(don know why it does not work)
here goes the code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
public class cuadro extends Applet{
private TextArea area1 =new TextArea(5,50);
private TextArea area2 =new TextArea(5,50);
private Button encriptar=new Button("encriptar");
private Button decriptar=new Button("decriptar");
public cuadro(){
layoutApplet();
encriptar.addActionListener(new ButtonHandler());
decriptar.addActionListener(new ButtonHandler());
resize(400,400);
private void layoutApplet(){
Panel keyPanel = new Panel();
keyPanel.add(encriptar);
keyPanel.add(decriptar);
Panel textPanel = new Panel();
Panel texto1 = new Panel();
Panel texto2 = new Panel();
texto1.add(new Label(" plain text"));
texto1.add(area1);
texto2.add(new Label(" cipher text"));
texto2.add(area2);
textPanel.setLayout(new GridLayout(2,1));
textPanel.add(texto1);
textPanel.add(texto2);
setLayout(new BorderLayout());
add("North", keyPanel);
add("Center", textPanel);
public static String encriptar(String text1){
//generar una clave
SecretKey clave=null;
String text2="";
try{
FileOutputStream fs =new FileOutputStream ("c:/javasoft/ti.txt");
DataOutputStream es= new DataOutputStream(fs);
for(int i=0;i<text1.length();++i){
int j=text1.charAt(i);
es.write(j);
es.close();
}catch(IOException e){
System.out.println("no funciona escritura");
}catch(SecurityException e){
System.out.println("el fichero existe pero es un directorio");
try{
//existe archivo DESkey.ser?
ObjectInputStream claveFich =new ObjectInputStream(new FileInputStream ("DESKey.ser"));
clave = (SecretKey) claveFich.readObject();
claveFich.close();
}catch(FileNotFoundException e){
System.out.println("creando DESkey.ser");
//si no, generar generar y guardar clave nueva
try{
KeyGenerator claveGen = KeyGenerator.getInstance("DES");
clave= claveGen.generateKey();
ObjectOutputStream claveFich = new ObjectOutputStream(new FileOutputStream("DESKey.ser"));
claveFich.writeObject(clave);
claveFich.close();
}catch(NoSuchAlgorithmException ex){
System.out.println("DES key Generator no encontrado.");
System.exit(0);
}catch(IOException ex){
System.out.println("error al salvar la clave");
System.exit(0);
}catch(Exception e){
System.out.println("error leyendo clave");
System.exit(0);
//crear una cifra
Cipher cifra = null;
try{
cifra= Cipher.getInstance("DES/ECB/PKCS5Padding");
cifra.init(Cipher.ENCRYPT_MODE,clave);
}catch(InvalidKeyException e){
System.out.println("clave no valida");
System.exit(0);
}catch(Exception e){
System.out.println("error creando cifra");
System.exit(0);
//leer y encriptar el archivo
try{
DataInputStream in = new DataInputStream(new FileInputStream("c:/javasoft/ti.txt"));
CipherOutputStream out = new CipherOutputStream(new DataOutputStream(new FileOutputStream("c:/javasoft/t.txt")),cifra);
int i;
do{
i=in.read();
if(i!=-1) out.write(i);
}while (i!=-1);
in.close();
out.close();
}catch(IOException e){
System.out.println("error en lectura y encriptacion");
System.exit(0);
try{
FileInputStream fe=new FileInputStream("c:/javasoft/t.txt");
DataInputStream le =new DataInputStream(fe);
int i;
char c;
do{
i=le.read();
c= (char)i;
if(i!=-1){
text2 += text2.valueOf(c);
}while(i!=-1);
le.close();
/*}catch(FileNotFoundException e){
System.out.println("fichero no encontrado");
System.exit(0);
}catch(ClassNotFoundException e){
System.out.println("clase no encontrada");
System.exit(0);
*/}catch(IOException e){
System.out.println("error e/s");
System.exit(0);
return text2;
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
if (e.getActionCommand().equals(encriptar.getLabel()))
// area2.setText(t1)
area2.setText(encriptar(area1.getText()));
//area2.setText("escribe algo");
else if (e.getActionCommand().equals(decriptar.getLabel()))
System.out.println("esto es decriptar");
//area2.setText("hola");
}catch(Exception ex){
System.out.println("error en motor de encriptacion");
//else System.out.println("no coge el boton encriptado/decript");If you don't require your code to run as an applet, you will probably get more mileage from refactoring it to run as an application.
As sudha_mp implied, an unsigned applet will fail on the line
FileInputStream fe=new FileInputStream("c:/javasoft/t.txt");
due to security restrictions. (Which, incidentally, are there for a very good reason) -
Function to change Boarder Look and feel of Jframe - Not working
Hi all,
In the given SSCE, the functionpublic void changeButtonColor(Component[] comps) to change the border look and feel of JFrame is not working.Please help.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class ScrollableWrapTest {
public static void main(String[] args) {
try {
final JPanel mainPanel = new JPanel(new WrapScollableLayout(FlowLayout.LEFT, 10, 10));
mainPanel.setBackground(Color.WHITE);
JScrollPane pane = new JScrollPane(mainPanel);
pane.setPreferredSize(new Dimension(320, 200));
Vector v = new Vector();
v.add("first");
JButton button = null;
for(int i =0;i<v.size();i++){
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(Color.WHITE);
int num = mainPanel.getComponentCount()+1;
button = new JButton("button" + num);
button.setPreferredSize(new Dimension(90, 25));
JLabel label = new JLabel((String)v.elementAt(i));
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(button, BorderLayout.NORTH);
panel.add(label, BorderLayout.SOUTH);
mainPanel.add(panel);
mainPanel.revalidate();
ScrollableWrapTest st = new ScrollableWrapTest();
st.buildGUI(pane);
} catch (Exception e) {e.printStackTrace();}
public void buildGUI(JScrollPane scrollPane)
JFrame frame = new JFrame("Scrollable Wrap Test");
JFrame.setDefaultLookAndFeelDecorated(true);
UIManager.put("activeCaption", new javax.swing.plaf.ColorUIResource(Color.LIGHT_GRAY));
changeButtonColor(frame.getComponents());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
public void changeButtonColor(Component[] comps)
for(int x = 0, y = comps.length; x < y; x++)
if(comps[x] instanceof AbstractButton)
((AbstractButton)comps[x]).setBackground(Color.LIGHT_GRAY);
((AbstractButton)comps[x]).setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
else if (comps[x] instanceof Container)
changeButtonColor(((Container)comps[x]).getComponents());
private static class WrapScollableLayout extends FlowLayout {
public WrapScollableLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
public Dimension preferredLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = super.preferredLayoutSize(target);
layoutContainer(target);
int nmembers = target.getComponentCount();
for (int i = 0 ; i < nmembers ; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
dim.height = Math.max(dim.height, d.height + m.getY());
if (target.getParent() instanceof JViewport)
dim.width = ((JViewport) target.getParent()).getExtentSize().width;
Insets insets = target.getInsets();
dim.height += insets.top + insets.bottom + getVgap();
return dim;
}Please help.
RonyYou are calling changeButtonColor(frame.getComponents()) before you add the JScrollPane to the content pane.
But why not just move this to the button creation loop?
button = new JButton("button" + num);
button.setBackground(Color.LIGHT_GRAY);
button.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); -
Custom TreeCellRenderer not working in Program
The following 2 lines set my TreeCellRenderer
FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
jtree.setCellRenderer(renderer1);
Rendering is not working in the Below Program. But If I comment the above 2 lines the default rendering is working. There is a probelm with my rendering class FSDirectoryCellRenderer which I am not able to figure out. PLease help me out
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
public class UniversityLayout extends JFrame {
private JTree jtree = null;
private DefaultTreeModel defaultTreeModel = null;
private JTextField jtfStatus;
public UniversityLayout() {
super("A University JTree Example");
setSize(300, 300);
Object[] nodes = buildJTree();
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setOpenIcon(new ImageIcon("opened.gif"));
renderer.setClosedIcon(new ImageIcon("closed.gif"));
renderer.setLeafIcon(new ImageIcon("leaf.gif"));
jtree.setCellRenderer(renderer);
jtree.setShowsRootHandles(true);
jtree.setEditable(false);
jtree.addTreeSelectionListener(new UTreeSelectionListener());
FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
jtree.setCellRenderer(renderer1);
JScrollPane s = new JScrollPane();
s.getViewport().add(jtree);
getContentPane().add(s, BorderLayout.CENTER);
jtfStatus = new JTextField(); // Use JTextField to allow copy operation
jtfStatus.setEditable(false);
jtfStatus.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
getContentPane().add(jtfStatus, BorderLayout.SOUTH);
TreePath path = new TreePath(nodes);
jtree.setSelectionPath(path);
// jtree.scrollPathToVisible(path);
class FSDirectoryCellRenderer extends JLabel implements TreeCellRenderer {
private Color textSelectionColor;
private Color textNoSelectionColor;
private Color backgroundSelectionColor;
private Color backgroundNoSelectionColor;
private boolean sel;
public FSDirectoryCellRenderer() {
super();
textSelectionColor = UIManager.getColor("Tree.selectionForeground");
textNoSelectionColor = UIManager.getColor("Tree.textForeground");
backgroundSelectionColor = UIManager
.getColor("Tree.selectionBackground");
backgroundNoSelectionColor = UIManager
.getColor("Tree.textBackground");
setOpaque(false);
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
setText(obj.toString());
if (obj instanceof Boolean) {
setText("Loading");
if (obj instanceof NodeIconData) {
NodeIconData nodeIconData = (NodeIconData) obj;
if (expanded) {
setIcon(nodeIconData.getExpandedIcon());
} else {
setIcon(nodeIconData.getNormalIcon());
} else {
setIcon(null);
setFont(jtree.getFont());
setForeground(selected ? textSelectionColor : textNoSelectionColor);
setBackground(selected ? backgroundSelectionColor
: backgroundNoSelectionColor);
sel = selected;
return this;
private Object[] buildJTree() {
Object[] nodes = new Object[4];
DefaultMutableTreeNode root = new DefaultMutableTreeNode(new College(1, "College"));
DefaultMutableTreeNode parent = root;
nodes[0] = root;
DefaultMutableTreeNode node = new DefaultMutableTreeNode(new College(2, "Class 1"));
parent.add(node);
parent = node;
parent.add(new DefaultMutableTreeNode(new College(3, "Section A")));
parent.add(new DefaultMutableTreeNode(new College(4, "Section B")));
parent = root;
node = new DefaultMutableTreeNode(new College(5, "Class 2"));
parent.add(node);
nodes[1] = node;
parent = node;
node = new DefaultMutableTreeNode(new College(6, "Science"));
parent.add(node);
// nodes[2] = node;
parent = node;
parent.add(new DefaultMutableTreeNode(new College(7, "Computer Science")));
parent.add(new DefaultMutableTreeNode(new College(8, "Information Science")));
parent = (DefaultMutableTreeNode)nodes[1];
node = new DefaultMutableTreeNode(new College(9, "Arts"));
parent.add(node);
nodes[2] = node;
parent = (DefaultMutableTreeNode)nodes[2];
parent.add(new DefaultMutableTreeNode(new College(10, "Drawing")));
node = new DefaultMutableTreeNode(new College(11, "Painting"));
parent.add(node);
nodes[3] = node;
parent = (DefaultMutableTreeNode)nodes[1];
parent.add(new DefaultMutableTreeNode(new College(12, "Telecom")));
defaultTreeModel = new DefaultTreeModel(root);
jtree = new JTree(defaultTreeModel);
return nodes;
public static void main(String argv[]) {
UniversityLayout frame = new UniversityLayout();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
class UTreeSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
Object[] nodes = path.getPath();
String status = "";
for (int k = 0; k < nodes.length; k++) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes[k];
College nd = (College) node.getUserObject();
status += "." + nd.getId();
jtfStatus.setText(status);
class College {
protected int id;
protected String name;
public College(int id, String name) {
this.id = id;
this.name = name;
public int getId() {
return id;
public String getName() {
return name;
public String toString() {
return name;
}It works fine for me (after commenting out the part about NodeIconData, whose source you didn't provide). What is the behavior you expect to see but don't? Is it that when you click on a tree node, it doesn't appear "selected?"
Why not extends DefaultTreeCellRenderer? You appear to be doing minimal configuring (sometimes changing the text and/or icon of the node).
class FSDirectoryCellRenderer extends DefaultTreeCellRenderer {
public FSDirectoryCellRenderer() {
super();
setOpaque(false);
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded,
leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object obj = node.getUserObject();
setText(obj.toString());
if (obj instanceof Boolean) {
setText("Loading");
// if (obj instanceof NodeIconData) {
// NodeIconData nodeIconData = (NodeIconData) obj;
// if (expanded) {
// setIcon(nodeIconData.getExpandedIcon());
// } else {
// setIcon(nodeIconData.getNormalIcon());
// } else {
setIcon(null);
return this;
} -
Repaint() method is not working in MAC IE
Hi All
why repaint method is not working in MAC IE ? What i am doing is in one class which is inheriting Canvas class getting the keybord input then adding it to main applet.
Please help me i am trying it for whole week and i couldn't find any solution. I didn't put my code but if anyone is willing to help me i can post it.
Thanks in advancs
ShanHi
Thanks for your reply. Actually i wrote simple applets and those are working well.
So i did debug the code and i found that when i am running the following code in Apple MAC IE, nothing is happening in handleEvent method. Especially it is not going into the if statement (if (evt.id==401)). here i am checking for KEY_PRESS. I also tried with keyDown method but same problem in MAC IE.
I am pasting the code that is giving me problem.
import java.awt.*;
import java.applet.*;
public class testApplet extends Applet
public void init()
setLayout(new BorderLayout());
editableArea = new EditableArea();
editableArea.setBackground(Color.yellow);
add("Center", editableArea);
EditableArea editableArea;
import java.awt.*;
public class EditableArea extends Canvas
String s = "";
public boolean handleEvent(Event evt)
if (evt.id==401)
if(evt.key >= 32 && evt.key <= 255)
char c = (char)evt.key;
s = s + c;
repaint();
return super.handleEvent(evt);
public void paint( Graphics g )
g.setColor(Color.blue);
g.drawString( s,5,15);
-------------------------------------------------------------------- -
Adding and displaying a new JPanel -- not working as expected
I'm starting my own new thread that is based on a problem discussed in another person's thread that can be found here in the New to Java forum titled "ActionListener:
http://forum.java.sun.com/thread.jspa?threadID=5207301
What I want to do: press a button which adds a new panel into another panel (the parentPane), and display the changes. The Actionlistener-derived class (AddPaneAction) for the button is in it's own file (it's not an internal class), and I pass a reference to the parentPane in the AddPaneAction's constructor as a parameter argument.
What works: After the button is clicked the AddPaneAction's actionPerformed method is called without problem.
What doesn't work: The new JPanel (called bluePanel) is not displayed as I thought it would be after I call
parentPane.revalidate(); // this doesn't work
parentPane.repaint();
What also doesn't work: So I obtained a reference to the main app's JFrame (I called it myFrame) by recursively calling component.getParent( ), no problem there, and then tried (and failed to show the bluePanel with) this:
myFrame.invalidate(); // I tried this with and without calling this method here
myFrame.validate(); // I tried this with and without calling this method here
myFrame.repaint();
What finally works but confuses me: I got it to work but only after calling this:
myFrame.pack();
myFrame.repaint();But I didn't think that I needed to call pack to display the panel. So, what am I doing wrong? Why are my expectations not correct? Here's my complete code/SSCCE below. Many thanks in advance.
Pete
The ParentPane class:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ParentPane extends JPanel
private JButton addPaneBtn = new JButton("Add new Pane");
public ParentPane()
super();
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setBackground(Color.yellow);
JPanel northPane = new JPanel();
northPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
northPane.setBackground(Color.yellow);
northPane.add(addPaneBtn);
add(northPane, BorderLayout.NORTH);
// add our actionlistener object and pass it a reference
// to the main class which happens to be a JPanel (this)
addPaneBtn.addActionListener(new AddPaneAction(this));
public static void main(String[] args)
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();
private static void createAndShowGUI()
JFrame frame = new JFrame("test add panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ParentPane());
frame.pack();
frame.setVisible(true);
} the AddPaneAction class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class AddPaneAction implements ActionListener
private JPanel parentPane;
private JFrame myFrame;
public AddPaneAction(JPanel parentPane)
this.parentPane = parentPane;
* recursively get the JFrame that holds the parentPane panel.
private JFrame getJFrame(Component comp)
Component parentComponent = comp.getParent();
if (parentComponent instanceof JFrame)
return (JFrame)parentComponent;
else
return getJFrame(parentComponent);
public void actionPerformed(ActionEvent arg0)
JPanel bluePanel = new JPanel(new BorderLayout());
bluePanel.setBackground(Color.blue);
bluePanel.setPreferredSize(new Dimension(400, 300));
JLabel myLabel = new JLabel("blue panel label");
myLabel.setForeground(Color.LIGHT_GRAY);
myLabel.setVerticalAlignment(SwingConstants.CENTER);
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
bluePanel.add(myLabel, BorderLayout.CENTER);
parentPane.add(bluePanel);
myFrame = getJFrame(parentPane);
//parentPane.revalidate(); // this doesn't work
//parentPane.repaint();
//myFrame.invalidate(); // and also this doesn't work
//myFrame.validate();
//myFrame.repaint();
myFrame.pack(); // but this does!?
myFrame.repaint();
}For me (as it happens I'm using JDK 1.5.0_04) your code appears to work fine.
It may be that we're seeing the same thing but interpreting it differently.
1. When I run your application with your "working" code, and press the button then the JFrame resizes and the blue area appears.
2. When I run your application with your "not working" code and press the button then the JFrame does not resize. If I manually resize it then the blue area is there.
3. When I run your application with your "not working" code, resize it first and then press the button then the JFrame then the blue area is there.
I interpret all of this as correct behaviour.
Is this what you are seeing too?
Are you expecting revalidate, repaint, invalidate or validate to resize your JFrame? I do not.
As an aside, I do remember having problems with this kind of thing in earlier JVMs (e.g. various 1.2 and 1.3), but I haven't used it enough recently to know if your code would manifest one of the previous problems or not. Also I don't know if they've fixed any stuff in this area. -
Hello! I am trying to indicate ProgressBar during download the binary file. But ProgressBar is not working.Please help me!
* BinarySaver6.java
* Created on 2003/08/30, 14:46
import java.net.*;
import java.io.*;
* @author masaki
public class BinarySaver6 extends javax.swing.JFrame {
/** Creates new form BinarySaver6 */
public BinarySaver6() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
private void initComponents() {//GEN-BEGIN:initComponents
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
jTextField1.setText("http://");
getContentPane().add(jTextField1, java.awt.BorderLayout.NORTH);
jButton1.setText("DOWNLOAD");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
jProgressBar1.setStringPainted(true);
getContentPane().add(jProgressBar1, java.awt.BorderLayout.SOUTH);
pack();
}//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
URL u = new URL(jTextField1.getText());
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || contentLength == -1 ) {
throw new IOException("This is not a binary file.");
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length-offset);
if (bytesRead == -1) break;
offset += bytesRead;
jProgressBar1.setValue(jProgressBar1.getValue()+offset);
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset
+ " bytes; Expected " + contentLength + " bytes");
String filename = u.getFile();
filename = filename.substring(filename.lastIndexOf('/') + 1);
FileOutputStream fout = new FileOutputStream(filename);
fout.write(data);
fout.flush();
fout.close();
catch (MalformedURLException e1) {
System.err.println(jTextField1.getText() + " is not URL I understand.");
catch (IOException e2) {
System.err.println("error");
}//GEN-LAST:event_jButton1ActionPerformed
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
System.exit(0);
}//GEN-LAST:event_exitForm
* @param args the command line arguments
public static void main(String args[]) {
new BinarySaver6().show();
// �������� - ���W�s��//GEN-BEGIN:variables
private javax.swing.JTextField jTextField1;
private javax.swing.JButton jButton1;
private javax.swing.JProgressBar jProgressBar1;
// �����������I����//GEN-END:variablesRichard, you like many, many others in the forum on this thread and others fail to appreciate the real problem here, I think. Lot's of people suggest to learn to use threads and read the Swing tutorial on ProgressMonitor. That is good as far as it goes, but consider what we have here. You are right that the problem is that the event processing thread is blocked and that is what is preventing the progress bar from updating. But often what you want to do is exactly to block the event processing thread.
Consider that any application code is full of action handlers etc that manipulate some common data structure(s). Now if you want to do some operation on this data structure you want to block others from manipulating it at the same time. Now if this operation you are doing takes a long time you want to present a progress bar.
How do you do that.
If you just put it up (the progress bar), in a (non modal) window, it won't show. You do not want to put the operation into a thread and let the event processing thread run, as preventing all those other event/action handlers from manipulating the data structures would require a lot of work.
I think that putting the progress bar into a modal dialog (showing the modal dialog would block the event processing thread and thus other action/etc handlers) and creating a separate thread to do the work would work, but seems like a quite a lot of work for something that should be as simple as:
ProgressBarDialog pbar=new ProgressBarDialog());
pbar.setVisible(true);
for (as long as I like)
pbar.setValue(i++)
pbar.setVisible(false);
all this in an actionListener.actionPerformed() method.
I'm just working on that but so far have no code to share...
regs Kusti
Maybe you are looking for
-
Iphone 4 is neither recognized by PC not connected to the elec. pluge
Iphone 4 is not charging, I've tried 3 different cables and 2 adapters. the OS on my computer is win 7 and also I can not connect the Iphone through cable to my portable computer. Sure, Itunes can not be connected as long as the win7 could not recogn
-
Where is the editor window in elements 12?
When I open up Elements 12 on my computer or laptop, the options bar that shows quick, guided and expert is not there. Where the hell is it?
-
Nokia Lumia 620 and Class10 microSDHC UHS-I compat...
Are these 2 compatible Nokia Lumia 620 sanDisk Ultra microSDHC UHS-I 32GB The Nokia Lumia page only mentions microSD and doesn't detail if it supports the UHS format.
-
Updating or changing the outbound delivery
Hi we have created a outbound delivery in the system, I want to update some of the detials like route, no of packages using a program. is there any FM or BAPI for that. I have tried using the BAPI_OUTB_DELIVERY_CHANGE to update the route in the deli
-
Hi . I 'm experiencingn the following problem when granting acess to the sys user can any one help please in this issue.I 'm using an oracle 10 g on a solaris system. Granting EXECUTE on DBMS_JAVA to SYSTEM WITH GRANT OPTION Error granting EXECUTE on