JFrame please help
Hi everybody
I have a Jmenu on a frame called mainFrame ,
and the Jmanu has for example an invoice button, which opens an other frame,
And a statement button which also opens an other frame.
Now I don�t want to put a print button in both frames (invoice statement)
So I put it in the Jmenu, But broblem.
Now this is the code for the print button in the Jmenu
//for loop because when pressed on mainFrame the other frames should still be focused
Frame[] frame = getFrames();
for(int j = 1; j < frame.length; j++)
frame[j].toFront();
Frame[] ff = getFrames();
for(int j = 1; j < ff.length; j++)
{ if ( ff[j].hasFocus() )
JOptionPane.showMessageDialog(null,"print");//example
Now I never see the word print, method hasFocus don�t work, why?
thanks for helping me
Hi,
first of all, I don't really understand what to intend to do...
but anyway, why do you move to front ALL the frames ? Only one should have the focus at any time... last, after calling toFront(), you need to call requestFocus() on one of its components.
Regards.
Similar Messages
-
Problem with JFrame , please help !
hello , all !
I define a JFrame1 as ancestor
I set the JFrame's contentPane Layout to borderLayout ,
and add some component in south , north , and add a menu , in its constructor
then I define a new JFrame2 inherit from JFrame1, I also add a Jpanel component
to contentPane center in its constructor !
but something a wrong , I can't see the Jpanel , only see the components which add in JFrame1?
this is why ?
thanks
/* source code */
public class JFrame1{
public JFrame1(){
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
statusBar.setBorder(BorderFactory.createEtchedBorder());
statusBar.setText("Hello , Young follow! ");
contentPane.add(statusBar, BorderLayout.SOUTH);
toolbar = new Toolbar_DataEntry(this);
contentPane.add(toolbar, BorderLayout.NORTH);
menubar = new Menu_DataEntry(this);
this.setJMenuBar(menubar);
public class JFrame2 extends JFrame1 {
public JFrame2() {
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
/**Component initialization*/
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
JPanel bodyPane = new JPanel();
bodyPane.setDataModule(queryDataSet1);
queryDataSet1.Opendatabase();
bodyPane.setBorder(null);
this.setTitle("Frame Title");
bodyPane.setBounds(new Rectangle(4, 5, 427, 114));
contentPane.setPreferredSize(bodyPane.getPreferredSize());
contentPane.setMinimumSize(bodyPane.getMinimumSize());
Frame_Resize();The problem is that the constructor for JFrame2 does not automatically call the constructor for JFrame1. Therefore the JFrame1 constructor never gets called.
You must do this yourself with the super() method.
public JFrame2() {
super();
try {
jbinit();
catch( Exception e )
e.printStackTrace();
Remember that this rule applies to all descendent classes. -
Please help - JFrame, menu, another JFrame, setBackground
I am trying to make a simple program that draws a JFrame with a menu. The menu has one item, which when selected draws another JFrame. That JFrame has a button, which when pressed changes the background color. Many hours have gone into this, despite the fact that I made a similar program a few weeks ago.
The compiler complains about the method getContentPane, when I remove that, it runs and draws the first window, but the menu item does not make the second window. Also, the setDefaultCloseOperation confuses the compiler as well.
Please help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuAction2
public static void main(String[] args)
MainWindow window = new MainWindow("Menu action example");
//window.setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
class MainWindow extends JFrame
MainWindow(String title)
super(title);
getContentPane.setLayout(new BorderLayout());
Toolkit theKit = getToolkit();
Dimension wndSize = theKit.getScreenSize();
setBounds(0, 0,wndSize.width, wndSize.height);
setJMenuBar(menuBar);
fileMenu = new JMenu("File");
connectItem = new JMenuItem();
connectItem = fileMenu.add("Connect...");
connectItem.addActionListener(menuHandler = new Handler());
menuBar.add(fileMenu);
getContentPane.add(toolBar, BorderLayout.NORTH);
class Handler implements ActionListener
public void actionPerformed(ActionEvent e)
win = new ConnectWindow("Connect to Database");
getContentPane().add(win, BorderLayout.NORTH);
setVisible(true);
private JMenu fileMenu;
private JMenuItem connectItem;
private JMenuBar menuBar = new JMenuBar();
private JToolBar toolBar = new JToolBar();
private Handler menuHandler;
private ConnectWindow win;
class ConnectWindow extends JFrame
ConnectWindow(String title)
super(title);
setSize(200,200);
setLayout(new BorderLayout());
JButton connectB = new JButton("Connect");
connectB.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
setBackground(Color.red);
add(connectB,BorderLayout.SOUTH);
setVisible(true);
}getContentPane is a method so you should use it that way:
getContentPane().setLayout(new BorderLayout());
getContentPane.add(new Button("Ok")); -
Problem with threads and simulation: please help
please help me figure this out..
i have something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawShapes extends JApplet{
private JButton choices[];
private String names[]={"line", "square", "oval"};
private JPanel buttonPanel;
private DrawPanel drawingArea;
private int width=300, height=200;
public void init(){
drawingArea=new DrawPanel(width, height);
choices=new JButton[names.length];
buttonPanel=new JPanel();
buttonPanel.setLayout(new GridLayout(1, choices.length));
ButtonHandler handler=new ButtonHandler();
for(int i=0; i<choices.length; i++){
choices=new JButton(names[i]);
buttonPanel.add(choices[i]);
choices[i].addActionListener(handler);
Container c=getContentPane();
c.add(buttonPanel, BorderLayout.NORTH);
c.add(drawingArea, BorderLayout.CENTER);
}//end init
public void setWidth(int w){
width=(w>=0 ? w : 300);
public void setHeight(int h){
height=(h>=0 ? h : 200);
/*public static void main(String args[]){
int width, height;
if(args.length!=2){
height=200; width=300;
else{
width=Integer.parseInt(args[0]);
height=Integer.parseInt(args[1]);
JFrame appWindow=new JFrame("An applet running as an application");
appWindow.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
DrawShapes appObj=new DrawShapes();
appObj.setWidth(width);
appObj.setHeight(height);
appObj.init();
appObj.start();
appWindow.getContentPane().add(appObj);
appWindow.setSize(width, height);
appWindow.show();
}//end main*/
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
for(int i=0; i<choices.length; i++){
if(e.getSource()==choices[i]){
drawingArea.setCurrentChoice(i);
break;
}//end class DrawShapes
class DrawPanel extends JPanel{
private int currentChoice=-1;
private int width=100, height=100;
public DrawPanel(int w, int h){
width=(w>=0 ? w : 100);
height=(h>=0 ? h : 100);
public void paintComponent(Graphics g){
super.paintComponent(g);
switch(currentChoice){
case 0: g.drawLine(randomX(), randomY(), randomX(), randomY());
break;
case 1: g.drawRect(randomX(), randomY(), randomX(), randomY());
break;
case 2: g.drawOval(randomX(), randomY(), randomX(), randomY());
break;
public void setCurrentChoice(int c){
currentChoice=c;
repaint();
private int randomX(){
return (int) (Math.random()*width);
private int randomY(){
return (int) (Math.random()*height);
}//end class drawPanel
That one's from a book. I used that code to start with my applet. Mine calls different merthod from the switch cases. Say I have:
case 0: drawStart(g); break;
public void drawStart(Graphics g){
/* something here */
drawMain(g);
public void drawMain(graphics g){
g.drawString("test", x, y);
//here's where i'm trying to pause
//i've tried placing Thread.sleep between these lines
g.drawLine(x, y, a, b);
//Thread.sleep here
g.drawRect(x, y, 50, 70);
}I also need to put delays between method calls but I need to synchronize them. Am I doing it all wrong? The application pauses or sleeps but afterwards, it still drew everything all at once. Thanks a lot!It is. Sorry about that. Just answer any if you want to. I'd appreciate your help. Sorry again if it caused you anything or whatever. .n_n.
-
I suppose it is the problem with socket connection,Please help
Hi,
I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
The Exceptions caused are given below
java.net.SocketException: Connection reset by peer: Connection reset by peer
at java.net.SocketInputStream.SocketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:119)
at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
at java.io.InputStreamReader.read(InputStreamReader.java:511)
at java.io.BufferedReader.fill(BufferedReader.java:139)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at Login.LoginData(Login.java:330)
at Login.test(Login.java:155)
at Login$Buttonhandler.actionPerformed(Login.java:138)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
at java.awt.Component.processMouseEvent(Component.java:4906)
at java.awt.Component.processEvent(component.java:4732)
at java.awt.Container.processEvent(Container.java:1337)
at java.awt.component.dispatchEventImpl(Component.java:3476)
at java.awt.Container.dispatchEventImpl(Container.java:1399)
at java.awt.Component.dispatchEvent(Component.java:3343)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
at java.awt.Container.dispatchEventImpl(Container.java:1373)
at java.awt.window.dispatchEventImpl(Window.java:1459)
at java.awt.Component.dispatchEvent(Component.java:3343)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
My program looks somewhat like this :
1st class definition:
public class Login extends Jframe// Login is the name of the first class;
Socket connection;
DataOutputStream outStream;
BufferedReader inStream;
Frame is set up here
public class Buttonhandler implements ActionListener
public void actionPerformed(ActionEvent e) {
String comm = e.getActionCommand();
if(comm.equals("ok")) {
check=LoginCheck(ID,paswd);
test();
public void test() //checks whether the login is true
if(check)
new Messenger(ID);// the second class is invoked
public boolean LoginCheck(String user,String passwd)
//Enter the Server's IP & port below
String destination="localhost";
int port=1234;
try
connection=new Socket(destination,port);
}catch (UnknownHostException ex){
error("Unknown host");
catch (IOException ex){
ex.printStackTrace ();
error("IO error creating socket ");
try{
inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
outStream=new DataOutputStream(connection.getOutputStream());
}catch (IOException ex){
error("IO error getting streams");
ex.printStackTrace();
System.out.println("connected to "+destination+" at port "+port+".");
BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
String receive=new String();
try{
receive=inStream.readLine();
}catch(IOException ex){ error("Error reading from server");}
if(receive.equals("Logintrue"))
check=true;
else
check=false;
try{
inStream.close();
outStream.close();
connection.close();
}catch (IOException ex){
error("IO error closing socket");
return(check);
// second class is defined below
public class Messenger
Socket connect;
DataOutputStream outStr;
BufferedReader inStr;
public static void main(String args[])
{ Messenger mes = new Messenger(args[0]);}
Messenger(String strg)
CreateWindow();
setupEvents();
LoginData(strg);
fram.show();
void setupEvents()
fram.addWindowListener(new WindowHandler());
login.addActionListener(new MenuItemHandler());
quit.addActionListener(new MenuItemHandler());
button.addActionListener(new Buttonhandle());
public void LoginData(String name)
//Enter the Server's IP & port below
String dest="localhost";
int port=1234;
int r=0;
String str[]=new String[40];
try
connect=new Socket(dest,port);
}catch (UnknownHostException ex){
error("Unknown host");
catch (IOException ex){
ex.printStackTrace ();
error("IO error creating socket ");
try{
inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
outStr=new DataOutputStream(connect.getOutputStream());
}catch (IOException ex){
error("IO error getting streams");
ex.printStackTrace();
String codeln=new String("\n");
try{
outStr.flush();
outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
outStr.writeBytes(codeln);
outStr.write(13);
outStr.flush();
String check="qkpltx";
String receive=new String();
try{
while((receive=inStr.readLine())!=null) //the statement that causes the exception
if(receive.equals(check))
break;
else
str[r]=receive;
r++;
}catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
catch(NullPointerException ex){ex.printStackTrace();}
} catch (IOException ex){ex.printStackTrace();
error("Error reading from keyboard or socket ");
try{
inStr.close();
outStr.close();
connect.close();
}catch (IOException ex){
error("IO error closing socket");
for(int l=0,k=1;l<r;l=l+2,k++)
if(!(str[l].equals(name)))
stud[k]=" "+str[l];
else
k--;
public class Buttonhandle implements ActionListener
public void actionPerformed(ActionEvent e) {
//chat with the selected user;
public class MenuItemHandler implements ActionListener
public void actionPerformed(ActionEvent e)
String cmd=e.getActionCommand();
if(cmd.equals("Disconnect"))
//Disconnect from the server
else if(cmd.equals("Change User"))
//Disconnect from the server & call the login window
else if(cmd.equals("View Connection Details"))
//show connection details;
public class WindowHandler extends WindowAdapter
public void windowClosing(WindowEvent e){
//Disconnect from server & then exit;
System.exit(0);}
I�ll be very thankful if anyone corrects the mistake for me.Please help.You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
public class Messenger {
Socket connect;
public static void main(String args[]) {
Messenger mes = new Messenger(args[0]);
Messenger(Socket s, String strg) {
this.connect = s;
CreateWindow();
setupEvents();
LoginData(strg);
fram.show();
} -
Please help me in creating a form using Swing.
(I m sorry if I've posted similar post in some other thread.I am new to this forum..:))
There are several problems which I am facing while coding a form.
1. In the form I have one JComboBox
of Country and other of State. Now I want it in such a way that when
I select a country from the Country JComboBox ,the corresponding states
automatically appears in the State JComboBox.
2. I need to add picture frame in the 6th tab so that the picture shows up when clicked browse and open.
3.I need to add tables in 1st and 5th tab which shows up the details through database when added through several textboxes and combo boxes.
so please help me!
Here's my code
==========================================================
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.Box;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Design extends JFrame
public Design()
super("Tenant Form");
setLayout(new BorderLayout());
JTabbedPane tabbedPane=new JTabbedPane(); //creating tabbed buttons
//<--------coding for first tab--------->
JPanel panel1=new JPanel();
tabbedPane.addTab("Detail of Landlord",null,panel1,"first tab"); //here panel1 is created for tab1
GridBagConstraints gbc=new GridBagConstraints();
gbc.insets=new Insets(2,2,2,2);
gbc.anchor=GridBagConstraints.WEST;
JPanel jp11 = new JPanel(); //1st panel in 1st tab for top labels and buttons
jp11.setLayout(new GridBagLayout());
JLabel l241 = new JLabel("Name Of LandLord");
jp11.add(l241,gbc);
JComboBox jc01=new JComboBox();
jc01.addItem("Select");
jc01.addItem("Mr.");
jc01.addItem("Mrs.");
gbc.gridx=1;
jp11.add(jc01,gbc);
JTextField f01=new JTextField(10);
gbc.gridx=2;
jp11.add(f01,gbc);
JLabel l251 = new JLabel("Sex");
gbc.gridx=5;
gbc.insets=new Insets(2,20,2,2);
jp11.add(l251,gbc);
JComboBox jc11=new JComboBox();
jc11.addItem("Select");
jc11.addItem("Male");
jc11.addItem("Female");
gbc.gridx=6;
gbc.insets=new Insets(2,2,2,2);
jp11.add(jc11,gbc);
JLabel l261 = new JLabel("Age(Yrs)");
gbc.gridx=8;
gbc.insets=new Insets(2,20,2,2);
jp11.add(l261,gbc);
JTextField f11=new JTextField(3);
gbc.gridx=9;
gbc.insets=new Insets(2,2,2,2);
jp11.add(f11,gbc);
JLabel l271 = new JLabel("Occupation");
gbc.gridx= 11;
gbc.insets=new Insets(2,20,2,2);
jp11.add(l271,gbc);
JComboBox jc21=new JComboBox();
jc21.addItem("Select");
jc21.addItem("Engineer");
jc21.addItem("Business");
gbc.gridx=12;
gbc.insets=new Insets(2,2,2,2);
jp11.add(jc21,gbc);
JButton ab1=new JButton("ADD");
gbc.gridx=14;
gbc.insets=new Insets(2,20,2,2);
jp11.add(ab1,gbc);
panel1.add(jp11);
//<--coding for adding table with scroll pane #yet to be coded#-->
JTable jtab1=new JTable();
//start of p21 panel. 1st of two titledborder panels in tab 1
JPanel jp21=new JPanel();
jp21.setBorder(new TitledBorder("Address Of Landlord Property"));
jp21.setLayout(new GridBagLayout());
JLabel l11=new JLabel("Property/House/Building Address");
gbc.gridx=0;
gbc.gridy=0;
jp21.add(l11,gbc);
JTextArea ta11=new JTextArea(3,15);
ta11.setLineWrap(true);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
JScrollPane scroll11=new JScrollPane(ta11,v,h);
gbc.gridx=1;
jp21.add(scroll11);
jp21.add(ta11,gbc);
JLabel l21=new JLabel("Land Mark");
gbc.gridx=0;
gbc.gridy=1;
gbc.ipady=0;
gbc.gridheight=1;
jp21.add(l21,gbc);
JTextField tf21=new JTextField(15);
gbc.gridx=1;
gbc.gridy=1;
jp21.add(tf21,gbc);
JLabel l31=new JLabel("Country");
gbc.gridx=0;
gbc.gridy=2;
jp21.add(l31,gbc);
JComboBox c11=new JComboBox();
c11.addItem("India");
c11.addItem("US");
c11.addItem("Australia");
gbc.gridx=1;
gbc.gridy=2;
jp21.add(c11,gbc);
JLabel l41=new JLabel("State");
gbc.gridx=0;
gbc.gridy=3;
jp21.add(l41,gbc);
JComboBox c21=new JComboBox();
c21.addItem("Rajasthan");
c21.addItem("Delhi");
c21.addItem("Maharastra");
gbc.gridx=1;
gbc.gridy=3;
jp21.add(c21,gbc);
JLabel l51=new JLabel("District");
gbc.gridx=0;
gbc.gridy=4;
jp21.add(l51,gbc);
JComboBox c31=new JComboBox();
c31.addItem("jaipur");
c31.addItem("ajmer");
c31.addItem("alwar");
gbc.gridx=1;
gbc.gridy=4;
jp21.add(c31,gbc);
JLabel l61=new JLabel("City/Town");
gbc.gridx=0;
gbc.gridy=5;
jp21.add(l61,gbc);
JTextField tf31=new JTextField(15);
gbc.gridx=1;
gbc.gridy=5;
jp21.add(tf31,gbc);
JLabel l71=new JLabel("Police District");
gbc.gridx=0;
gbc.gridy=6;
jp21.add(l71,gbc);
JComboBox c41=new JComboBox();
c41.addItem("Jaipur");
c41.addItem("Alwar");
c41.addItem("Ajmer");
gbc.gridx=1;
gbc.gridy=6;
jp21.add(c41,gbc);
JLabel l81=new JLabel("Police Circle");
gbc.gridx=0;
gbc.gridy=7;
jp21.add(l81,gbc);
JComboBox c51=new JComboBox();
c51.addItem("India");
c51.addItem("US");
c51.addItem("Australia");
gbc.gridx=1;
gbc.gridy=7;
jp21.add(c51,gbc);
JLabel l91=new JLabel("Police station");
gbc.gridx=0;
gbc.gridy=8;
jp21.add(l91,gbc);
JComboBox c61=new JComboBox();
c61.addItem("Bani Park");
c61.addItem("Raja Park");
c61.addItem("Malviya Nagar");
gbc.gridx=1;
gbc.gridy=8;
jp21.add(c61,gbc);
JLabel l101=new JLabel("Pin No.");
gbc.gridx=0;
gbc.gridy=9;
jp21.add(l101,gbc);
JTextField tf41=new JTextField(15);
gbc.gridx=1;
gbc.gridy=9;
jp21.add(tf41,gbc);
JLabel l111=new JLabel("Phone No.(R)");
gbc.gridx=0;
gbc.gridy=10;
jp21.add(l111,gbc);
JTextField tf51=new JTextField(15);
gbc.gridx=1;
gbc.gridy=10;
jp21.add(tf51,gbc);
//start of p31.2nd of two titledborder panels in tab 1
JPanel jp31=new JPanel();
jp31.setBorder(new TitledBorder("Address Of Landlord Office"));
jp31.setLayout(new GridBagLayout());
JLabel l121=new JLabel("Office Address");
gbc.gridx=0;
gbc.gridy=0;
jp31.add(l121,gbc);
JTextArea ta61=new JTextArea(3,15);
ta61.setLineWrap(true);
JScrollPane scroll2=new JScrollPane(ta61);
gbc.gridx=1;
gbc.gridy=0;
jp31.add(ta61,gbc);
JLabel l131=new JLabel("Country");
gbc.gridx=0;
gbc.gridy=1;
gbc.gridheight=1;
jp31.add(l131,gbc);
JComboBox c12=new JComboBox();
c12.addItem("India");
c12.addItem("US");
c12.addItem("Australia");
gbc.gridx=1;
gbc.gridy=1;
jp31.add(c12,gbc);
JLabel l141=new JLabel("State");
gbc.gridx=0;
gbc.gridy=2;
jp31.add(l141,gbc);
JComboBox c22=new JComboBox();
c22.addItem("Rajasthan");
c22.addItem("Delhi");
c22.addItem("Maharastra");
gbc.gridx=1;
gbc.gridy=2;
jp31.add(c22,gbc);
JLabel l151=new JLabel("District");
gbc.gridx=0;
gbc.gridy=3;
jp31.add(l151,gbc);
JComboBox c32=new JComboBox();
c32.addItem("jaipur");
c32.addItem("ajmer");
c32.addItem("alwar");
gbc.gridx=1;
gbc.gridy=3;
jp31.add(c32,gbc);
JLabel l161=new JLabel("City/Town");
gbc.gridx=0;
gbc.gridy=4;
jp31.add(l161,gbc);
JTextField tf71=new JTextField(15);
gbc.gridx=1;
gbc.gridy=4;
jp31.add(tf71,gbc);
JLabel l171=new JLabel("Police District");
gbc.gridx=0;
gbc.gridy=5;
jp31.add(l171,gbc);
JComboBox c42=new JComboBox();
c42.addItem("Jaipur");
c42.addItem("Alwar");
c42.addItem("Ajmer");
gbc.gridx=1;
gbc.gridy=5;
jp31.add(c42,gbc);
JLabel l181=new JLabel("Police Circle");
gbc.gridx=0;
gbc.gridy=6;
jp31.add(l181,gbc);
JComboBox c52=new JComboBox();
c52.addItem("India");
c52.addItem("US");
c52.addItem("Australia");
gbc.gridx=1;
gbc.gridy=6;
jp31.add(c52,gbc);
JLabel l191=new JLabel("Police station");
gbc.gridx=0;
gbc.gridy=7;
jp31.add(l191,gbc);
JComboBox c62=new JComboBox();
c62.addItem("Bani Park");
c62.addItem("Raja Park");
c62.addItem("Malviya Nagar");
gbc.gridx=1;
gbc.gridy=7;
jp31.add(c62,gbc);
JLabel l201=new JLabel("Pin No.");
gbc.gridx=0;
gbc.gridy=8;
jp31.add(l201,gbc);
JTextField tf81=new JTextField(15);
gbc.gridx=1;
gbc.gridy=8;
jp31.add(tf81,gbc);
JLabel l211=new JLabel("Phone No.(O)");
gbc.gridx=0;
gbc.gridy=9;
jp31.add(l211,gbc);
JTextField tf91=new JTextField(15);
gbc.gridx=1;
gbc.gridy=9;
jp31.add(tf91,gbc);
JLabel l221=new JLabel("Phone No.(M)");
gbc.gridx=0;
gbc.gridy=10;
gbc.gridheight=1;
jp31.add(l221,gbc);
JTextField tf101=new JTextField(15);
gbc.gridx=1;
gbc.gridy=10;
jp31.add(tf101,gbc);
JLabel l231=new JLabel("E-mail");
gbc.gridx=0;
gbc.gridy=11;
gbc.gridheight=1;
jp31.add(l231,gbc);
JTextField tf111=new JTextField(15);
gbc.gridx=1;
gbc.gridy=11;
jp31.add(tf111,gbc);
JPanel jp41=new JPanel(); //adding above two panels p21 and p31 to p41 panel.
jp41.setLayout(new BoxLayout(jp41,BoxLayout.X_AXIS));
jp41.add(jp21);
jp41.add(Box.createHorizontalStrut(50));
jp41.add(jp31);
panel1.add(jp41); //adding p41 panel to panel1
//<--------coding for second tab--------->
JPanel panel2 = new JPanel();
tabbedPane.addTab("Id of Landlord",null,panel2,"second tab");
panel2.setLayout(new FlowLayout());
//adding radiobutton above TitledBorder panel
JPanel jp02=new JPanel();
JLabel l12=new JLabel("Identity Known");
JRadioButton jrb12=new JRadioButton("Yes");
JRadioButton jrb22=new JRadioButton("No");
ButtonGroup bg12=new ButtonGroup();
bg12.add(jrb12);
bg12.add(jrb22);
jp02.add(l12);
jp02.add(jrb12);
jp02.add(jrb22);
//adding TitledBorder panel
JPanel jp12=new JPanel();
jp12.setBorder(new TitledBorder("Identity Detail"));
jp12.setLayout(new GridBagLayout());
gbc.insets=new Insets(5,5,5,5);
JLabel l22=new JLabel("Identity Card");
gbc.gridx=0;
gbc.gridy=0;
jp12.add(l22,gbc);
JTextField jtf12=new JTextField(10);
gbc.gridx=1;
jp12.add(jtf12,gbc);
JLabel l32=new JLabel("Date of Issue");
gbc.gridx=0;
gbc.gridy=1;
jp12.add(l32,gbc);
JTextField jtf22=new JTextField(10);
gbc.insets=new Insets(5,5,5,25);
gbc.gridx=1;
jp12.add(jtf22,gbc);
JLabel l42=new JLabel("Identity Number");
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=2;
jp12.add(l42,gbc);
JTextField jtf32=new JTextField(10);
gbc.gridx=3;
jp12.add(jtf32,gbc);
JLabel l52=new JLabel("Name Of Issuer");
gbc.gridx=0;
gbc.gridy=2;
jp12.add(l52,gbc);
JTextField jtf42=new JTextField(10);
gbc.insets=new Insets(5,5,5,25);
gbc.gridx=1;
jp12.add(jtf42,gbc);
JLabel l62= new JLabel("Place Of Issuer");
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=2;
jp12.add(l62,gbc);
JTextField jtf52=new JTextField(10);
gbc.gridx=3;
jp12.add(jtf52,gbc);
gbc.gridx=0;
gbc.gridy=2;
Box b12 =Box.createVerticalBox(); //adding both panels to vertica box and adding it to panel2
b12.add(jp02);
b12.add(jp12);
panel2.add(b12);
//<--------coding for third tab--------->
JPanel panel3 = new JPanel();
tabbedPane.addTab("Detail of Tenant",null,panel3,"third tab");
//adding panel for top data
JPanel jp13=new JPanel(); //jp13 panel for details above 3 TitledBorder panels
jp13.setLayout(new GridBagLayout());
JLabel l13=new JLabel("Name");
gbc.insets=new Insets(2,2,2,2);
gbc.gridx=0;
gbc.gridy=0;
jp13.add(l13,gbc);
JComboBox c13=new JComboBox();
c13.addItem("Select");
c13.addItem("Mr.");
c13.addItem("Mrs.");
gbc.gridx=1;
jp13.add(c13,gbc);
JTextField jtf13=new JTextField(16);
gbc.gridx=2;
gbc.gridwidth=2;
jp13.add(jtf13,gbc);
JLabel l23=new JLabel("Sex");
gbc.insets=new Insets(2,20,2,2);
gbc.gridx=4;
gbc.gridwidth=1;
jp13.add(l23,gbc);
JComboBox c23=new JComboBox();
c23.addItem("Select");
c23.addItem("Male");
c23.addItem("Female");
gbc.insets=new Insets(2,2,2,2);
gbc.gridx=5;
jp13.add(c23,gbc);
JLabel l33=new JLabel("Father/Mother/Husband's Name");
gbc.gridy=1;
gbc.gridx=0;
jp13.add(l33,gbc);
JComboBox c33=new JComboBox();
c33.addItem("Select");
c33.addItem("Mr.");
c33.addItem("Mrs.");
gbc.gridx=1;
jp13.add(c33,gbc);
JComboBox c43=new JComboBox();
c43.addItem("Select");
c43.addItem("Mr.");
c43.addItem("Mrs.");
gbc.gridx=2;
jp13.add(c43,gbc);
JTextField jtf23=new JTextField(10);
gbc.gridx=3;
jp13.add(jtf23,gbc);
JLabel l43=new JLabel("Age(Yrs)");
gbc.insets=new Insets(2,20,2,2);
gbc.gridx=4;
jp13.add(l43,gbc);
JTextField jtf33=new JTextField(3);
gbc.insets=new Insets(2,2,2,2);
gbc.gridx=5;
jp13.add(jtf33,gbc);
JLabel l53=new JLabel("Citizenship");
gbc.gridy=2;
gbc.gridx=0;
jp13.add(l53,gbc);
JComboBox c53=new JComboBox();
c53.addItem("Select");
c53.addItem("Indian");
c53.addItem("Australian");
gbc.gridx=1;
gbc.gridwidth=2;
jp13.add(c53,gbc);
JLabel l63=new JLabel("Occupation");
gbc.insets=new Insets(2,20,2,2);
gbc.gridx=4;
gbc.gridwidth=1;
jp13.add(l63,gbc);
JComboBox c63=new JComboBox();
c63.addItem("Select");
c63.addItem("Engineer");
c63.addItem("Doctor");
gbc.insets=new Insets(2,2,2,2);
gbc.gridx=5;
jp13.add(c63,gbc);
panel3.add(jp13);
JPanel jp23=new JPanel(); //first of 3 TitledBorder panels
jp23.setBorder(new TitledBorder("Local Address"));
jp23.setLayout(new GridBagLayout());
JLabel l73=new JLabel("Local Address");
gbc.gridx=0;
gbc.gridy=0;
jp23.add(l73,gbc);
JTextArea ta43=new JTextArea(3,10);
ta43.setLineWrap(true);
JScrollPane scroll13=new JScrollPane(ta43);
gbc.gridx=1;
gbc.gridy=0;
jp23.add(ta43,gbc);
JLabel l83=new JLabel("Country");
gbc.gridx=0;
gbc.gridy=1;
gbc.gridheight=1;
jp23.add(l83,gbc);
JComboBox c73=new JComboBox();
c73.addItem("India");
c73.addItem("US");
c73.addItem("Australia");
gbc.gridx=1;
gbc.gridy=1;
jp23.add(c73,gbc);
JLabel l93=new JLabel("State");
gbc.gridx=0;
gbc.gridy=2;
jp23.add(l93,gbc);
JComboBox c83=new JComboBox();
c83.addItem("Rajasthan");
c83.addItem("Delhi");
c83.addItem("Maharastra");
gbc.gridx=1;
gbc.gridy=2;
jp23.add(c83,gbc);
JLabel l103=new JLabel("District");
gbc.gridx=0;
gbc.gridy=3;
jp23.add(l103,gbc);
JComboBox c93=new JComboBox();
c93.addItem("jaipur");
c93.addItem("ajmer");
c93.addItem("alwar");
gbc.gridx=1;
gbc.gridy=3;
jp23.add(c93,gbc);
JLabel l113=new JLabel("City/Town");
gbc.gridx=0;
gbc.gridy=4;
jp23.add(l113,gbc);
JTextField tf53=new JTextField(10);
gbc.gridx=1;
gbc.gridy=4;
jp23.add(tf53,gbc);
JLabel l123=new JLabel("Police District");
gbc.gridx=0;
gbc.gridy=5;
jp23.add(l123,gbc);
JComboBox c103=new JComboBox();
c103.addItem("Jaipur");
c103.addItem("Alwar");
c103.addItem("Ajmer");
gbc.gridx=1;
gbc.gridy=5;
jp23.add(c103,gbc);
JLabel l133=new JLabel("Police Circle");
gbc.gridx=0;
gbc.gridy=6;
jp23.add(l133,gbc);
JComboBox c113=new JComboBox();
c113.addItem("India");
c113.addItem("US");
c113.addItem("Australia");
gbc.gridx=1;
gbc.gridy=6;
jp23.add(c113,gbc);
JLabel l143=new JLabel("Police station");
gbc.gridx=0;
gbc.gridy=7;
jp23.add(l143,gbc);
JComboBox c123=new JComboBox();
c123.addItem("Bani Park");
c123.addItem("Raja Park");
c123.addItem("Malviya Nagar");
gbc.gridx=1;
gbc.gridy=7;
jp23.add(c123,gbc);
JLabel l153=new JLabel("Pin No.");
gbc.gridx=0;
gbc.gridy=8;
jp23.add(l153,gbc);
JTextField tf63=new JTextField(10);
gbc.gridx=1;
gbc.gridy=8;
jp23.add(tf63,gbc);
JLabel l163=new JLabel("Phone No.(R)");
gbc.gridx=0;
gbc.gridy=9;
jp23.add(l163,gbc);
JTextField tf73=new JTextField(10);
gbc.gridx=1;
gbc.gridy=9;
jp23.add(tf73,gbc);
JLabel l173=new JLabel("E-mail");
gbc.gridx=0;
gbc.gridy=10;
gbc.gridheight=1;
jp23.add(l173,gbc);
JTextField tf83=new JTextField(10);
gbc.gridx=1;
gbc.gridy=10;
jp23.add(tf83,gbc);
JPanel jp33=new JPanel(); //second of 3 TitledBorder panels
jp33.setBorder(new TitledBorder("Permanent Address"));
jp33.setLayout(new GridBagLayout());
JLabel l183=new JLabel("Perm. Address");
gbc.gridx=0;
gbc.gridy=0;
jp33.add(l183,gbc);
JTextArea ta93=new JTextArea(5,10);
JScrollPane scroll23=new JScrollPane(ta43);
ta93.setLineWrap(true);
gbc.gridx=1;
gbc.gridy=0;
jp33.add(ta43,gbc);
JLabel l193=new JLabel("Country");
gbc.gridx=0;
gbc.gridy=1;
gbc.gridheight=1;
jp33.add(l193,gbc);
JComboBox c133=new JComboBox();
c133.addItem("India");
c133.addItem("US");
c133.addItem("Australia");
gbc.gridx=1;
gbc.gridy=1;
jp33.add(c133,gbc);
JLabel l203=new JLabel("State");
gbc.gridx=0;
gbc.gridy=2;
jp33.add(l203,gbc);
JComboBox c143=new JComboBox();
c143.addItem("Rajasthan");
c143.addItem("Delhi");
c143.addItem("Maharastra");
gbc.gridx=1;
gbc.gridy=2;
jp33.add(c143,gbc);
JLabel l213=new JLabel("District");
gbc.gridx=0;
gbc.gridy=3;
jp33.add(l213,gbc);
JComboBox c153=new JComboBox();
c153.addItem("jaipur");
c153.addItem("ajmer");
c153.addItem("alwar");
gbc.gridx=1;
gbc.gridy=3;
jp33.add(c153,gbc);
JLabel l223=new JLabel("City/Town");
gbc.gridx=0;
gbc.gridy=4;
jp33.add(l223,gbc);
JTextField tf103=new JTextField(10);
gbc.gridx=1;
gbc.gridy=4;
jp33.add(tf103,gbc);
JLabel l233=new JLabel("Police District");
gbc.gridx=0;
gbc.gridy=5;
jp33.add(l233,gbc);
JComboBox c163=new JComboBox();
c163.addItem("Jaipur");
c163.addItem("Alwar");
c163.addItem("Ajmer");
gbc.gridx=1;
gbc.gridy=5;
jp33.add(c163,gbc);
JLabel l243=new JLabel("Police Circle");
gbc.gridx=0;
gbc.gridy=6;
jp33.add(l243,gbc);
JComboBox c173=new JComboBox();
c173.addItem("India");
c173.addItem("US");
c173.addItem("Australia");
gbc.gridx=1;
gbc.gridy=6;
jp33.add(c173,gbc);
JLabel l253=new JLabel("Police station");
gbc.gridx=0;
gbc.gridy=7;
jp33.add(l253,gbc);
JComboBox c183=new JComboBox();
c183.addItem("Bani Park");
c183.addItem("Raja Park");
c183.addItem("Malviya Nagar");
gbc.gridx=1;
gbc.gridy=7;
jp33.add(c183,gbc);
JLabel l263=new JLabel("Pin No.");
gbc.gridx=0;
gbc.gridy=8;
jp33.add(l263,gbc);
JTextField tf113=new JTextField(10);
gbc.gridx=1;
gbc.gridy=8;
jp33.add(tf113,gbc);
JLabel l273=new JLabel("Phone No.(R)");
gbc.gridx=0;
gbc.gridy=9;
jp33.add(l273,gbc);
JTextField tf123=new JTextField(10);
gbc.gridx=1;
gbc.gridy=9;
jp33.add(tf123,gbc);
JLabel l283=new JLabel("phone No.(M)");
gbc.gridx=0;
gbc.gridy=10;
gbc.gridheight=1;
jp33.add(l283,gbc);
JTextField tf133=new JTextField(10);
gbc.gridx=1;
gbc.gridy=10;
jp33.add(tf133,gbc);
JPanel jp43=new JPanel(); //third of 3 TitledBorder panels
jp43.setBorder(new TitledBorder("Ex-Home Address"));
jp43.setLayout(new GridBagLayout());
JLabel l293=new JLabel("Address");
gbc.gridx=0;
gbc.gridy=0;
jp43.add(l293,gbc);
JTextArea ta143=new JTextArea(3,10);
ta143.setLineWrap(true);
JScrollPane scroll33=new JScrollPane(ta143);
gbc.gridx=1;
gbc.gridy=0;
jp43.add(ta143,gbc);
JLabel l303=new JLabel("Country");
gbc.gridx=0;
gbc.gridy=1;
gbc.gridheight=1;
jp43.add(l303,gbc);
JComboBox c193=new JComboBox();
c193.addItem("India");
c193.addItem("US");
c193.addItem("Australia");
gbc.gridx=1;
gbc.gridy=1;
jp43.add(c193,gbc);
JLabel l313=new JLabel("State");
gbc.gridx=0;
gbc.gridy=2;
jp43.add(l313,gbc);
JComboBox c203=new JComboBox();
c203.addItem("Rajasthan");
c203.addItem("Delhi");
c203.addItem("Maharastra");
gbc.gridx=1;
gbc.gridy=2;
jp43.add(c203,gbc);
JLabel l323=new JLabel("District");
gbc.gridx=0;
gbc.gridy=3;
jp43.add(l323,gbc);
JComboBox c213=new JComboBox();
c213.addItem("jaipur");
c213.addItem("ajmer");
c213.addItem("alwar");
gbc.gridx=1;
gbc.gridy=3;
jp43.add(c213,gbc);
JLabel l333=new JLabel("City/Town");
gbc.gridx=0;
gbc.gridy=4;
jp43.add(l333,gbc);
JTextField tf153=new JTextField(10);
gbc.gridx=1;
gbc.gridy=4;
jp43.add(tf153,gbc);
JLabel l343=new JLabel("Police District");
gbc.gridx=0;
gbc.gridy=5;
jp43.add(l343,gbc);
JComboBox c223=new JComboBox();
c223.addItem("Jaipur");
c223.addItem("Alwar");
c223.addItem("Ajmer");
gbc.gridx=1;
gbc.gridy=5;
jp43.add(c223,gbc);
JLabel l353=new JLabel("Police Circle");
gbc.gridx=0;
gbc.gridy=6;
jp43.add(l353,gbc);
JComboBox c233=new JComboBox();
c233.addItem("India");
c233.addItem("US");
c233.addItem("Australia");
gbc.gridx=1;
gbc.gridy=6;
jp43.add(c233,gbc);
JLabel l363=new JLabel("Police station");
gbc.gridx=0;
gbc.gridy=7;
jp43.add(l363,gbc);
JComboBox c243=new JComboBox();
c243.addItem("Bani Park");
c243.addItem("Raja Park");
c243.addItem("Malviya Nagar");
gbc.gridx=1;
gbc.gridy=7;
jp43.add(c123,gbc);
JLabel l373=new JLabel("Pin No.");
gbc.gridx=0;
gbc.gridy=8;
jp43.add(l373,gbc);
JTextField tf163=new JTextField(10);
gbc.gridx=1;
gbc.gridy=8;
jp43.add(tf163,gbc);
JLabel l383=new JLabel("Phone");
gbc.gridx=0;
gbc.gridy=9;
jp43.add(l383,gbc);
JTextField tf173=new JTextField(10);
gbc.gridx=1;
gbc.gridy=9;
jp43.add(tf173,gbc);
JLabel l393=new JLabel("Leaving Date");
gbc.gridx=0;
gbc.gridy=10;
gbc.gridheight=1;
jp43.add(l393,gbc);
JTextField tf183=new JTextField(10);
gbc.gridx=1;
gbc.gridy=10;
jp43.add(tf183,gbc);
/*JCheckBox cb13=new JCheckBox("Approx");
gbc.gridx=2;
gbc.gridy=10;
jp43.add(cb13);*/
JPanel jp53=new JPanel(); //panel for addin all 3 TitledBorder panels
jp53.setLayout(new BoxLayout(jp53,BoxLayout.X_AXIS));
jp53.add(jp23);
jp53.add(Box.createHorizontalStrut(30)); //giving space between each TitledBorder panel
jp53.add(jp33);
jp53.add(Box.createHorizontalStrut(30));
jp53.add(jp43);
panel3.add(jp53); //adding panel which contains all 3 TitledBorder panels to panel3
JPanel jp63=new JPanel(); //jp63 panel for bottom data
jp63.setBorder(new TitledBorder("Tennancy Start/End"));
JLabel l403=new JLabel("From Date");
jp63.add(l403);
JTextField jtf193=new JTextField(12);
jp63.add(jtf193);
JCheckBox jcb23=new JCheckBox("Approx");
jp63.add(jcb23);
JLabel l413=new JLabel("To Date");
jp63.add(l413);
JTextField jtf203=new JTextField(12);
jp63.add(jtf203);
JCheckBox jcb33=new JCheckBox("Approx");
jp63.add(jcb33);
panel3.add(jp63); //adding bottom details panel jp63 to panel3
//<--------coding for fourth tab--------->
JPanel panel4 = new JPanel();
tabbedPane.addTab("Id of Tenant",null,panel4,"fourth tab");
panel4.setLayout(new FlowLayout());
//adding radiobutton above TitledBorder panel jp14
JPanel jp04=new JPanel();
JLabel l14=new JLabel("Identity Known");
JRadioButton jrb14=new JRadioButton("Yes");
JRadioButton jrb24=new JRadioButton("No");
ButtonGroup bg14=new ButtonGroup();
bg14.add(jrb14);
bg14.add(jrb24);
jp04.add(l14);
jp04.add(jrb14);
jp04.add(jrb24);
//adding TitledBorder panel jp14
JPanel jp14=new JPanel();
jp14.setBorder(new TitledBorder("Identity Detail"));
jp14.setLayout(new GridBagLayout());
gbc.insets=new Insets(5,5,5,5);
JLabel l24=new JLabel("Identity Card");
gbc.gridx=0;
gbc.gridy=0;
jp14.add(l24,gbc);
JTextField jtf14=new JTextField(10);
gbc.gridx=1;
jp14.add(jtf14,gbc);
JLabel l34=new JLabel("Date of Issue");
gbc.gridx=0;
gbc.gridy=1;
jp14.add(l34,gbc);
JTextField jtf24=new JTextField(10);
gbc.insets=new Insets(5,5,5,25);
gbc.gridx=1;
jp14.add(jtf24,gbc);
JLabel l44=new JLabel("Identity Number");
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=2;
jp14.add(l44,gbc);
JTextField jtf34=new JTextField(10);
gbc.gridx=3;
jp14.add(jtf34,gbc);
JLabel l54=new JLabel("Name Of Issuer");
gbc.gridx=0;
gbc.gridy=2;
jp14.add(l54,gbc);
JTextField jtf44=new JTextField(10);
gbc.insets=new Insets(5,5,5,25);
gbc.gridx=1;
jp14.add(jtf44,gbc);
JLabel l64=new JLabel("Place Of Issuer");
gbc.insets=new Insets(5,5,5,5);
gbc.gridx=2;
jp14.add(l64,gbc);
JTextField jtf54=new JTextField(10);
gbc.gridx=3;
jp14.add(jtf54,gbc);
gbc.gridx=0;
gbc.gridy=2;
Box b14=Box.createVerticalBox(); //adding both panels to panel4 in vertical box
b14.add(jp04);
b14.add(jp14);
panel4.add(b14);
//<--------coding for fifth tab--------->
JPanel panel5 = new JPanel();
tabbedPane.addTab("Info Of Other Members",null,panel5,"fifth tab");
JPanel jp15=new JPanel(); //top panel jp15 for details above add delete buttons
jp15.setLayout(new GridBagLayout());
JLabel l15=new JLabel("Name");
gbc.gridx=0;
gbc.gridy=0;
gbc.insets=new Insets(10,10,10,10);
jp15.add(l15,gbc);
JTextField jtf15=new JTextField(10);
gbc.gridx=1;
jp15.add(jtf15,gbc);
JLabel l25=new JLabel("Sex");
gbc.gridx=2;
gbc.insets=new Insets(10,80,10,10);
jp15.add(l25,gbc);
JComboBox jcb15=new JComboBox();
jcb15.addItem("Male");
jcb15.addItem("Female");
gbc.gridx=3;
gbc.insets=new Insets(10,10,10,10);
jp15.add(jcb15,gbc);
JLabel l35=new JLabel("Relation");
gbc.gridx=0;
gbc.gridy=1;
gbc.insets=new Insets(10,10,40,10);
jp15.add(l35,gbc);
JTextField jtf25=new JTextField(10);
gbc.gridx=1;
jp15.add(jtf25,gbc);
JLabel l45=new JLabel("Age");
gbc.gridx=2;
gbc.insets=new Insets(10,80,40,10);
jp15.add(l45,gbc);
JTextField jtf35 =new JTextField(10);
gbc.gridx=3;
gbc.insets=new Insets(10,10,40,10);
jp15.add(jtf35,gbc);
JPanel jp25=new JPanel(); //middle panel jp25 for adding "add" and "delete" buttons
JButton jb15=new JButton("Add");
JButton jb25=new JButton("Delete");
jp25.add(jb15);
jp25.add(jb25);
//adding table #yet to be coded#
Box b15=Box.createVerticalBox();
b15.add(jp15);
b15.add(jp25);
panel5.add(b15); //adding jp15 and jp25 to panel5 in vertical box
//<--------coding for sixth tab--------->
JPanel panel6 = new JPanel();
tabbedPane.addTab("Related To Office",null,panel6,"sixth tab");
panel6.setLayout(new GridBagLayout());
//adding 4 labels and textfields vertically
JLabel l16=new JLabel("Investigation Officer");
gbc.gridx=0;
gbc.gridy=0;
gbc.insets=new Insets(40,40,20,10);
panel6.add(l16,gbc);
JTextField jtf16 =new JTextField(10);
gbc.gridx=1;
gbc.insets=new Insets(40,20,20,40);
panel6.add(jtf16,gbc);
JLabel l26=new JLabel("S.No.");
gbc.gridx=0;
gbc.gridy=1;
gbc.insets=new Insets(10,40,20,10);
panel6.add(l26,gbc);
JTextField jtf26 =new JTextField(10);
gbc.gridx=1;
gbc.insets=new Insets(10,20,20,40);
panel6.add(jtf26,gbc);
JLabel l36=new JLabel("Page No.");
gbc.gridx=0;
gbc.gridy=2;
gbc.insets=new Insets(10,40,20,10);
panel6.add(l36,gbc);
JTextField jtf36 =new JTextField(10);
gbc.gridx=1;
gbc.insets=new Insets(10,20,20,40);
panel6.add(jtf36,gbc);
JLabel l46=new JLabel("Date");
gbc.gridx=0;
gbc.gridy=3;
gbc.insets=new Insets(10,40,20,10);
panel6.add(l46,gbc);
JTextField jtf46=new JTextField(10);
gbc.gridx=1;
gbc.insets=new Insets(10,20,20,40);
panel6.add(jtf46,gbc);
/* Canvas c16=new Canvas(); //creating a rectangle frame for adding image
Image i16=c.createImage(200,100);
gbc.gridx=2;
gbc.gridy=0;
gbc.insets=new Insets(40,20,20,40);
gbc.gridheight=3;
panel6.add(i16,gbc);*/
JButton jb16=new JButton("Browse"); //adding "browse" and "save" buttons
gbc.insets=new Insets(10,20,20,40);
gbc.gridy=3;
panel6.add(jb16,gbc);
JButton jb26=new JButton("Save");
gbc.insets=new Insets(50,20,20,40);
gbc.gridy=4;
panel6.add(jb26,gbc);
//<-------end of sixth tab------->
add(tabbedPane);
//lower panel for cancel button
JPanel jp1=new JPanel();
jp1.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton can=new JButton("Cancel"); //initialising cancel button
jp1.add(can);
add(jp1,BorderLayout.SOUTH);
class Blistener implements ActionListener // class for action listener
public void actionPerformed(ActionEvent ae)
Object obj=ae.getSource();
try{
if(obj == can) //condition for cancel button
System.exit(0);
}catch(Exception e)
{System.out.println(e);
public class Project
public static void main(String args[]) //main method for the program
Design tabbedwin= new Design();
tabbedwin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabbedwin.setSize(900,700);
tabFirst things first. Next time please use the code formating tags when posting your code.
Secondly, we cant help you do your entire project or more specifically we cant do it for you. We can probably help you with one section at a time.
Thirdly, do not post your entire code. Create a Short, Self Contained, Compilable Example (SSCCE) that demonstrates the problem section, and that is independent of any third party libraries and can compiled instantly and tested.
Now, lets see if we can answer one problem here.
Ques 1. In the form I have one JComboBox of Country and other of State. Now I want it in such a way that whenI select a country from the Country JComboBox ,the corresponding states automatically appears in the State JComboBox.
Ans 1: Use an ItemListener or an ActionListener (javax.swing.event) for this. Once an item is selected, the event will be fired and then you populate your ComboBox with the requried data.
Ques 2. I need to add picture frame in the 6th tab so that the picture shows up when clicked browse and open.
Ans 2: You haven't created the JButton for the browse action, nor have you created the JLabel to show the picture in. Create the JButton, then the JLabel, attach an ActionListener to the button to listen for the button click, open a JFileChooser, select the image file, create an ImageIcon and pass the File object returned to it. Then call the JLabel.setIcon( the ImageIcon) to display the picture. You'll have to store the picture File information some where so can reference it when saving.
Ques 3.I need to add tables in 1st and 5th tab which shows up the details through database when added through several textboxes and combo boxes.
You need to do some reading. The Swing Tutorial has everything you need, from How to use Tables to How to connect to databases. There are also some examples in your JDK installation folder, ie, jdk/demos/jfc/tableExample. Here is the link to the swing tutorial on how to use Tables: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html. You find other useful links there.
ICE -
Please help me to avoid this Exception.
I have a JTextField which will accept only non-negative integer. To get the Document roll_doc for the constructor of JTextField
I have a class maxLengthText which will make sure that the JTextfield accepts only non-negative integer.
I have a problem while resetting the content of the JTextField. As I have made sure that only integers are allowed in my text field.
So while using setText(" "). The code executes the exception in my actionListener. I don't want this exceptuion to get executed when I reset the content of my JTextField using setText(String).
Please help. Suggest any workaround for this. Thanks in advance
The code is as follows:
package marksheet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.BorderFactory;
import javax.swing.*;
import javax.swing.text.*;
public class SpringApplet1 extends JApplet implements ActionListener {
JLabel l_instruction1;
JLabel l_instruction2;
JLabel l_instruction3;
JLabel l_instruction4;
JLabel l_instruction5;
JLabel l_instruction6;
JLabel l_instruction7;
JLabel l_instruction8;
JLabel l_space;
JLabel label1;
JLabel label2;
JLabel label3;
JLabel label4;
JTextField text1;
JTextField text2;
JTextField text3;
JTextField text4;
JLabel l_name;
JLabel l_fname;
JLabel l_course;
JLabel l_specialization;
JLabel l_batch;
JLabel l_semester;
JLabel l_rollno;
JLabel l_enrolno;
JTextField t_name;
JTextField t_fname;
JTextField t_rollno;
JTextField t_enrollno;
JComboBox cb_course;
JComboBox cb_branch;
JComboBox cb_batch;
JComboBox cb_semester;
JCheckBox c_parttime;
JCheckBox c_fulltime;
JButton Submit;
JButton enterMarks;
JButton reset;
JTextField txtInt;
JPanel p;
JPanel p1;
JPanel p2;
JPanel p3;
public void init () {
l_space = new JLabel(" ");
Document roll_doc = new maxLengthText(5); // set maximum length to 5
Document enroll_doc = new maxLengthText(6); // set maximum length to 6
t_rollno= new JTextField(roll_doc, "", 6);
t_enrollno= new JTextField(enroll_doc, "", 7);
Document name_doc = new maxLengthAlpha(15); // set maximum length to 15
t_name = new JTextField(name_doc, "", 7);
l_instruction1 = new JLabel("All names should be alphabets",JLabel.LEFT);
l_instruction1.setForeground(Color.blue);
l_instruction1.setVisible(false);
l_instruction1.setVisible(true);
l_instruction2 = new JLabel("Name can not be greater than 15 characters",JLabel.LEFT);
l_instruction2.setForeground(Color.blue);
l_instruction2.setVisible(false);
l_instruction2.setVisible(true);
l_instruction3 = new JLabel("Seperate firstname and last name with a 'space'",JLabel.LEFT);
l_instruction3.setForeground(Color.blue);
l_instruction3.setVisible(false);
l_instruction3.setVisible(true);
l_instruction4 = new JLabel("All marks are out of 100, Marks obtained are non-negative integers",JLabel.LEFT);
l_instruction4.setForeground(Color.blue);
l_instruction4.setVisible(false);
l_instruction4.setVisible(true);
l_instruction8 = new JLabel("Marks obtained can not be greater than 100 ",JLabel.LEFT);
l_instruction8.setForeground(Color.blue);
l_instruction8.setVisible(false);
l_instruction8.setVisible(true);
l_instruction5 = new JLabel("Roll number should be of length 5 and only numeric",JLabel.LEFT);
l_instruction5.setForeground(Color.blue);
l_instruction5.setVisible(false);
l_instruction5.setVisible(true);
l_instruction6 = new JLabel("Enrolment number should be of length 6 and only numeric",JLabel.LEFT);
l_instruction6.setForeground(Color.blue);
l_instruction6.setVisible(false);
l_instruction6.setVisible(true);
l_instruction7 = new JLabel("All fields are Mandatory",JLabel.LEFT);
l_instruction7.setForeground(Color.blue);
l_instruction7.setVisible(false);
l_instruction7.setVisible(true);
l_name = new JLabel("Name",JLabel.LEFT);
l_name.setForeground(Color.blue);
l_fname = new JLabel("Father's Name",JLabel.LEFT);
l_fname.setForeground(Color.blue);
l_course = new JLabel("Course",JLabel.LEFT);
l_course.setForeground(Color.blue);
l_specialization = new JLabel("Specialization",JLabel.LEFT);
l_specialization.setForeground(Color.blue);
l_batch = new JLabel("Batch",JLabel.LEFT);
l_batch.setForeground(Color.blue);
l_semester = new JLabel("Semester",JLabel.LEFT);
l_semester.setForeground(Color.blue);
l_rollno = new JLabel("Roll Number",JLabel.LEFT);
l_rollno.setForeground(Color.blue);
l_enrolno = new JLabel("Enrolment Number",JLabel.LEFT);
l_enrolno.setForeground(Color.blue);
//t_name = new JTextField(20);
t_name.setEditable(true);
// t_name.setBackground(Color.YELLOW);
t_fname = new JTextField(20);
t_fname.setEditable(true);
// t_fname.setBackground(Color.YELLOW);
//t_rollno = new JTextField(20);
t_rollno.setEditable(true);
// t_rollno.setBackground(Color.YELLOW);
//t_enrollno = new JTextField(20);
t_enrollno.setEditable(true);
// t_enrollno.setBackground(Color.YELLOW);
label1 = new JLabel("Data Structures",JLabel.LEFT);
label1.setForeground(Color.blue);
label1.setVisible(true);
label2 = new JLabel("Compiler Design",JLabel.LEFT);
label2.setForeground(Color.blue);
label2.setVisible(true);
label3 = new JLabel("Numerical Analysis",JLabel.LEFT);
label3.setForeground(Color.blue);
label3.setVisible(true);
label4 = new JLabel("Discrete Matehmatics",JLabel.LEFT);
label4.setForeground(Color.blue);
label4.setVisible(true);
text1 = new JTextField(20);
text1.setEditable(false);
// text1.setBackground(Color.green);
text1.setVisible(true);
text2 = new JTextField(20);
text2.setEditable(false);
// text2.setBackground(Color.green);
text2.setVisible(true);
text3 = new JTextField(20);
text3.setEditable(false);
// text3.setBackground(Color.green);
text3.setVisible(true);
text4 = new JTextField(20);
text4.setEditable(false);
// text4.setBackground(Color.green);
text4.setVisible(true);
String a_course[] =
{" ","BE","MCA"};
String a_branch[] =
{" ","Computer Science","Electronics"};
String a_batch[] =
{" ","2000-2001","2001-2002","2002-2003","2003-2004","2004-2005"};
String a_semester[] =
{" ","I","II","III","IV","V","VI","VII","VIII"};
cb_course = new JComboBox(a_course);
cb_branch = new JComboBox(a_branch);
cb_batch = new JComboBox(a_batch);
cb_semester = new JComboBox(a_semester);
c_parttime = new JCheckBox("Part Time");
c_fulltime = new JCheckBox("Full Time");
Submit = new JButton ("Generate Marksheet");
Submit.setVisible(true);
// Submit.addActionListener(this);
enterMarks = new JButton ("Enter Marks");
enterMarks.setVisible(true);
// enterMarks.addActionListener(this);
reset= new JButton ("Reset");
reset.setVisible(true);
//reset.addActionListener(this);
p = new JPanel(new GridLayout(5,2,2,2));
p.setBorder(BorderFactory.createTitledBorder("Student Details"));
p.add(l_name);
p.add(t_name);
p.add(l_fname);
p.add(t_fname);
p.add(l_rollno);
p.add(t_rollno);
p.add(l_enrolno);
p.add(t_enrollno);
p.add(l_space);
p.add(l_space);
p1 = new JPanel(new GridLayout(0,2,2,2));
p1.setBorder(BorderFactory.createTitledBorder("Course Details"));
p1.add(l_course);
p1.add(cb_course);
p1.add(l_specialization);
p1.add(cb_branch);
p1.add(l_batch);
p1.add(cb_batch);
p1.add(l_semester);
p1.add(cb_semester);
p1.add(c_parttime);
p1.add(c_fulltime);
p1.add(reset);
p1.add(enterMarks);
p2 = new JPanel(new GridLayout(0,2,2,2));
p2.setBorder(BorderFactory.createTitledBorder("Marks Details"));
p2.add(label1);
p2.add(text1);
p2.add(label2);
p2.add(text2);
p2.add(label3);
p2.add(text3);
p2.add(label4);
p2.add(text4);
p2.add(Submit);
p2.setVisible(true);
p3 = new JPanel(new GridLayout(0,1,2,2));
p3.setBorder(BorderFactory.createTitledBorder("Instructions"));
p3.add(l_instruction1);
p3.add(l_instruction2);
p3.add(l_instruction3);
p3.add(l_instruction4);
p3.add(l_instruction8);
p3.add(l_instruction5);
p3.add(l_instruction6);
p3.add(l_instruction7);
JFrame f = new JFrame("Student Marksheet System");
f.getContentPane().setLayout(new GridLayout(2,2,3,3));
f.getContentPane().add(p3);
f.getContentPane().add(p);
f.getContentPane().add(p1);
f.getContentPane().add(p2);
enterMarks.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
String message = "Are you sure all information is correct";
String get_text1;
String title = "Confirmation";
int getcourseindex;
int getbranchindex;
int getsemesterindex;
int getbatchindex;
getcourseindex = cb_course.getSelectedIndex();
getbranchindex = cb_branch.getSelectedIndex();
getsemesterindex = cb_semester.getSelectedIndex();
getbatchindex = cb_branch.getSelectedIndex();
if (c_fulltime.isSelected() == false && c_parttime.isSelected() == false)
JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
return;
if(getcourseindex == 0)
JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
return;
if(getbranchindex == 0)
JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
return;
if(getsemesterindex == 0)
JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
return;
if(getbatchindex == 0)
JOptionPane.showMessageDialog(null,"Atleast one mandatory field is missing","TextField",1);
return;
int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
if(n==0)
get_text1 = t_name.getText();
t_name.setEditable(false);
t_fname.setEditable(false);
t_rollno.setEditable(false);
t_enrollno.setEditable(false);
cb_course.setEnabled(false);
cb_branch.setEnabled(false);
cb_batch.setEnabled(false);
cb_semester.setEnabled(false);
reset.setEnabled(false);
reset.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
String message = "Are you sure to reset the fields";
String title = "Confirmation";
int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
if(n==0)
Submit.setEnabled(true);
cb_course.setSelectedIndex(0);
cb_branch.setSelectedIndex(0);
cb_batch.setSelectedIndex(0);
cb_semester.setSelectedIndex(0);
t_rollno.setText("");
Submit.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
String message = "Confirmation will generate the marksheet";
String title = "Confirmation";
int n = JOptionPane.showConfirmDialog(null,message,title, JOptionPane.YES_NO_OPTION);
if(n==0)
Submit.setEnabled(true);
c_parttime.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
if (c_fulltime.isSelected() == true)
c_fulltime.setSelected(false);
c_fulltime.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
if (c_parttime.isSelected() == true)
c_parttime.setSelected(false);
f.pack();
f.setVisible(true);
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, size().width - 1, size().height - 1);
public void actionPerformed(ActionEvent event){
package marksheet;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class maxLengthText extends PlainDocument
int maxVal=0;
public maxLengthText(int maxLength)
maxVal = maxLength;
publ1ic void insertString(int offset, String str, AttributeSet a) throws BadLocationException
if (getLength() + str.length() > maxVal)
return;
else
try
if(!Double.isNaN(Double.parseDouble(str)))
super.insertString(offset, str, a);
catch(Exception e)
JOptionPane.showMessageDialog(null,"Numbers Only","TextField",1);
offset=0;
}When you post code, please use the [co[i]de][co[i]de] tags. There is a code button above the message textfield.
-
How to change background color in a window? Please help.
Please help me to set background color to my window that includes some panels components.
I have tried
content.setBackground(Color.green); and
frame.setBackground(Color.RED);
but nothing works?
Please what should I change in my code? Thanks already in advance for helping!!
Main parts of my code:
public void addComponentToPane(Container allComponents) throws IOException
definePanels();
allComponents.setLayout(new BoxLayout(allComponents, BoxLayout.Y_AXIS));
allComponents.add(panel_introduction);
allComponents.add(panel_n);
allComponents.add(panel_resultTitle);
allComponents.add(panel_w);
allComponents.add(panel_testing);
allComponents.setVisible(true);
public static void main(String[] args) throws IOException
try {
GraphicsDevice device;
Container content;
JFrame frame = new JFrame("ImageOrder");
device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingApplication app = new SwingApplication();
content = frame.getContentPane();
content.setBackground(Color.green);
app.addComponentToPane(content);
frame.setVisible(true);
finally {
System.out.println("helle");
}import java.awt.Color;
import javax.swing.*;
class Test extends JFrame {
public Test( ){
getContentPane().setBackground(Color.RED);
pack();
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String[] argv) {
new Test().setVisible(true);
} -
Problem in socket communication please help me!
server
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
class SocketServer extends JFrame
implements ActionListener {
JLabel text1, text2;
JButton button1, button2;
JPanel panel;
JTextField textField1, textField2;
ServerSocket server = null;
Socket socket = null;
BufferedReader in1 = null;
PrintWriter out1 = null;
String line1;
String line2;
SocketServer(){ //Begin Constructor
text1 = new JLabel("Send Information:");
text2 = new JLabel("Receive Information:");
textField1 = new JTextField(20);
textField2 = new JTextField(20);
button1 = new JButton("Send");
button2 = new JButton("Receive");
button1.addActionListener(this);
button2.addActionListener(this);
panel = new JPanel();
panel.setLayout(new GridLayout(2,3));
panel.setBackground(Color.lightGray);
getContentPane().add(panel);
panel.add(text1);
panel.add(textField1);
panel.add(button1);
panel.add(text2);
panel.add(textField2);
panel.add(button2);
setSize(500,100);
} //End Constructor
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == button1){
//Send data over socket
String text = textField1.getText();
out1.println(text);
textField1.setText(new String(""));
//Receive text from server
try{
String line1 = in1.readLine();
System.out.println("Text received :" + line1);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
if(source == button2){
textField2.setText(line2);
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
try{
socket = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
try{
in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out1 = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
while(true){
try{
line2 = in1.readLine();
//Send data back to client
out1.println(line2);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
protected void finalize(){
//Clean up
try{
in1.close();
out1.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(-1);
public static void main(String[] args){
SocketServer frame = new SocketServer();
frame.setTitle("Chat (Server)");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
client
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
class SocketClient extends JFrame
implements ActionListener {
JLabel text1, text2;
JButton button1, button2;
JPanel panel;
JTextField textField1, textField2;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
String line3;
String line4;
SocketClient(){ //Begin Constructor
text1 = new JLabel("Send Information:");
text2 = new JLabel("Receive Information:");
textField1 = new JTextField(20);
textField2 = new JTextField(20);
button1 = new JButton("Send");
button2 = new JButton("Receive");
button1.addActionListener(this);
button2.addActionListener(this);
panel = new JPanel();
panel.setLayout(new GridLayout(2,3));
panel.setBackground(Color.lightGray);
getContentPane().add(panel);
panel.add(text1);
panel.add(textField1);
panel.add(button1);
panel.add(text2);
panel.add(textField2);
panel.add(button2);
setSize(500,100);
} //End Constructor
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if(source == button1){
//Send data over socket
String text = textField1.getText();
out.println(text);
textField1.setText(new String(""));
//Receive text from server
try{
String line3 = in.readLine();
System.out.println("Text received :" + line3);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
if(source == button2){
textField2.setText(line4);
public void listenSocket(){
//Create socket connection
try{
socket = new Socket("Localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: Localhost");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
while(true){
try{
line4 = in.readLine();
//Send data back to client
out.println(line4);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
public static void main(String[] args){
SocketClient frame = new SocketClient();
frame.setTitle("Chat (Client)");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
There were problems when executing the application
please help mei had no problem running this... make sure you open the server part first and have that sitting and waiting for the client to connect.... then it should work.
Would you believe that i too am working on the server / socket thing... however my problem is getting the server to read from a database and report back to the client.... -
Scroll bar problems ..Please help!!!!!!
This is what the program looks like. topPanel has newItemPanel on top of it. when you click continue newItemPanel becomes invisible and newItemDescriptionPanel becomes visible. When you click continue newItemDescriptionPanel becomes invisible and priceEnterPanel becomes visible.
I want newItemDescriptionPanel and priceEnterPanel to have a scroll bar. but everything I have tried hasn't worked. I am new. You will see the code is ugly and there is an attempt to add a scrollbar.
Please help
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.lang.System;
public class MainPanel extends JFrame implements ActionListener
private boolean firstRun = true;
private final int ITEM_PLAIN = 0; // Item types
private final int ITEM_CHECK = 1;
private final int ITEM_RADIO = 2;
private JPanel topPanel;
private JPanel newItemPanel;
private JRadioButton onlineAuctionRadio;
private JRadioButton fixedPriceRadio;
private ButtonGroup bg;
private JButton continueButton;
private JLabel blankLabel; //used to give space between things
private JPanel newItemDescriptionPanel;
private JPanel takeAdditionalSpacePanelCheckBox;
private JPanel takeAdditionalSpacePanel;
private JPanel takeAdditionalSpacePanelLabel;
private JPanel takeAdditionalSpacePanelLabel2;
private JPanel takeAdditionalSpacePanel2;
private JPanel takeAdditionalSpacePanel3;
private JPanel takeAdditionalSpacePanel4;
private JPanel takeAdditionalSpacePanel5;
JScrollPane displayScroller;
JEditorPane itemDescriptionTextArea;
GridBagLayout gridbag;
GridBagConstraints gbc;
private JCheckBox secondCategoryCheckBox;
private JLabel itemTitleLabel;
private JLabel requiredLabel, requiredLabel2;
private JLabel requiredStarLabel;
private JTextField itemTitleTextField;
private JLabel subtitleLabel;
private JTextField subtitleTextField;
private JLabel itemDescriptionLabel;
private JButton itemDescriptionContinueButton;
private JLabel percentageLabel;
//------- price enter page ----------------
private JLabel startingPriceLabel;
private JLabel dollarSignLabel;
private JTextField startingPriceTextField;
private JPanel fillUpSpacePanel;
private JPanel fillUpSpacePanel1;
private JPanel fillUpSpacePanel2;
private JLabel buyItNowLabel;
private JPanel fillUpSpacePanel3;
private JLabel dollarSignLabel2;
private JTextField buyItNowTextField;
private JPanel fillUpSpacePanel4;
private JPanel fillUpSpacePanel5;
private JPanel fillUpSpacePanel6;
private JPanel fillUpSpacePanel7;
private JPanel fillUpSpacePanel8;
private JPanel fillUpSpacePanel9;
private JPanel fillUpSpacePanel10;
private JPanel fillUpSpacePanel11;
private JPanel fillUpSpacePanel12;
private JPanel fillUpSpacePanel13;
private JPanel fillUpSpacePanel14;
private JPanel fillUpSpacePanel15;
private JPanel fillUpSpacePanel16;
private JPanel fillUpSpacePanel17;
private JPanel fillUpSpacePanel18;
private JLabel donatePercentageLabel;
private JTextField donatePercentageTextField;
private JPanel fSp; // fill space panel
private JPanel fSp1;
private JPanel fSp2;
private JPanel fSp3;
private JPanel fSp4;
private JPanel fSp5;
private JPanel fSp6;
private JPanel fSp7;
private JPanel fSp8;
private JPanel fSp9;
private JLabel numberOfPicturesLabel;
private JTextField numberOfPicturesTextField;
private JCheckBox superSizePicturesCheckBox;
private JLabel superSizePicturesLabel;
private JRadioButton standardPictureRadioButton;
private JRadioButton picturePackRadioButton;
private JCheckBox listingDesignerCheckBox;
private ButtonGroup bgPictures;
private JCheckBox valuePackCheckBox;
private JCheckBox galleryPictureCheckBox;
private JCheckBox subtitleCheckBox;
private JCheckBox boldCheckBox;
private JCheckBox borderCheckBox;
private JCheckBox highlightCheckBox;
private JCheckBox featuredPlusCheckBox;
private JCheckBox galleryFeaturedCheckBox;
private JLabel homePageFeaturedLabel;
private JComboBox homePageFeaturedComboBox;
private JCheckBox giftCheckBox;
JScrollPane priceEnterPanelScroll;
private JButton backToRadioButton;
private JButton backToItemDescriptionButton;
private JPanel priceEnterPanel;
private final static String RADIOPANEL = "JPanel with radios";
private final static String DESCRIPTIONPANEL = "JPanel with description";
private final static String PRICEENTERPANEL = "JPanel with price entering";
private JPanel cards;
private JMenuBar menuBar;
private JMenu menuFile;
private JMenu menuEdit;
private JMenu menuProperty;
private JMenuItem menuPropertySystem;
private JMenuItem menuPropertyEditor;
private JMenuItem menuPropertyDisplay;
private JMenu menuFileNew;
private JMenuItem menuFileNewAccount;
private JMenuItem menuFileNewItem;
private JMenuItem menuFileOpen;
private JMenuItem menuFileSave;
private JMenuItem menuFileSaveAs;
private JMenuItem menuFileExit;
private JMenuItem menuEditCopy;
private JMenuItem menuEditCut;
private JMenuItem menuEditPaste;
public MainPanel()
requiredLabel = new JLabel ("* Required");
requiredLabel.setForeground (Color.red);
requiredLabel2 = new JLabel ("* Required");
requiredLabel2.setForeground (Color.red);
requiredStarLabel = new JLabel ("*");
requiredStarLabel.setForeground (Color.green);
setTitle( "photo galleries" );
setSize( 310, 130 );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
topPanel.setBorder (BorderFactory.createTitledBorder ("TopPanel"));
//topPanel.setPreferredSize(new Dimension (300,300));
getContentPane().add( topPanel );
topPanel.setVisible (false);
// For New Item Panel
ButtonListener ears = new ButtonListener();
blankLabel = new JLabel (" "); // used to give space between radio buttons and continue button
continueButton = new JButton ("Continue >");
continueButton.addActionListener (ears);
backToRadioButton = new JButton ("< back");
backToRadioButton.addActionListener (ears);
itemDescriptionContinueButton = new JButton ("Continue >");
itemDescriptionContinueButton.addActionListener (ears);
backToItemDescriptionButton = new JButton ("< back");
backToItemDescriptionButton.addActionListener (ears);
newItemPanel = new JPanel();
newItemPanel.setLayout (new BoxLayout(newItemPanel, BoxLayout.Y_AXIS));
//topPanel.add (newItemPanel, BorderLayout.NORTH);
newItemPanel.setBorder (BorderFactory.createTitledBorder ("NewItemPanel"));
newItemPanel.setVisible (false);
onlineAuctionRadio = new JRadioButton ("Sold item at online Auction" );
fixedPriceRadio = new JRadioButton ("Sold at a Fixed Price");
bg = new ButtonGroup();
bg.add(onlineAuctionRadio);
bg.add(fixedPriceRadio);
onlineAuctionRadio.addActionListener (ears);
fixedPriceRadio.addActionListener (ears);
newItemPanel.add (onlineAuctionRadio);
newItemPanel.add (fixedPriceRadio);
newItemPanel.add (blankLabel);
newItemPanel.add (continueButton);
// ------ After continue pressed ---------
newItemDescriptionPanel = new JPanel();
newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
newItemPanel.add (newItemDescriptionPanel, BorderLayout.NORTH);
newItemDescriptionPanel.setBorder (BorderFactory.createTitledBorder ("newItemDescriptionPanel"));
secondCategoryCheckBox = new JCheckBox ("The item was listed in a second category");
newItemDescriptionPanel.setVisible (false);
itemTitleLabel = new JLabel ("Item title");
itemTitleTextField = new JTextField (30);
subtitleLabel = new JLabel ("Subtitle ($0.50)");
subtitleTextField = new JTextField (30);
itemDescriptionLabel = new JLabel ("Item description");
itemDescriptionTextArea = new JEditorPane();
itemDescriptionTextArea.setContentType( "text/html" );
itemDescriptionTextArea.setEditable( false );
itemDescriptionTextArea.setPreferredSize(new Dimension (500,250));
itemDescriptionTextArea.setFont(new Font( "Serif", Font.PLAIN, 12 ));
itemDescriptionTextArea.setForeground( Color.black );
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
displayScroller = new JScrollPane( itemDescriptionTextArea );
gridbag = new GridBagLayout ();
gridbag.setConstraints( displayScroller, gbc );
itemDescriptionTextArea.setEditable( true );
takeAdditionalSpacePanelCheckBox = new JPanel(new FlowLayout(FlowLayout.LEFT));
takeAdditionalSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanelLabel = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanelLabel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));//<--added, to take additional space
takeAdditionalSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
takeAdditionalSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
//takeAdditionalSpacePanel2.setBorder (BorderFactory.createTitledBorder ("Additonal 2"));
takeAdditionalSpacePanelCheckBox.add (secondCategoryCheckBox);
newItemDescriptionPanel.add (takeAdditionalSpacePanelCheckBox);
//newItemDescriptionPanel.add (blankLabel);
takeAdditionalSpacePanelLabel.add (itemTitleLabel);
takeAdditionalSpacePanelLabel.add (requiredLabel);
newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel);
//newItemDescriptionPanel.add (itemTitleTextField);
takeAdditionalSpacePanel.add(itemTitleTextField);//<--add textfield to panel
newItemDescriptionPanel.add (takeAdditionalSpacePanel);//<--add panel to boxlayout panel
takeAdditionalSpacePanelLabel2.add (subtitleLabel);
newItemDescriptionPanel.add (takeAdditionalSpacePanelLabel2);
takeAdditionalSpacePanel2.add (subtitleTextField);
newItemDescriptionPanel.add (takeAdditionalSpacePanel2);
takeAdditionalSpacePanel4.add (itemDescriptionLabel);
//takeAdditionalSpacePanel4.add (requiredLabel2);
newItemDescriptionPanel.add (takeAdditionalSpacePanel4);
takeAdditionalSpacePanel3.add (displayScroller);
newItemDescriptionPanel.add (takeAdditionalSpacePanel3);
takeAdditionalSpacePanel5.add (backToRadioButton);
takeAdditionalSpacePanel5.add (itemDescriptionContinueButton);
newItemDescriptionPanel.add (takeAdditionalSpacePanel5);
//newItemDescriptionPanel.setLayout (new BoxLayout(newItemDescriptionPanel, BoxLayout.Y_AXIS));
//----------- Price Enter Page ----------------
priceEnterPanel = new JPanel();
priceEnterPanel.setLayout (new BoxLayout(priceEnterPanel, BoxLayout.Y_AXIS));
newItemDescriptionPanel.add (priceEnterPanel, BorderLayout.NORTH);
priceEnterPanel.setBorder (BorderFactory.createTitledBorder ("Price enter Panel"));
priceEnterPanel.setVisible (false);
priceEnterPanelScroll = new JScrollPane (priceEnterPanel);
topPanel.add (priceEnterPanelScroll);
standardPictureRadioButton = new JRadioButton ("Standard");
picturePackRadioButton = new JRadioButton ("Picture Pack ($1.00 for up to 6 pictures or $1.50 for 7 to 12 pictures)");
bgPictures = new ButtonGroup();
bgPictures.add(standardPictureRadioButton);
bgPictures.add(picturePackRadioButton);
standardPictureRadioButton.addActionListener (ears);
picturePackRadioButton.addActionListener (ears);
superSizePicturesCheckBox = new JCheckBox ("Supersize Pictures ($0.75)");
listingDesignerCheckBox = new JCheckBox ("Listing designer $0.10");
valuePackCheckBox = new JCheckBox ("Get the Essentials for less! Gallery, Subtitle, Listing Designer. $0.65 (save $0.30)");
superSizePicturesCheckBox.setEnabled (false);
superSizePicturesCheckBox.addActionListener (ears);
listingDesignerCheckBox.addActionListener (ears);
valuePackCheckBox.addActionListener (ears);
startingPriceLabel = new JLabel ("Starting Price");
dollarSignLabel = new JLabel ("$");
startingPriceTextField = new JTextField (10);
buyItNowLabel = new JLabel ("Buy It Now");
dollarSignLabel2 = new JLabel ("$");
buyItNowTextField = new JTextField (10);
donatePercentageLabel = new JLabel ("Donate percentage of sale");
donatePercentageTextField = new JTextField (2);
donatePercentageTextField.setText ("0");
percentageLabel = new JLabel ("%");
// Right-justify the text
donatePercentageTextField.setHorizontalAlignment(JTextField.RIGHT);
numberOfPicturesLabel = new JLabel ("Number of pictures used");
numberOfPicturesTextField = new JTextField (1);
numberOfPicturesTextField.setText ("0");
galleryPictureCheckBox = new JCheckBox ("Gallery ($0.35) [Requires a picture]");
subtitleCheckBox = new JCheckBox ("Subtitle ($0.50)");
boldCheckBox = new JCheckBox ("Bold ($1.00)");
borderCheckBox = new JCheckBox ("Border ($3.00)");
highlightCheckBox = new JCheckBox ("Highlight ($5.00)");
featuredPlusCheckBox = new JCheckBox ("Featured Plus! ($19.95)");
galleryFeaturedCheckBox = new JCheckBox ("Gallery Featured ($19.95) [Requires a picture]");
homePageFeaturedLabel = new JLabel ("Home Page Featured ($39.95 for 1 item, $79.95 for 2 or more items)");
homePageFeaturedComboBox = new JComboBox ();
homePageFeaturedComboBox.addItem (("None..."));
homePageFeaturedComboBox.addItem (("1 item"));
homePageFeaturedComboBox.addItem (("2 or more items"));
giftCheckBox = new JCheckBox ("Show as a gift ($0.25)");
fillUpSpacePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel10 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel11 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel12 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel13 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel14 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel15 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel16 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel17 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel18 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp7 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp8 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fSp9 = new JPanel(new FlowLayout(FlowLayout.LEFT));
fillUpSpacePanel.add (startingPriceLabel);
fillUpSpacePanel.add (requiredLabel2);
priceEnterPanel.add (fillUpSpacePanel);
fillUpSpacePanel2.add (dollarSignLabel);
fillUpSpacePanel2.add (startingPriceTextField);
priceEnterPanel.add (fillUpSpacePanel2);
// fillUpSpacePanel1.add (backToItemDescriptionButton);
// priceEnterPanel.add (fillUpSpacePanel1);
fillUpSpacePanel3.add (buyItNowLabel);
priceEnterPanel.add (fillUpSpacePanel3);
fillUpSpacePanel4.add (dollarSignLabel2);
fillUpSpacePanel4.add (buyItNowTextField);
priceEnterPanel.add (fillUpSpacePanel4);
fillUpSpacePanel1.add (donatePercentageLabel);
priceEnterPanel.add (fillUpSpacePanel1);
fillUpSpacePanel5.add (donatePercentageTextField);
fillUpSpacePanel5.add (percentageLabel);
priceEnterPanel.add (fillUpSpacePanel5);
fillUpSpacePanel6.add (numberOfPicturesLabel);
priceEnterPanel.add (fillUpSpacePanel6);
fillUpSpacePanel7.add (numberOfPicturesTextField);
priceEnterPanel.add (fillUpSpacePanel7);
fillUpSpacePanel8.add (standardPictureRadioButton);
priceEnterPanel.add (fillUpSpacePanel8);
fillUpSpacePanel10.add (blankLabel);
fillUpSpacePanel10.add (superSizePicturesCheckBox);
priceEnterPanel.add (fillUpSpacePanel10);
fillUpSpacePanel9.add (picturePackRadioButton);
priceEnterPanel.add (fillUpSpacePanel10);
fillUpSpacePanel11.add (picturePackRadioButton);
priceEnterPanel.add (fillUpSpacePanel11);
fillUpSpacePanel12.add (listingDesignerCheckBox);
priceEnterPanel.add (fillUpSpacePanel12);
fillUpSpacePanel13.add (valuePackCheckBox);
priceEnterPanel.add (fillUpSpacePanel13);
fSp.add (galleryPictureCheckBox);
priceEnterPanel.add (fSp);
fSp1.add (subtitleCheckBox);
priceEnterPanel.add (fSp1);
fSp2.add (boldCheckBox);
priceEnterPanel.add (fSp2);
fSp3.add (borderCheckBox);
priceEnterPanel.add (fSp3);
fSp4.add (highlightCheckBox);
priceEnterPanel.add (fSp4);
fSp5.add (featuredPlusCheckBox);
priceEnterPanel.add (fSp5);
fSp6.add (galleryFeaturedCheckBox);
priceEnterPanel.add (fSp6);
fSp7.add (homePageFeaturedLabel);
priceEnterPanel.add (fSp7);
fSp8.add (homePageFeaturedComboBox);
priceEnterPanel.add (fSp8);
fSp9.add (giftCheckBox);
priceEnterPanel.add (fSp9);
newItemDescriptionPanel.add (priceEnterPanelScroll);
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(newItemPanel, RADIOPANEL);
cards.add(newItemDescriptionPanel, DESCRIPTIONPANEL);
cards.add(priceEnterPanel, PRICEENTERPANEL);
topPanel.add(cards, BorderLayout.NORTH);
// Create the menu bar
menuBar = new JMenuBar();
// Set this instance as the application's menu bar
setJMenuBar( menuBar );
// Build the property sub-menu
menuProperty = new JMenu( "Properties" );
menuProperty.setMnemonic( 'P' );
// Create property items
menuPropertySystem = CreateMenuItem( menuProperty, ITEM_PLAIN,
"System...", null, 'S', null );
menuPropertyEditor = CreateMenuItem( menuProperty, ITEM_PLAIN,
"Editor...", null, 'E', null );
menuPropertyDisplay = CreateMenuItem( menuProperty, ITEM_PLAIN,
"Display...", null, 'D', null );
//Build the File-New sub-menu
menuFileNew = new JMenu ("New");
menuFileNew.setMnemonic ('N');
//Create File-New items
menuFileNewItem = CreateMenuItem( menuFileNew, ITEM_PLAIN,
"Item", null, 'A', null );
menuFileNewAccount = CreateMenuItem( menuFileNew, ITEM_PLAIN,
"Account", null, 'A', null );
// Create the file menu
menuFile = new JMenu( "File" );
menuFile.setMnemonic( 'F' );
menuBar.add( menuFile );
//Add the File-New menu
menuFile.add( menuFileNew );
// Create the file menu
// Build a file menu items
menuFileOpen = CreateMenuItem( menuFile, ITEM_PLAIN, "Open...",
new ImageIcon( "open.gif" ), 'O',
"Open a new file" );
menuFileSave = CreateMenuItem( menuFile, ITEM_PLAIN, "Save",
new ImageIcon( "save.gif" ), 'S',
" Save this file" );
menuFileSaveAs = CreateMenuItem( menuFile, ITEM_PLAIN,
"Save As...", null, 'A',
"Save this data to a new file" );
// Add the property menu
menuFile.addSeparator();
menuFile.add( menuProperty );
menuFile.addSeparator();
menuFileExit = CreateMenuItem( menuFile, ITEM_PLAIN,
"Exit", null, 'X',
"Exit the program" );
//menuFileExit.addActionListener(this);
// Create the file menu
menuEdit = new JMenu( "Edit" );
menuEdit.setMnemonic( 'E' );
menuBar.add( menuEdit );
// Create edit menu options
menuEditCut = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Cut", null, 'T',
"Cut data to the clipboard" );
menuEditCopy = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Copy", null, 'C',
"Copy data to the clipboard" );
menuEditPaste = CreateMenuItem( menuEdit, ITEM_PLAIN,
"Paste", null, 'P',
"Paste data from the clipboard" );
public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
ImageIcon image, int acceleratorKey,
String sToolTip )
// Create the item
JMenuItem menuItem;
switch( iType )
case ITEM_RADIO:
menuItem = new JRadioButtonMenuItem();
break;
case ITEM_CHECK:
menuItem = new JCheckBoxMenuItem();
break;
default:
menuItem = new JMenuItem();
break;
// Add the item test
menuItem.setText( sText );
// Add the optional icon
if( image != null )
menuItem.setIcon( image );
// Add the accelerator key
if( acceleratorKey > 0 )
menuItem.setMnemonic( acceleratorKey );
// Add the optional tool tip text
if( sToolTip != null )
menuItem.setToolTipText( sToolTip );
// Add an action handler to this menu item
menuItem.addActionListener( this );
menu.add( menuItem );
return menuItem;
public void actionPerformed( ActionEvent event )
CardLayout cl = (CardLayout)(cards.getLayout());
if (event.getSource() == menuFileExit)
System.exit(0);
if (event.getSource() == menuFileNewAccount)
System.out.println ("hlkadflkajfalkdjfalksfj");
if (event.getSource() == menuFileNewItem){
if (firstRun){
newItemPanel.setVisible (true);
topPanel.setVisible (true);
cl.show(cards,RADIOPANEL);
firstRun = false;
//System.out.println( event );
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
CardLayout cl = (CardLayout)(cards.getLayout());
// cl.show(cards, (String)evt.getItem());
if (event.getSource() == continueButton){
if (!(onlineAuctionRadio.isSelected()) && !(fixedPriceRadio.isSelected()))
JOptionPane.showMessageDialog(null, "You must select at least one.", "Error", JOptionPane.ERROR_MESSAGE);
else{
if (onlineAuctionRadio.isSelected()){
cl.show (cards, DESCRIPTIONPANEL);
//newItemPanel.setVisible (false);
//newItemDescriptionPanel.setVisible (true);
if (event.getSource() == itemDescriptionContinueButton){
if (itemTitleTextField.getText().trim().equalsIgnoreCase(""))
JOptionPane.showMessageDialog(null, "You must enter a title.", "Error", JOptionPane.ERROR_MESSAGE);
else
cl.show (cards, PRICEENTERPANEL);
if (event.getSource() == backToRadioButton){
cl.show (cards, RADIOPANEL);
if (event.getSource() == backToItemDescriptionButton){
cl.show(cards, DESCRIPTIONPANEL);
if (standardPictureRadioButton.isSelected()){
superSizePicturesCheckBox.setEnabled (true);
if (picturePackRadioButton.isSelected()){
superSizePicturesCheckBox.setEnabled (false);
} //end of action performed
}Mostly I see there is about 100 times as much code as I care to look at.
So you don't know how to get a panel in a scroll pane, and then get that scroll pane into your GUI? Then try doing that by itself, not encumbered with 10000 lines of irrelevant code. Once you have it working, plug it into the big lump of code. Or if you can't get it working, ask about the small problem here. -
Hi i want to create custom data source as i have read in different post and also on sun site
I tried to create one one for my self,
where am getting stream from tcp port.
before that i test the data by using socket programming, i saved the input stream into file and played and its working fine and then i transfer that file using avtransmiter2.java and it work fine again its mean it confirm that the data i am getting from skype is working fine . now my question is how to get that input stream and instead of saving to the file i can play it using jmf player or send it on rtp session. i read different post how to create custom data source from inputstreams but have not work for me ... i modified a user code posted http://archives.java.sun.com/cgi-bin/wa?A2=ind0106&L=jmf-interest&D=0&P=25865 in that post some body recommanded to implement seekable so i implemented that one als in that code..... below is the code
the error is
LoadInputStream.loadBytes() - realizing player
Exception in thread "JMF thread: com.sun.media.PlaybackEngine@8ed465[ com.sun.media.PlaybackEngine@8ed465 ] ( configureThread)" java.lang.NullPointerException
at com.skype.sample.InputSourceStream.read(InputSourceStream.java:89)
at com.sun.media.parser.BasicPullParser.readBytes(BasicPullParser.java:142)
at com.sun.media.parser.BasicPullParser.readBytes(BasicPullParser.java:114)
at com.sun.media.parser.BasicPullParser.readInt(BasicPullParser.java:191)
at com.sun.media.parser.audio.AuParser.readHeader(AuParser.java:109)
at com.sun.media.parser.audio.AuParser.getTracks(AuParser.java:76)
at com.sun.media.BasicSourceModule.doRealize(BasicSourceModule.java:180)
at com.sun.media.PlaybackEngine.doConfigure1(PlaybackEngine.java:229)
at com.sun.media.PlaybackEngine.doConfigure(PlaybackEngine.java:193)
at com.sun.media.ConfigureWorkThread.process(BasicController.java:1370)
at com.sun.media.StateTransitionWorkThread.run(BasicController.java:1339)
i need urgent help to this matter so please help me in that i would be very thankfulll ......
below is the code
skype use the standard audio format
Audio format
File: WAV PCM
Sockets: raw PCM samples
16 KHz mono, 16 bit
Note
import javax.media.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class LoadInputStream extends JFrame implements ControllerListener {
private Player player;
/** Creates new LoadInputStream */
public LoadInputStream() {
try{
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket SkypeServer = null;
DataInputStream is;
Socket clientSocket = null;
try {
SkypeServer = new ServerSocket(4447);
catch (IOException e) {
System.out.println(e);
// Open input stream
clientSocket = SkypeServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
loadBytes(is);
setBounds(100, 100, 300, 300);
setVisible(true);
catch(Exception e){
System.out.println(e);
/* Loads the given byte [] into the MediaPlayer and starts playing it immediately. */
public void loadBytes(InputStream is){
DataSource ds=new DataSource(is);
System.out.println("LoadInputStream.loadBytes() - Creating DataSource (InputStream)");
System.out.println("LoadInputStream.loadBytes() - Creating Player");
try {
player = Manager.createPlayer(ds);
} catch(NoPlayerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("LoadInputStream.loadBytes() - Adding Controller Listener");
player.addControllerListener(this);
System.out.println("LoadInputStream.loadBytes() - realizing player");
player.realize();
public static void main(String[] args){
new LoadInputStream();
public void controllerUpdate(javax.media.ControllerEvent e) {
if(e instanceof RealizeCompleteEvent){
System.out.println("Adding visual component");
getContentPane().add(player.getVisualComponent());
player.start();
=============================Datasource==========================================================
import java.io.*;
import java.nio.ByteBuffer;
import javax.media.*;
import javax.media.protocol.*;
public class DataSource extends PullDataSource {
private InputStream is;
private byte [] bytes;
/** Creates new MediaViewerDataSource */
public DataSource(InputStream is) {
super();
this.is = is;
try{
int byteCount = is.available();
bytes = new byte [byteCount];
is.read(bytes);
catch (Exception e){
System.out.println(e);
public PullSourceStream [] getStreams() {
PullSourceStream [] streams = new PullSourceStream [1];
InputSourceStream iss = new InputSourceStream(new ByteArrayInputStream(bytes), new FileTypeDescriptor(ContentDescriptor.RAW_RTP));
streams[0] = iss;
return streams;
public void connect() {}
public void disconnect() {}
public String getContentType() {
return new String("audio.x-wav");
public MediaLocator getLocator() {
return null;
public void initCheck() {}
public void setLocator(MediaLocator source) {}
public void start() {}
public void stop() {}
public Object getControl(String s){
return null;
public Object [] getControls(){
return null;
public Time getDuration(){
return null;
=================================InputStream======================================================
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PullSourceStream;
import javax.media.protocol.Seekable;
import javax.media.protocol.SourceStream;
* Build a source stream out of an input stream.
* @see DataSource
* @see SourceStream
* @see java.io.InputStream
* @version %I%, %E%.
public
class InputSourceStream implements PullSourceStream, Seekable {
protected InputStream stream;
protected boolean eosReached;
ContentDescriptor contentType;
protected ByteBuffer inputBuffer;
* Construct an <CODE>InputSourceStream</CODE> from an input stream.
* @param s The input stream to build the source stream from.
* @param type The content-type of the source stream.
public InputSourceStream(InputStream s, ContentDescriptor type) {
stream = s;
eosReached = false;
contentType = type;
* Get the content type for this stream.
* @return content descriptor for the stream.
public ContentDescriptor getContentDescriptor() {
return contentType;
* Obtain the content length
* @return content length for this stream.
public long getContentLength() {
return SourceStream.LENGTH_UNKNOWN;
* Query if the next read will block.
* @return true if a read will block.
public boolean willReadBlock() {
if( eosReached == true) {
return true;
} else {
try {
return stream.available() == 0;
} catch (IOException e) {
return true;
* Read a buffer of data.
* @param buffer The buffer to read data into.
* @param offset The offset into the buffer for reading.
* @param length The number of bytes to read.
* @return The number of bytes read or -1 indicating end-of-stream.
public int read(byte[] buffer, int offset, int length) throws IOException {
int bytesRead = stream.read(buffer, offset, length);
if( bytesRead == -1) {
eosReached = true;
inputBuffer.get(buffer,offset,length);
return bytesRead;
* Turn the stream off.
* @exception IOException Thrown if there is a problem closing the stream.
public void close() throws IOException {
stream.close();
* Return if the end of stream has been reached.
* @return true if the end of the stream has been reached.
// $jdr: This is a bug. Need to figure out
// the "correct" way to determine, before a read
// is done, if we're at EOS.
public boolean endOfStream() {
return eosReached;
* Returns an zero length array because no controls
* are supported.
* @return a zero length <code>Object</code> array.
public Object[] getControls() {
return new Object[0];
* Returns <code>null</code> because no controls are implemented.
* @return <code>null</code>.
public Object getControl(String controlName) {
return null;
public long seek(long where) {
try {
inputBuffer.position((int)(where));
return where;
catch (IllegalArgumentException E) {
return this.tell(); // staying at the current position
public long tell() {
return inputBuffer.position();
public void SeekableStream(ByteBuffer byteBuffer) {
inputBuffer = byteBuffer;
this.seek((long)(0)); // set the ByteBuffer to to beginning
public boolean isRandomAccess() {
// TODO Auto-generated method stub
return false;
}Use a BufferedImage where you draw the other images.
You have to know the size.
For example if the size is (50*50) for each image :
int width =50;
int height = 50;
BufferedImage bufIm = new BufferedImage(width*3,height*3,BufferedImage.TYPE_INT_ARGB);
Graphics gr = bufIm.createGraphics();
int k, j;
Toolkit tk = Toolkit.getDefaultToolkit();
Image imTemp;
for (k = 0; k<3; k++) {
for (j = 0; j<3; j++) {
imTemp = tk.getImage(imageNames[k][j]);
gr.drawImage(imTemp,width*k,height*j, this); // replace this by the Image observer you want (this if you are in a panel for example)
}After that bufIm contains the images as you want and you can paint it on a Graphics.
Denis -
How to empty the JTextField automatically? Please HELP me.
Hello,
This is my full listing program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class PortGUI extends JFrame
private JButton btOk;
private JButton btCancel;
private JButton btReply;
private JLabel lblServIP;
private JLabel lblAuth;
private JLabel lblThrd;
private JLabel lblAcc;
private JLabel lblMax;
private JLabel lblAuthent;
private JLabel lblAdm;
private JLabel lblReplServ;
private JCheckBox chkUsers;
private JCheckBox chkEnbDbg;
private JOptionPane pnlErr = new JOptionPane();
public PortGUI()
// Create main panel
JPanel topPanel = new JPanel();
topPanel.setLayout(null);
getContentPane().add( topPanel );
// Create Server Settings panel
JPanel panelsett = new JPanel();
panelsett.setLayout(null);
panelsett.setBounds(5,5,680, 200);
// panelsett containers
final JTextField fldServIP = new JTextField();
fldServIP.setBounds( 160, 30, 100, 25 );
fldServIP.setFocusAccelerator( 'v' );
panelsett.add(fldServIP);
lblServIP = new JLabel( "Server IP" );
lblServIP.setBounds( 20, 30, 100, 25 );
lblServIP.setLabelFor( fldServIP );
panelsett.add(lblServIP);
final JTextField fldAuth = new JTextField();
fldAuth.setBounds( 600, 30, 50, 25 );
fldAuth.setFocusAccelerator( 'v' );
panelsett.add(fldAuth);
lblAuth = new JLabel( "Incoming Radius Authentication Port");
lblAuth.setBounds( 350, 30, 300, 25 );
lblAuth.setLabelFor(fldAuth);
panelsett.add(lblAuth);
final JTextField fldThrd = new JTextField();
fldThrd.setBounds( 160, 60, 50, 25 );
fldThrd.setFocusAccelerator( 'a' );
panelsett.add(fldThrd);
lblThrd = new JLabel( "Worker Threads" );
lblThrd.setBounds( 20, 60, 100, 25 );
lblThrd.setLabelFor(fldThrd);
panelsett.add(lblThrd);
final JTextField fldAcc = new JTextField();
fldAcc.setBounds( 600, 60, 50, 25 );
fldAcc.setFocusAccelerator( 'a' );
panelsett.add( fldAcc );
lblAcc = new JLabel( "Incoming Radius Accounting Port" );
lblAcc.setBounds( 350, 60, 300, 25 );
lblAcc.setLabelFor( fldAcc );
panelsett.add( lblAcc );
final JTextField fldMax = new JTextField();
fldMax.setBounds( 160, 90, 50, 25 );
fldMax.setFocusAccelerator( 'c' );
panelsett.add( fldMax );
lblMax = new JLabel( "Maximum Consoles" );
lblMax.setBounds( 20, 90, 200, 25 );
lblMax.setLabelFor( fldMax );
panelsett.add(lblMax);
// Create combo box
String[] AuthStrings = {"Local Server", "Proxy Server", "Local and Proxy"};
JComboBox AuthList = new JComboBox(AuthStrings);
AuthList.setSelectedIndex(2);
AuthList.setSelectedItem(null);
AuthList.setBounds(450, 90, 200, 25);
panelsett.add(AuthList);
lblAuthent = new JLabel( "Authenticator" );
lblAuthent.setBounds( 350, 90, 100, 25 );
lblAuthent.setLabelFor( AuthList);
panelsett.add(lblAuthent);
final JTextField fldAdm = new JTextField();
fldAdm.setBounds( 160, 120, 50, 25 );
fldAdm.setFocusAccelerator( 'c' );
panelsett.add( fldAdm );
lblAdm = new JLabel( "Admin TCP Port" );
lblAdm.setBounds( 20, 120, 150, 25 );
lblAdm.setLabelFor( fldAdm );
panelsett.add(lblAdm);
// create checkbox
chkUsers = new JCheckBox("Cache Users in Memory");
chkUsers.setBounds(350, 120, 250, 25);
chkUsers.setMnemonic('m');
chkUsers.setSelected(false);
panelsett.add(chkUsers);
final JTextField fldReplServ = new JTextField();
fldReplServ.setBounds( 160, 150, 100, 25 );
fldReplServ.setFocusAccelerator( 'c' );
panelsett.add( fldReplServ );
lblReplServ = new JLabel( "Replication Server IP" );
lblReplServ.setBounds( 20, 150, 200, 25 );
lblReplServ.setLabelFor(fldReplServ);
panelsett.add(lblReplServ);
chkEnbDbg = new JCheckBox("Enable Debug Trace Output");
chkEnbDbg.setBounds(350, 150, 250, 25);
chkEnbDbg.setMnemonic('n');
chkEnbDbg.setSelected(false);
panelsett.add(chkEnbDbg);
Border etched;
etched = BorderFactory.createLoweredBevelBorder();
TitledBorder title;
title = BorderFactory.createTitledBorder(etched, "Server Settings");
title.setTitleJustification(TitledBorder.LEFT);
panelsett.setBorder(title);
topPanel.add(panelsett);
// Create a button
btOk = new JButton( "OK" );
btOk.setBorder(BorderFactory.createRaisedBevelBorder());
btOk.setBounds( 170, 270, 100, 35 );
btOk.setEnabled(false );
topPanel.add(btOk);
btReply = new JButton( "Apply" );
btReply.setBorder(BorderFactory.createRaisedBevelBorder());
btReply.setBounds( 300, 270, 100, 35 );
topPanel.add(btReply);
btCancel = new JButton( "Cancel" );
btCancel.setBorder(BorderFactory.createRaisedBevelBorder());
btCancel.setBounds( 420, 270, 100, 35 );
btCancel.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
System.exit(0);
topPanel.add(btCancel);
// Action for each components
fldServIP.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldServIP.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldServIP.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldServIP.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldAuth.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldAuth.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldAuth.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldAuth.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldThrd.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldThrd.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldThrd.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldThrd.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldAcc.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldAcc.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldAcc.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldAcc.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldMax.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldMax.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldMax.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldMax.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldAdm.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldAdm.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldAdm.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldAdm.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
fldReplServ.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldReplServ.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldReplServ.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
public void removeUpdate( DocumentEvent event )
// Prevent the user from entering a blank field
if( fldReplServ.getText().length() == 0 )
btOk.setEnabled( false );
else
// Do the same error checking as insertUpdate()
insertUpdate( event );
public void changedUpdate( DocumentEvent event )
// Nothing to do here
public static void main(String[] args)
//int windowWidth, windowHeight;
int windowWidth = 700;
int windowHeight = 400;
PortGUI window = new PortGUI();
window.setTitle("");
Dimension windowSize = window.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setSize(windowWidth, windowHeight);
window.setLocation((screenSize.width - windowWidth) / 2, (screenSize.height - windowHeight) / 2);
window.setVisible(true);
window.setResizable(false);
On that listing program, my problem is in field document listener, that is:
fldThrd.getDocument().addDocumentListener(new DocumentListener()
public void insertUpdate( DocumentEvent event )
String sString = fldThrd.getText();
try
int iValue = Integer.parseInt( sString );
btOk.setEnabled( true );
catch( NumberFormatException e )
if( fldThrd.getText().length() == 4 )
JOptionPane.showMessageDialog(pnlErr,
"Please try again",
"Error Message",
JOptionPane.ERROR_MESSAGE);
if I execute this program, the textfield can only receive integer input. If input is string til 4 times, the dialog panel will display error message. After that, textfield must be empty (delete automatically).
I want to ask you about how I can emptying that textfield automatically after the dialog panel is appear?
Please help me to get out from my problem.
Thank's for your help,
harHi,
To empty the text file, use the method setText("").
eg. fldServIP.setText("");
fldServIP is one of your textfield. So whereever you are showing the dialog box, use setText("") for the corresponding textfields.
All the best -
Jtable Update problem .. Please help !!!!!!!!
Hi ,
I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
Here is the code .... Please see it and tell me if it is possible :
package newpackage;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.text.*;
import newpackage.ExcelExporter;
import java.awt.Dimension;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.*;
import java.io.*;
import java.util.Random.*;
import javax.swing.*;
import java.text.*;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class tab7le extends javax.swing.JFrame {
Vector columnNames = new Vector();
Vector data = new Vector();
Connection con;
Statement stat;
ResultSet rs;
int li_cols = 0;
Vector allRows;
Vector row;
Vector newRow;
Vector colNames;
String dbColNames[];
String pkValues[];
String tableName;
ResultSetMetaData myM;
String pKeyCol;
Vector deletedKeys;
Vector newRows;
boolean ibRowNew = false;
boolean ibRowInserted = false;
private Map<String, Color> colormap = new HashMap<String, Color>();
/** Creates new form tab7le */
public tab7le() {
populate();
initComponents();
public void updateDB(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch (ClassNotFoundException e){
System.out.println("Cannot Load Driver!");
try{
String url = "jdbc:odbc:FAMS";
con = DriverManager.getConnection(url);
stat = con.createStatement();
rs = stat.executeQuery("Select * from SubAllot");
deletedKeys = new Vector();
newRows = new Vector();
myM = rs.getMetaData();
tableName = myM.getTableName(1);
li_cols = myM.getColumnCount();
dbColNames = new String[li_cols];
for(int col = 0; col < li_cols; col ++){
dbColNames[col] = myM.getColumnName(col + 1);
allRows = new Vector();
while(rs.next()){
newRow = new Vector();
for(int i = 1; i <= li_cols; i++){
newRow.addElement(rs.getObject(i));
} // for
allRows.addElement(newRow);
} // while
catch(SQLException e){
System.out.println(e.getMessage());
String updateLine[] = new String[dbColNames.length];
try{
DatabaseMetaData dbData = con.getMetaData();
String catalog;
// Get the name of all of the columns for this table
String curCol;
colNames = new Vector();
ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
while (rset1.next()) {
curCol = rset1.getString(4);
colNames.addElement(curCol);
rset1.close();
pKeyCol = colNames.firstElement().toString();
// Go through the rows and perform INSERTS/UPDATES/DELETES
int totalrows;
totalrows = allRows.size();
String dbValues[];
Vector currentRow = new Vector();
pkValues = new String[allRows.size()];
// Get column names and values
for(int i=0;i < totalrows;i++){
currentRow = (Vector) allRows.elementAt(i);
int numElements = currentRow.size();
dbValues = new String[numElements];
for(int x = 0; x < numElements; x++){
String classType = currentRow.elementAt(x).getClass().toString();
int pos = classType.indexOf("String");
if(pos > 0){ // we have a String
dbValues[x] = "'" + currentRow.elementAt(x) + "'";
updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
pos = classType.indexOf("Integer");
if(pos > 0){ // we have an Integer
dbValues[x] = currentRow.elementAt(x).toString();
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString();
else{
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
pos = classType.indexOf("Boolean");
if(pos > 0){ // we have a Boolean
dbValues[x] = currentRow.elementAt(x).toString();
updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
pkValues[i] = currentRow.elementAt(x).toString() ;
} // For Loop
// If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
int numNewRows = newRows.size();
int insertRow = 0;
boolean newRowFound;
for (int z = 0;z < numNewRows;z++){
insertRow = ((Integer) newRows.get(z)).intValue();
if(insertRow == i+1){
StringBuffer InsertSQL = new StringBuffer();
InsertSQL.append("INSERT INTO " + tableName + " (");
for(int zz=0;zz<=dbColNames.length-1;zz++){
if (dbColNames[zz] != null){
InsertSQL.append(dbColNames[zz] + ",");
// Strip out last comma
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
InsertSQL.append(" VALUES(" + pkValues[i] + ",");
for(int c=1;c < dbValues.length;c++){
InsertSQL.append(dbValues[c] + ",");
InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
System.out.println(InsertSQL.toString());
stat.executeUpdate(InsertSQL.toString());
ibRowInserted=true;
} // End of INSERT Logic
// If row has not been INSERTED perform an UPDATE
if(ibRowInserted == false){
StringBuffer updateSQL = new StringBuffer();
updateSQL.append("UPDATE " + tableName + " SET ");
for(int z=0;z<=updateLine.length-1;z++){
if (updateLine[z] != null){
updateSQL.append(updateLine[z]);
// Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
System.out.println(updateSQL.toString());
stat.executeUpdate(updateSQL.toString());
} //for
catch(Exception ex){
System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
// Delete records from the DB
try{
int numDeletes = deletedKeys.size();
String deleteSQL;
for(int i = 0; i < numDeletes;i++){
deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
((Integer) deletedKeys.get(i)).toString();
System.out.println(deleteSQL);
stat.executeUpdate(deleteSQL);
// Assume deletes where successful. Recreate Vector holding PK Keys
deletedKeys = new Vector();
catch(Exception ex){
System.out.println(ex.getMessage());
public void populate()
try
// Connect to the Database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
System.out.println("ok1");
// Read data from a table
String sql;
sql = "Select * from SubAllot";
System.out.println("ok1");
Statement stmt = con.createStatement();
System.out.println("ok1");
ResultSet rs = stmt.executeQuery( sql );
System.out.println("ok1");
ResultSetMetaData md = rs.getMetaData();
System.out.println("ok1");
int columns = md.getColumnCount();
for(int i = 0;i<columns;i++){
columnNames.addElement(md.getColumnName(i+1));
System.out.println("ok2");
while (rs.next())
Vector row = new Vector(columns);
for (int i = 1; i <columns+1; i++)
row.addElement( rs.getObject(i) );
data.addElement( row );
catch(Exception e){
e.printStackTrace();
public void dropmenu(JTable table,TableColumn subpref1) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
for (int i = 0;i<=20;i++)
comboBox.addItem(i);
subpref1.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
subpref1.setCellRenderer(renderer);
abstract class StringTransferHandler extends TransferHandler {
public int dropAction;
protected abstract String exportString(final JComponent c);
protected abstract void importString(final JComponent c, final String str);
@Override
protected Transferable createTransferable(final JComponent c) {
return new StringSelection(exportString(c));
@Override
public int getSourceActions(final JComponent c) {
return MOVE;
@Override
public boolean importData(final JComponent c, final Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String) t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
} catch (UnsupportedFlavorException ufe) {
} catch (IOException ioe) {
return false;
@Override
public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
for (int ndx = 0; ndx < flavors.length; ndx++) {
if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
return true;
return false;
class TableTransferHandler extends StringTransferHandler {
private int dragRow;
private int[] dragColumns;
private BufferedImage[] image;
private int row;
private int[] columns;
public JTable target;
private Map<String, Color> colormap;
private TableTransferHandler(final Map<String, Color> colormap) {
this.colormap = colormap;
@Override
protected Transferable createTransferable(final JComponent c) {
JTable table = (JTable) c;
dragRow = table.getSelectedRow();
dragColumns = table.getSelectedColumns();
createDragImage(table);
return new StringSelection(exportString(c));
protected String exportString(final JComponent c) {
JTable table = (JTable) c;
row = table.getSelectedRow();
columns = table.getSelectedColumns();
StringBuffer buff = new StringBuffer();
colormap.clear();
for (int j = 0; j < columns.length; j++) {
Object val = table.getValueAt(row, columns[j]);
buff.append(val == null ? "" : val.toString());
if (j != columns.length - 1) {
buff.append(",");
colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
table.repaint();
return buff.toString();
protected void importString(final JComponent c, final String str) {
target = (JTable) c;
DefaultTableModel model = (DefaultTableModel) target.getModel();
String[] values = str.split("\n");
int colCount = target.getSelectedColumn();
int max = target.getColumnCount();
for (int ndx = 0; ndx < values.length; ndx++) {
String[] data = values[ndx].split(",");
for (int i = 0; i < data.length; i++) {
String string = data;
if(colCount < max){
Object val = model.getValueAt(target.getSelectedRow(), colCount);
model.setValueAt(string, target.getSelectedRow(), colCount);
model.setValueAt(val, dragRow, dragColumns[i]);
colCount++;
public BufferedImage[] getDragImage() {
return image;
private void createDragImage(final JTable table) {
if (dragColumns != null) {
try {
image = new BufferedImage[dragColumns.length];
for (int i = 0; i < dragColumns.length; i++) {
Rectangle cellBounds = table.getCellRect(dragRow, i, true);
TableCellRenderer r = table.getCellRenderer(dragRow, i);
DefaultTableModel m = (DefaultTableModel) table.getModel();
JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
lbl.setBounds(cellBounds);
BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
lbl.paint(graphics);
graphics.dispose();
image[i] = img;
} catch (RuntimeException re) {
class TableDropTarget extends DropTarget {
private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
private Rectangle rect2D = new Rectangle();
private TableTransferHandler handler;
public TableDropTarget(final TableTransferHandler h) {
super();
this.handler = h;
@Override
public void dragOver(final DropTargetDragEvent dtde) {
handler.dropAction = dtde.getDropAction();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
Point location = dtde.getLocation();
int row = table.rowAtPoint(location);
int column = table.columnAtPoint(location);
table.changeSelection(row, column, false, false);
paintImage(table, location);
autoscroll(table, location);
super.dragOver(dtde);
public void dragExit(final DropTargetDragEvent dtde) {
clearImage((JTable) dtde.getDropTargetContext().getComponent());
super.dragExit(dtde);
@Override
public void drop(final DropTargetDropEvent dtde) {
Transferable data = dtde.getTransferable();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
clearImage(table);
handler.importData(table, data);
super.drop(dtde);
private final void paintImage(final JTable table, final Point location) {
Point pt = new Point(location);
BufferedImage[] image = handler.getDragImage();
if (image != null) {
table.paintImmediately(rect2D.getBounds());
rect2D.setLocation(pt.x - 15, pt.y - 15);
int wRect2D = 0;
int hRect2D = 0;
for (int i = 0; i < image.length; i++) {
table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
pt.x += image[i].getWidth();
if (hRect2D < image[i].getHeight()) {
hRect2D = image[i].getHeight();
wRect2D += image[i].getWidth();
rect2D.setSize(wRect2D, hRect2D);
private final void clearImage(final JTable table) {
table.paintImmediately(rect2D.getBounds());
private Insets getAutoscrollInsets() {
return autoscrollInsets;
private void autoscroll(final JTable table, final Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = table.getVisibleRect();
Rectangle inner = new Rectangle(outer.x + insets.left,
outer.y + insets.top,
outer.width - (insets.left + insets.right),
outer.height - (insets.top + insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
cursorLocation.y - insets.top,
insets.left + insets.right,
insets.top + insets.bottom);
table.scrollRectToVisible(scrollRect);
/** 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.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setModel(new javax.swing.table.DefaultTableModel(
data, columnNames
jScrollPane1.setViewportView(table);
//populate();
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setCellSelectionEnabled(true);
table.setDragEnabled(true);
TableTransferHandler th = new TableTransferHandler(colormap);
table.setTransferHandler(th);
table.setDropTarget(new TableDropTarget(th));
dropmenu(table, table.getColumnModel().getColumn(11));
jButton1.setText("Update");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Ex");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(347, 347, 347)
.addComponent(jButton1)
.addGap(115, 115, 115)
.addComponent(jButton2)))
.addContainerGap(73, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButton1)
.addContainerGap(83, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addGap(65, 65, 65))))
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
updateDB(); // TODO add your handling code here:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
pathToDesktop = pathToDesktop + "//Final Allotment.xls";
ExcelExporter exp = new ExcelExporter();
exp.exportTable(table, new File(pathToDesktop));
JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
} // TODO add your handling code here:
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new tab7le().setVisible(true);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
// End of variables declaration
Please help !!!!!!!!
Thanks in advance.....Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
Why post code with access to a database? We can't access the database.
Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour. -
Please Help - Need Help with Buttons for GUI for assignment. URGENT!!
Can someone please help me with the buttons on this program? I cannot figure out how to get them to work.
Thanks!!!
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.JButton;
public class InventoryTAH implements ActionListener
Maker[] proMaker;
JTextField[] fields;
NumberFormat nf;
public void actionPerformed(ActionEvent e)
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
public static void main(String[] args)
try
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e)
System.err.println(e.getClass().getName() + ": " + e.getMessage());
InventoryTAH test = new InventoryTAH();
test.initMakers();
test.showGUI();
test.populateFields(0);
private void initMakers() {
proMaker = new Maker[10];
proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");
int maxNum = 10;
int currentNum = 0;
int currentInv = 0;
Action firstAction = new AbstractAction("First")
public void actionPerformed(ActionEvent evt)
currentInv = 0;
int populateFields;
JButton firstButton = new JButton(firstAction);
Action previousAction = new AbstractAction("Previous")
public void actionPerformed(ActionEvent evt)
currentInv--;
if (currentInv < 0)
currentInv = maxNum - 1;
int populateFields;
JButton previousButton = new JButton(previousAction);
Action nextAction = new AbstractAction("Next")
public void actionPerformed(ActionEvent evt)
currentInv++;
if (currentInv >= currentNum)
currentInv = 0;
int populateFields;
JButton nextButton = new JButton(nextAction);
Action lastAction = new AbstractAction("Last")
public void actionPerformed(ActionEvent evt)
currentInv = currentNum - 1;
int populateFields;
JButton lastButton = new JButton(lastAction);
JPanel buttonPanel = new JPanel( );
private void showGUI() {
JLabel l;
JButton button1;
JButton button2;
fields = new JTextField[8];
JFrame f = new JFrame("Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('h');
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c);
fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c);
fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c);
fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c);
fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c);
fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c);
fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c);
fields[7].setFocusAccelerator('h');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(firstButton);
cp.add(previousButton);
cp.add(nextButton);
cp.add(lastButton);
JComboBox combo = new JComboBox();
for(int j = 0; j < proMaker.length; j++)
combo.addItem(proMaker[j].getName());
combo.addActionListener(this);
cp.add(combo);
cp.add(button1 = new JButton(" "), c);
f.pack();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent evt)
System.exit(0);
f.setVisible(true);
private void populateFields(int index) {
Maker maker = proMaker[index];
fields[0].setText(Long.toString(maker.getNumberCode()));
fields[1].setText(maker.getName());
fields[2].setText(Long.toString(maker.getUnits()));
fields[3].setText(Double.toString(maker.getPrice()));
fields[4].setText(Double.toString(maker.getSum()));
fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
fields[6].setText(maker.getManufact());
fields[7].setText(Double.toString(maker.getSum()*.05));
class Maker {
int itemNumber;
String name;
int units;
double price;
String manufacturer;
public Maker(int n, String name, double price, int units, String manufac) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
manufacturer = manufac;
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getManufact() { return manufacturer; }
public double totalAllInventory(Maker[] makers) {
double total = 0;
for(int j = 0; j < makers.length; j++)
total += makers[j].getSum();
return total;
}}// I have made some modifications. Please try this.
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.JButton;
public class InventoryTAH implements ActionListener
Maker[] proMaker;
JTextField[] fields;
NumberFormat nf;
int currentInv = 0;
public void actionPerformed(ActionEvent e)
currentInv= ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(currentInv);
public static void main(String[] args)
try
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
catch (Exception e)
System.err.println(e.getClass().getName() + ": " + e.getMessage());
InventoryTAH test = new InventoryTAH();
test.initMakers();
test.showGUI();
test.populateFields(0);
private void initMakers() {
proMaker = new Maker[10];
proMaker[0] = new Maker( 1, "Pens",1.59,100,"Bic");
proMaker[1] = new Maker( 2, "Pencils", .65, 100,"Mead");
proMaker[2] = new Maker( 3, "Markers", 1.29, 100,"Sharpie");
proMaker[3] = new Maker( 4, "Paperclips", 1.19, 100,"Staples");
proMaker[4] = new Maker( 5, "Glue", .85, 100,"Elmer's");
proMaker[5] = new Maker( 6, "Tape", .50, 100,"3m");
proMaker[6] = new Maker( 7, "Paper", 1.85, 100,"Mead");
proMaker[7] = new Maker( 8, "Stapler", 2.21, 100,"Swingline");
proMaker[8] = new Maker( 9, "Folders", .50, 100,"Mead");
proMaker[9] = new Maker( 10, "Rulers", .27, 100,"Stanley");
int maxNum = 10;
int currentNum = 0;
Action firstAction = new AbstractAction("First")
public void actionPerformed(ActionEvent evt)
currentInv = 0;
populateFields(currentInv);
JButton firstButton = new JButton(firstAction);
Action previousAction = new AbstractAction("Previous")
public void actionPerformed(ActionEvent evt)
currentInv--;
if (currentInv < 0)
currentInv = maxNum - 1;
populateFields(currentInv);
JButton previousButton = new JButton(previousAction);
Action nextAction = new AbstractAction("Next")
public void actionPerformed(ActionEvent evt)
currentInv++;
if (currentInv >= maxNum)
currentInv = 0;
populateFields(currentInv);
JButton nextButton = new JButton(nextAction);
Action lastAction = new AbstractAction("Last")
public void actionPerformed(ActionEvent evt)
currentInv = maxNum-1;
populateFields(currentInv);
JButton lastButton = new JButton(lastAction);
JPanel buttonPanel = new JPanel( );
private void showGUI() {
JLabel l;
JButton button1;
JButton button2;
fields = new JTextField[8];
JFrame f = new JFrame("Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor(Color.BLACK));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of Item: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of Merchandise in Inventory: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Manufacturer:", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Restocking Fee: $", SwingConstants.CENTER), c);
l.setDisplayedMnemonic('h');
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c);
fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c);
fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c);
fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c);
fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c);
fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c);
fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c);
fields[7].setFocusAccelerator('h');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(firstButton);
cp.add(previousButton);
cp.add(nextButton);
cp.add(lastButton);
JComboBox combo = new JComboBox();
for(int j = 0; j < proMaker.length; j++)
combo.addItem(proMaker[j].getName());
combo.addActionListener(this);
cp.add(combo);
cp.add(button1 = new JButton(" "), c);
f.pack();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent evt)
System.exit(0);
f.setVisible(true);
private void populateFields(int index) {
Maker maker = proMaker[index];
fields[0].setText(Long.toString(maker.getNumberCode()));
fields[1].setText(maker.getName());
fields[2].setText(Long.toString(maker.getUnits()));
fields[3].setText(Double.toString(maker.getPrice()));
fields[4].setText(Double.toString(maker.getSum()));
fields[5].setText(Double.toString(maker.totalAllInventory(proMaker)));
fields[6].setText(maker.getManufact());
fields[7].setText(Double.toString(maker.getSum()*.05));
class Maker {
int itemNumber;
String name;
int units;
double price;
String manufacturer;
public Maker(int n, String name, double price, int units, String manufac) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
manufacturer = manufac;
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getManufact() { return manufacturer; }
public double totalAllInventory(Maker[] makers) {
double total = 0;
for(int j = 0; j < makers.length; j++)
total += makers[j].getSum();
return total;
}} -
Problem with interputting accessframe example please help!!!
A use code bellow to access every frame in the movie :
import java.awt.*;
import javax.media.*;
import javax.media.control.TrackControl;
import javax.media.Format;
import javax.media.format.*;
import java.io.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.Color.*;
import java.awt.image.*;
import java.util.*;
import java.awt.image.*;
import javax.media.util.*;
import javax.swing.JFrame;
public class Film2ramki implements ControllerListener {
Processor p;
Object waitSync = new Object();
boolean stateTransitionOK = true;
public boolean alreadyPrnt = false;
public void zakoncz(){
p.stop();
p.close();
p.deallocate();
public boolean open(MediaLocator ml) {
try {
p = Manager.createProcessor(ml);
} catch (Exception e) {
System.err.println("Failed to create a processor from the given url: " + e);
return false;
p.addControllerListener(this);
// Put the Processor into configured state.
p.configure();
if (!waitForState(p.Configured)) {
System.err.println("Failed to configure the processor.");
return false;
// So I can use it as a player.
p.setContentDescriptor(null);
// Obtain the track controls.
TrackControl tc[] = p.getTrackControls();
if (tc == null) {
System.err.println("Failed to obtain track controls from the processor.");
return false;
// Search for the track control for the video track.
TrackControl videoTrack = null;
for (int i = 0; i < tc.length; i++) {
if (tc.getFormat() instanceof VideoFormat) {
videoTrack = tc[i];
break;
if (videoTrack == null) {
System.err.println("The input media does not contain a video track.");
return false;
System.err.println("Video format: " + videoTrack.getFormat());
// Instantiate and set the frame access codec to the data flow path.
try {
Codec codec[] = { new PreAccessCodec(),
new PostAccessCodec()};
videoTrack.setCodecChain(codec);
} catch (UnsupportedPlugInException e) {
System.err.println("The process does not support effects.");
// Realize the processor.
p.prefetch();
if (!waitForState(p.Prefetched)) {
System.err.println("Failed to realize the processor.");
return false;
p.start();
return true;
boolean waitForState(int state) {
synchronized (waitSync) {
try {
while (p.getState() != state && stateTransitionOK)
waitSync.wait();
} catch (Exception e) {}
return stateTransitionOK;
public void controllerUpdate(ControllerEvent evt) {
if (evt instanceof ConfigureCompleteEvent ||
evt instanceof RealizeCompleteEvent ||
evt instanceof PrefetchCompleteEvent) {
synchronized (waitSync) {
stateTransitionOK = true;
waitSync.notifyAll();
} else if (evt instanceof ResourceUnavailableEvent) {
synchronized (waitSync) {
stateTransitionOK = false;
waitSync.notifyAll();
} else if (evt instanceof EndOfMediaEvent) {
p.stop();
p.close();
System.exit(0);
Film2ramki(){}
public void startnow (String plik) {
//this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
String url = "file:"+plik;
if (url.indexOf(":") < 0) {
prUsage();
System.exit(0);
MediaLocator ml;
if ((ml = new MediaLocator(url)) == null) {
System.err.println("Cannot build media locator from: " + url);
System.exit(0);
if (!open(ml))
System.exit(0);
static void prUsage() {
System.err.println("Usage: java Film2ramki <url>");
* Inner class.
* A pass-through codec to access to individual frames.
public class PreAccessCodec implements Codec {
* Callback to access individual video frames.
void accessFrame(Buffer frame) {
// For demo, we'll just print out the frame #, time &
// data length.
long t = (long)(frame.getTimeStamp()/10000000f);
System.err.println("Pre: frame #: " + frame.getSequenceNumber() +
", time: " + ((float)t)/100f +
", len: " + frame.getLength());
* The code for a pass through codec.
// We'll advertize as supporting all video formats.
protected Format supportedIns[] = new Format [] {
new VideoFormat(null)
// We'll advertize as supporting all video formats.
protected Format supportedOuts[] = new Format [] {
new VideoFormat(null)
Format input = null, output = null;
public String getName() {
return "Pre-Access Codec";
// No op.
public void open() {
// No op.
public void close() {
// No op.
public void reset() {
public Format [] getSupportedInputFormats() {
return supportedIns;
public Format [] getSupportedOutputFormats(Format in) {
if (in == null)
return supportedOuts;
else {
// If an input format is given, we use that input format
// as the output since we are not modifying the bit stream
// at all.
Format outs[] = new Format[1];
outs[0] = in;
return outs;
public Format setInputFormat(Format format) {
input = format;
return input;
public Format setOutputFormat(Format format) {
output = format;
return output;
public int process(Buffer in, Buffer out) {
// This is the "Callback" to access individual frames.
accessFrame(in);
// Swap the data between the input & output.
Object data = in.getData();
in.setData(out.getData());
out.setData(data);
// Copy the input attributes to the output
out.setFlags(Buffer.FLAG_NO_SYNC);
out.setFormat(in.getFormat());
out.setLength(in.getLength());
out.setOffset(in.getOffset());
return BUFFER_PROCESSED_OK;
public Object[] getControls() {
return new Object[0];
public Object getControl(String type) {
return null;
public class PostAccessCodec extends PreAccessCodec {
// We'll advertize as supporting all video formats.
public PostAccessCodec() {
supportedIns = new Format [] {
new RGBFormat()
* Callback to access individual video frames.
void accessFrame(Buffer frame) {
// For demo, we'll just print out the frame #, time &
// data length.
if(!alreadyPrnt)
BufferToImage stopBuffer = new BufferToImage((VideoFormat)frame.getFormat());
System.out.println(stopBuffer.toString());
System.out.println("CreatedBuffer");
System.out.println("Created stopImage");
Image stopImage = stopBuffer.createImage(frame);
System.out.println("stopImage is full");
if(stopImage == null)
System.out.println("stopImage is null");
try
BufferedImage outImage = new BufferedImage (320, 240,BufferedImage.TYPE_INT_RGB);
Graphics og = outImage.getGraphics();
og.drawImage(stopImage,0,0,320,240,null);
//prepareImage(outImage,rheight,rheight, null);
Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter)writers.next();
//Once an ImageWriter has been obtained, its destination must be set to an ImageOutputStream:
File f = new File("frames\\"+frame.getSequenceNumber() + ".jpg");
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
//Finally, the image may be written to the output stream:
//BufferedImage bi;
//writer.write(imagebi);
writer.write(outImage);
ios.close();
catch(IOException e)
System.out.println("Error :" + e);
//alreadyPrnt = true;
long t = (long)(frame.getTimeStamp()/10000000f);
System.err.println("Post: frame #: " + frame.getSequenceNumber() +
", time: " + ((float)t)/100f +
", len: " + frame.getLength());
if(frame.getLength()==0){p.stop();p.close();p.deallocate();}
public String getName() {
return "Post-Access Codec";
this code capture every frame from movie but it never ends running and i can't invoke any metod after grabing frames becouse its still running. How Can I stop this to enter the next metod.
Please help me
thxAnswering sam04 question Yes this make that every frame is captured
Back to my problem :
I invoke caputre frames class from other class like this:
Film2ramki f2r=new Film2ramki();
f2r.startnow(pathtomov);
System.out.println("End of capture");...........................
So when capturing frames ends it should print "End of caputre" but I get something like this :
JPEG, 320x240, FrameRate=13.0, Length=18198
Video format: JPEG, 320x240, FrameRate=13.0, Length=18198
Pre: frame #: 1, time: 0.0, len: 16282
Post: frame #: 1, time: 0.0, len: 230400
End of capture
Pre: frame #: 2, time: 0.07, len: 16471
Post: frame #: 2, time: 0.07, len: 230400
Pre: frame #: 3, time: 0.15, len: 16620
Post: frame #: 3, time: 0.15, len: 230400
Pre: frame #: 4, time: 0.23, len: 16541
Post: frame #: 4, time: 0.23, len: 230400
Pre: frame #: 5, time: 0.3, len: 16749
Pre: frame #: 18, time: 1.3, len: 15708
Post: frame #: 18, time: 1.3, len: 230400
Pre: frame #: 18, time: 1.3, len: 0
Post: frame #: 18, time: 1.3, len: 0this is strange becouse it captures 1 frame end print "End of capture" and then its capures other frames. Why ?????
Maybe you are looking for
-
Hi, We are working with SRM 5.5 (EBP and SUS) and we are making the basic settings in which we can find the IPC, but the guides don´t specify nothing about that, it only say that we need configure the IPC but i don´t know how. I'm looking for informa
-
Photoshop Elements 9 for Mac default setting?
I want to use Photoshop Elements 9 for MAC instead of IPhoto, but can't seem to find how to make Photoshop the default. Should I delete IPhoto entirely?
-
The Include Directive (at Page Translation Time)
Version: 5.1 Service Pack: 6 I am generating the following error when I attempt to manually compile a JSP file: [jspc] parsing /vobs/projects/public_html//test.jsp: WARNING: Failed to include file 'te
-
Error compiling EJB.jar + cannot resolve symbol+while deploying
I am getting following Error compiling EJB.jar , cannot resolve symbol ,Syntax error in source, am getting around 17 errors while deploying EAR generated using Jdev905 into standalone oc4jContainers(10g). Can anyone please help me out where is the pr
-
Can't post on an online forum for the game 'Runescape'? Using Macbook Pro 13'
Hello, I can't seem to post anything on it. When I press the button to publish it, the page just freezes. I use a Macbook Pro 13', and on Safari. I also bought this last Friday. If anyone has any suggestions, that would be appreciated.