JLabel PLEASE help

I want to have a list of text items on the LHS of my window, and when the user clicks one of these texts, then the RHS of the screen displays the relevant stuff. So should I create a JLabel(text) and then addMouseListener to it, and then do all my stuff in the Mouse Listener?
Also, how can I make it such that when the user moves the mouse over the JLabel it changes colour, i.e. is hiughlighted. The JLabel API does not contain any rollovers :-(

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = f.getContentPane();
cp.setLayout(new GridLayout(0,1,5,5));
cp.add(createButton("press here"));
cp.add(createButton("or press here"));
cp.add(createButton("perhaps here"));
f.pack();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
static JButton createButton(String text) {
JButton btn = new JButton(text);
btn.setActionCommand(text);
btn.setBorderPainted(false);
btn.setFocusPainted(false);
btn.addMouseListener(l);
return btn;
static MouseListener l =  new  MouseAdapter() {
public void mouseEntered(MouseEvent e) {
AbstractButton b = (AbstractButton)
tractButton) e.getSource();
String text = b.getActionCommand();
b.setText("<html><u>" + text +
u>" + text + "</u></html>");
public void mouseExited(MouseEvent e) {
AbstractButton b = (AbstractButton)
tractButton) e.getSource();
b.setText(b.getActionCommand());
}I like that code, I actually followed it, kinda, but why is MouseListener static and also why did you add invokeLater and runnable, is that necessary, cos to eb honest I dont want to use threads cos I just want to keep things simple, just put it all in one thread is how I want to do it, thats always my motto in programming, keep it simple, cos 90% of the bugs are people trying to complicate things, but thanks a lot for your heklp, I appreciate you took the time to write code for a Java beginner like me

Similar Messages

  • 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);
    tab

    First 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.

  • Please help getString()

    hi,
    this might sound like a question that shouln't have been asked but
    i'm new to java, studied it for a few months (haven't learnt any kind of programming languages before )and been assigned to do a project, tried my best at it but got stuck on this GetString() method
    what's wrong with this code
    i tried to compile it but came up with errors
    cannot find symbol
    symbol : method getString()
    location: class java.lang.String
    stm.setString(4,strdate.getString());
    cannot find symbol
    symbol : method strtimegetString()
    location: class javaproject
    stm.setString(5, strtimegetString());
    2 errors
    here's the code
    //javaproject.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.sql.*;
    public class javaproject extends JApplet implements ActionListener,Runnable
    JPanel panel; JLabel lname, lcode,lterm,ltime,ldate;
    JTextField tfname , tfcode;
    JButton bttsaved, bttcancel, bttclose;
    JComboBox cbterm;     
    String term[] ={"Semester A","Semester B","Semester C","Semester D"};
    String strdate, strtime ;
    Thread time;
    GregorianCalendar calendar;
    public void init()
         panel = new JPanel();
         lcode = new JLabel ("Code : ");
         lname = new JLabel("Name : ");
         lterm = new JLabel("Term : ");
         ltime = new JLabel();
         ldate = new JLabel();
         tfcode = new JTextField(20);
         tfname = new JTextField(20);
         cbterm = new JComboBox(term);
    bttsaved = new JButton(" Saved ");
    bttcancel = new JButton(" Cancel ");
    bttclose = new JButton(" Close ");
         calendar = new GregorianCalendar();
         time =new Thread(this);
         time.start();
         display();
         panel.add(ldate); panel.add(ltime);
         panel.add(lcode); panel.add(tfcode);
         panel.add(lname); panel.add(tfname);
         panel.add(lterm); panel.add(cbterm);
         panel.add(bttsaved); panel.add(bttcancel); panel.add(bttclose);
         getContentPane().add(panel);
         bttsaved.addActionListener(this);
         bttcancel.addActionListener(this);
         bttclose.addActionListener(this);
    public void run()
         for(;;)
         calendar = new GregorianCalendar();
              strtime = calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)
              +":"+calendar.get(Calendar.SECOND);
              ltime.setText(strtime);
              try
              time.sleep(1000);
              catch(InterruptedException e)
              showStatus("ThreadInterrupted");          
    public void display()
         strdate = calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH)+1) + "/"+calendar.get(Calendar.YEAR);
         ldate.setText(strdate);
    public void actionPerformed(ActionEvent evt)
         if(evt.getSource() == bttcancel )
         tfcode.setText(" ");
         tfname.setText(" ");
         showStatus(" ..... Please enter new information ..... ");
         if(evt.getSource() == bttclose )
         System.exit(0);          
         if(evt.getSource() ==bttsaved )
         try
              String blankcode = tfcode.getText();
              if(blankcode.length() == 0)
                   showStatus("Student's code cannot be empty");
                   return;          
              String blankname = tfname.getText();
              if(blankname.length() == 0)
                   showStatus("..... Student's name cannot be empty ......");
              return;
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con;
              con = DriverManager.getConnection("jdbc:odbc:kayteej","sa", null);
              PreparedStatement stm;
              stm = con.prepareStatement("insert into Students values(?,?,?)");
              stm.setString(1,tfcode.getText());     
              stm.setString(2,tfname.getText());
              stm.setString(3,(String)cbterm.getSelectedItem());
              stm.setString(4,strdate.getString());
              stm.setString(5, strtimegetString());
              stm.executeUpdate();     
              showStatus("..... Please enter new information ..... ");
              JOptionPane.showMessageDialog(null, "Data Saved","Congrats!!",1);
         catch(Exception err)
              showStatus("Error occured while interacting with sql");
    //<Applet code="javaproject.class" width=800 height=600></applet>
    should i use the getString method or is it possible to use other type of methods. please help I'm really stuck
    Thank you in advance

    So when you run it, the code throws an exception? Then there's something wrong with your code, or with your setup.
    The exception's stack trace contains useful information which would help you (or us) figure out just what is wrong. Hopefully you have a catch-block that calls the printStackTrace() method of the exception.

  • 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 me

    i 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.

  • SetText() is not working ....please help

    hello all,
    i am really stuck at something silly in my program, my code is huge to post in here, so i will try to describe as much as i can.
    well my problem is i have a class which listen to a socket, when some data has been changed, i want it to modify a JPanel in "another" class, which is the main class of my GUI, by changing the text in that panel.
    i am using setText(Sting), but it doesnt work.
    i tried to call a method from the listen class to the main and that method have a print statment and setText() call, i checked that the statment is being printed, "which tells me that the listen class is calling that method in the main class, but the text doesnt change.. i tried repaint, revalidate... please help ..
    thx for ur time.

    i am trying to give u the closest picture of my code:
    public class SetTextTest extends JPanel{
         public JPanel updateHistory;
         private JButton updateHistoryButton;
    public JLabel updateLabel;
         public String updateStatus = "Updates: ";
         String updatesList ="";
    String updatesIds="", updatesTimes="";
         int numOfupdates = 0;
         public SetTextTest() {
              super(new BorderLayout());
              updateHistory = new JPanel();
              //Set up Updates History Panel
              updateHistory.setLayout(new BoxLayout(updateHistory,BoxLayout.Y_AXIS));//new BorderLayout());
              updateHistory.setMaximumSize(new Dimension(300,250));
              updateLabel = new JLabel(updateStatus + numOfupdates);
              updateHistoryButton = new JButton("Check Updates");
              updateHistoryButton.setPreferredSize(new Dimension(120,25));
              updateHistoryButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        //open a table
         updateHistory.add(updateLabel);
         updateHistory.add(updateHistoryButton);
         public void newUpdates(){
              numOfupdates++;
              java.awt.Toolkit.getDefaultToolkit().beep();
              System.out.println(updateStatus + numOfupdates);
              updateLabel.setText(updateStatus + numOfupdates);
    }

  • 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,
    har

    Hi,
    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

  • 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;
    }}

  • Please help...my browser can't display applets

    I know it might sound inept to be asking something about my mozilla browser in this forum but right now I am studying Java and using my browser to view the applet exercises I make. I am particularly in the methods section where you have to make recursions (I am using JAVA 2 how to program Third Edition by Deitel). I made my own version of the fibonacci program in the book . It has a GUI, action listener and the method where all the calculations take place. Unfortunately, when I test it on my brower, Mozilla Fireforx, it just displays the GUI and whole program does not work. The compiler, in this case javac, cannot sense anything wrong and I take it that my code is correct. However nothing still happens when I test it on my browser. As previously mentioned, it just displays the GUI and that's all. I really do not know what is wrong. Is it with my code or with the browser? Or is with the fact that I am using an outdated version of JAVA 2 how to program with a new version of J2SDK that makes my code incompatible with the new technology? please help. TY
    Here's my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class AppletCode extends JApplet implements ActionListener {
         JLabel inputLabel, outputLabel;
         JTextField input, output;
         public void init(){
              Container c = getContentPane();
              c.setLayout(new FlowLayout());
              JLabel inputLabel = new JLabel();
              inputLabel.setText("Enter an Integer and press Enter");
              c.add(inputLabel);
              JTextField input = new JTextField(10);
              input.addActionListener(this);
              c.add(input);
              JLabel outputLabel = new JLabel();
              outputLabel.setText("Fibonacci Value is");
              c.add(outputLabel);
              JTextField output = new JTextField(20);
              output.setEditable(false);
              c.add(output);
         } // GUI
         public void actionPerformed(ActionEvent e) {
              long number, fibonacciValue;
              number = Long.parseLong(input.getText());
              fibonacciValue = fibonacci(number);
              output.setText(Long.toString(fibonacciValue));
         } // Action Listener
         public long fibonacci(long x) {
              if (x==0 || x==1)
                   return x;
              else
                   return fibonacci(x-1) + fibonacci(x-2);
         } // Fibonacci Module
    }

    I don't see anything obviously wrong with your code, but it's been a while since i coded applets, so there might still be something wrong. What exactly does not work? You see the 2 labels and the text fields? Can you enter any text into the text field? Have you looked into the Java Console wether it prints any exceptions? (and please use the [ code][ /code] tags to mark your code (without the spaces obviously))

  • Button to frame | button going back to the main frame (please help)

    these are the codes, by clicking the "FCFS" button it will generate another frame and from that frame another button will be pressed "accept" and it will go to another frame....
    my problem is that i nid to put codes on the "back" button to go back to the main frame were it started... please help me... thnks
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Oscon extends JFrame
         private JButton fcfsB, priorityB, sjfB, rrB, exitB, creditsB;
         private fcfsButtonHandler fbHandler;
         private priorityButtonHandler pbHandler;
         private sjfButtonHandler sbHandler;
         private rrButtonHandler rbHandler;
         private exitButtonHandler ebHandler;
         private creditsButtonHandler cbHandler;     
         public Oscon()// main frame
              fcfsB = new JButton ("FCFS");
              fbHandler = new fcfsButtonHandler();
              fcfsB.addActionListener(fbHandler);
              priorityB = new JButton ("PRIORITY");
              pbHandler = new priorityButtonHandler();
              priorityB.addActionListener(pbHandler);
              sjfB = new JButton ("SJF");
              sbHandler = new sjfButtonHandler();
              sjfB.addActionListener(sbHandler);
              rrB = new JButton ("RR");
              rbHandler = new rrButtonHandler();
              rrB.addActionListener(rbHandler);
              exitB = new JButton ("EXIT");
              ebHandler = new exitButtonHandler();
              exitB.addActionListener(ebHandler);
              creditsB = new JButton ("CREDITS");
              cbHandler = new creditsButtonHandler();
              creditsB.addActionListener(cbHandler);
              setTitle("CPU SCHEDULING");
              Container pane =getContentPane ();     
              pane.setLayout(new GridLayout(2,3));
              pane.add(fcfsB);
              pane.add(priorityB);
              pane.add(sjfB);
              pane.add(rrB);
              pane.add(exitB);
              pane.add(creditsB);
              setSize(500,100);
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public class fcfsButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   JFrame frame = new JFrame("FCFCS setting");
         final JLabel FCFSProcessL, FCFSp1L,FCFSp2L,FCFSp3L,FCFSp4L, FCFSbt;
              final JTextField FCFSp1TF,FCFSp2TF,FCFSp3TF,FCFSp4TF;
                        FCFSProcessL = new JLabel("PROCESS", SwingConstants.CENTER);
                        FCFSp1L     = new JLabel("P1:", SwingConstants.CENTER);
                        FCFSp2L     = new JLabel("P2:", SwingConstants.CENTER);
                        FCFSp3L     = new JLabel("P3:", SwingConstants.CENTER);
                        FCFSp4L     = new JLabel("P4:", SwingConstants.CENTER);
                        FCFSbt      = new JLabel("BT:", SwingConstants.CENTER);
                        FCFSp1TF= new JTextField (10);
                        FCFSp2TF= new JTextField (10);
                        FCFSp3TF= new JTextField (10);
                        FCFSp4TF= new JTextField (10);
                        JButton     FCFSokB = new JButton ("Accept");
                        FCFSokB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  JFrame frame2 = new JFrame("FCFCS");
                                  frame2.setSize(500,500);
                                  frame2.setVisible(true);
                                  frame2.setDefaultCloseOperation(EXIT_ON_CLOSE);
                                  JButton     FCFSclearB = new JButton ("clear");
                                  FCFSclearB.addActionListener(new ActionListener() {   
                                  public void actionPerformed(ActionEvent e)
                                  FCFSp1TF.setText("");
                                  FCFSp2TF.setText("");
                                  FCFSp3TF.setText("");
                                  FCFSp4TF.setText("");
                        JButton     FCFSBackB = new JButton ("Back");
                        FCFSBackB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  setTitle("CPU SCHEDULING");
                                  frame.setLayout(new GridLayout(7,2));
                                  frame.add(FCFSProcessL);
                                  frame.add(FCFSbt);
                                  frame.add(FCFSp1L);
                                  frame.add(FCFSp1TF);
                                  frame.add(FCFSp2L);
                                  frame.add(FCFSp2TF);
                                  frame.add(FCFSp3L);
                                  frame.add(FCFSp3TF);
                                  frame.add(FCFSp4L);
                                  frame.add(FCFSp4TF);
                                  frame.add(FCFSokB);
                                  frame.add(FCFSclearB);
                                  frame.add(FCFSBackB);
                                  frame.setSize(200,250);
                                  frame.setVisible(true);
                                  frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public class priorityButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
         public class sjfButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class rrButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class exitButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
         public class creditsButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit (0);          
              public static void main (String [] args)
              Oscon O = new Oscon();
    }

    please help me revise my program, im almost done, i just nid to set the progress bar that it will run according to the waiting time, or set the progress bar to run in order.. these are the variable names of the progress bar(current1, then current2, then current3 then current4).
    i looked it up on the site and i cant really understand it... i just did the part where i included the progress bar to the interface. ijust want the 4 progress bars to run after clicking the accept button.... Please help me!!! its for my project and i didnt slept last night just working on this... i just nid help sir... thnks...
    these are the codes i made:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JProgressBar;
    public class CPUSched
              public CPUSched()
              JFrame frame = new JFrame();
                   JProgressBar current1, current2, current3, current4;
                   Thread runner;
                   int num = 0;
              final JLabel ProcessL, p1L,p2L,p3L,p4L, bt, prioL, tqL, wtL, awtL, awtLA;
                   final JTextField p1TF,p2TF,p3TF,p4TF, prio1TF, prio2TF,prio3TF,prio4TF, tqTF ;
                   final JLabel      blank1, blank2, blank3, blank4, blank5, blank6, blank7, blank8, blank9, blank10, blank11,
                                       blank12, blank13, blank14, blank15;
                   final JLabel     blank16, blank17, blank18, blank19, blank20, blank21, blank22, blank23, blank24, blank25,
                                       blank26, blank27, blank28, blank29, blank30;
                   current1 = new JProgressBar(0, 2000);
                   current1.setValue(0);
         current1.setStringPainted(true);
                   current2 = new JProgressBar(0, 2000);
                   current2.setValue(0);
         current2.setStringPainted(true);
                   current3= new JProgressBar(0, 2000);
                   current3.setValue(0);
         current3.setStringPainted(true);
                   current4 = new JProgressBar(0, 2000);
                   current4.setValue(0);
         current4.setStringPainted(true);
                        ProcessL = new JLabel("PROCESS", SwingConstants.CENTER);
                        p1L     = new JLabel("P1:", SwingConstants.CENTER);
                        p2L     = new JLabel("P2:", SwingConstants.CENTER);
                        p3L     = new JLabel("P3:", SwingConstants.CENTER);
                        p4L     = new JLabel("P4:", SwingConstants.CENTER);
                        bt      = new JLabel("Burst Time:", SwingConstants.CENTER);
                        prioL= new JLabel("Priority (1-4):", SwingConstants.CENTER);
                        tqL= new JLabel("Time Quantum:", SwingConstants.CENTER);
                        wtL= new JLabel("Waiting time:", SwingConstants.CENTER);
                        awtL= new JLabel("Average Waiting time:");
                        awtLA= new JLabel("");
                        blank1= new JLabel("");
                        blank2= new JLabel("");
                        blank3= new JLabel("" ,SwingConstants.CENTER);
                        blank4= new JLabel("");
                        blank5= new JLabel("", SwingConstants.CENTER);
                        blank6= new JLabel("");
                        blank7= new JLabel("");
                        blank8= new JLabel("" ,SwingConstants.CENTER);
                        blank9= new JLabel("");
                        blank10= new JLabel("");
                        blank11= new JLabel("", SwingConstants.CENTER);
                        blank12= new JLabel("");
                        blank13= new JLabel("");
                        blank14= new JLabel("");
                        blank15= new JLabel("");
                        blank16= new JLabel("");
                        blank17= new JLabel("");
                        blank18= new JLabel("");
                        blank19= new JLabel("");
                        blank20= new JLabel("");
                        blank21= new JLabel("");
                        blank22= new JLabel("");
                        blank23= new JLabel("");
                        blank24= new JLabel("");
                        blank25= new JLabel("");
                        blank26= new JLabel("");
                        blank27= new JLabel("");
                        blank28= new JLabel("");
                        blank29= new JLabel("");
                        blank30= new JLabel("");
                        p1TF= new JTextField (2);
                        p2TF= new JTextField (2);
                        p3TF= new JTextField (2);
                        p4TF= new JTextField (2);
                        prio1TF= new JTextField (2);
                        prio2TF= new JTextField (2);
                        prio3TF= new JTextField (2);
                        prio4TF= new JTextField (2);
                        tqTF= new JTextField (2);
                             prio1TF.setEditable(false);
                             prio2TF.setEditable(false);
                             prio3TF.setEditable(false);
                             prio4TF.setEditable(false);
                             tqTF.setEditable(false);
                        JButton     okB = new JButton ("Accept");
                        okB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                             double iw=0, wtp1, wtp2, wtp3, wtp4;
                             double bt1, bt2, bt3, bt4;
                             double averageWT, sumWT;
                             bt1=Double.parseDouble(p1TF.getText());
                             bt2=Double.parseDouble(p2TF.getText());
                             bt3=Double.parseDouble(p3TF.getText());
                             bt4=Double.parseDouble(p4TF.getText());
                             wtp1 = iw;
                             wtp2 = wtp1+bt1;
                             wtp3 = wtp2+bt2;
                             wtp4 = wtp3+bt3;
                             sumWT = wtp1+wtp2+wtp3+wtp4;
                             averageWT = sumWT/4;
                             awtLA.setText(""+averageWT);
                             blank3.setText(""+wtp1);
                             blank5.setText(""+wtp2);
                             blank8.setText(""+wtp3);
                             blank11.setText(""+wtp4);
                        JButton     clearB = new JButton ("Clear");
                        clearB.addActionListener(new ActionListener() {   
                        public void actionPerformed(ActionEvent e)
                                  p1TF.setText("");
                                  p2TF.setText("");
                                  p3TF.setText("");
                                  p4TF.setText("");
                             awtLA.setText("");
                             blank3.setText("");
                             blank5.setText("");
                             blank8.setText("");
                             blank11.setText("");
                             frame.setTitle("First Come First Serve");
                                  frame.setLayout(new GridLayout(6,6));
                                  frame.add(ProcessL);
                                  frame.add(blank1);
                                  frame.add(wtL);
                                  frame.add(bt);
                                  frame.add(prioL);
                                  frame.add(tqL);
                                  frame.add(p1L);
                                  frame.add(current1);
                                  frame.add(blank3);                              
                                  frame.add(p1TF);
                                  frame.add(prio1TF);
                                  frame.add(tqTF);
                                  frame.add(p2L);
                                  frame.add(current2);
                                  frame.add(blank5);
                                  frame.add(p2TF);
                                  frame.add(prio2TF);
                                  frame.add(blank6);
                                  frame.add(p3L);
                                  frame.add(current3);
                                  frame.add(blank8);
                                  frame.add(p3TF);
                                  frame.add(prio3TF);
                                  frame.add(blank9);
                                  frame.add(p4L);
                                  frame.add(current4);
                                  frame.add(blank11);
                                  frame.add(p4TF);
                                  frame.add(prio4TF);
                                  frame.add(blank12);
                                  frame.add(blank13);
                                  frame.add(blank14);
                                  frame.add(okB);
                                  frame.add(clearB);
                                  frame.add(awtL);
                                  frame.add(awtLA);
                                  frame.setSize(800,200);
                                  frame.setVisible(true);
                                  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public static void main (String [] args)
              CPUSched O = new CPUSched();
    }

  • Very very desperate ....please help!!

    I have a very simple but seemingly very hard to solve problem in JBuilder 6 Personal.....
    Firstly, I have 2 Application frame, say A frame and B frame, and i have certain JLabel in A frame called HField (which i want to set the field to be hidden). I've link these 2 pages using these statement:
    for A frame:
    public class A extends JFrame....{
    A aFrame;
    B bFrame;
    public jbinit { // component initialzation
    bFrame = new B(this);
    void GotoB_actionPerformed(ActionEvent e) {
    bFrame.setVisible(true);
    this.setVisible(false);
    for B frame:
    public class B extends JFrame....{
    JFrame aFrame;
    public B(JFrame tempFrame) {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbinit();
    aFrame = tempFrame;
    catch {....}
    void closeB_actionPerformed(ActionEvent e) {
    this.setVisible(false);
    aFrame.setVisible(true);
    (Some details are omitted.) As a result, the navigation works fine...
    Now I'd like B frame to recall HField in A frame to get the data. So i add this statement in both frame:
    public A frame.... {
    String HField;
    HField.setEnabled(false);
    public B frame...{
    A aFrame;
    System.out.println(aFrame.HField);
    It's NOT working, and I receive such error:
    NullPointerEXception
    then i try to create a new class called C, which is just a java class but not application class. I put the variable there and try to recall the variable using:
    for B frame:
    public B frame...{
    C cClass = new C();
    System.out.println(cClass.HField);
    it works(Surely!!) but when i try to set the variable in A, navigate from A to B and then retrieve it in B , like adding:
    for A frame:
    public A frame....{
    C cClass = new C();
    cClass.HField = "ABC";
    public B frame...{
    C cClass = new C();
    System.out.println(cClass.HField);
    the NullPinterException comes again.
    I have totally NO idea what's happening.... Can anyone help me to solve it out???
    Anyone who solves this can get 10 tokens!!! Please help!!!!!!

    It's still not working....
    I got an error message like
    "UserPage.java": Error #: 300 : variable HField not found in class javax.swing.JFrame at line 208, column 30
    Well the code for A(indeed Login) frame is like this:
    public class Login extends JFrame {
    Login login1;
    UserPage userPage;
    public String HField = "";
    public Login() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    userPage = new UserPage(this);
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void login_actionPerformed(ActionEvent e) {
    HField = "YEAH!!!";
    this.setVisible(false);
    new UserPage().show();
    (Of course the login button is initialized)
    For B(Indeed UserPage) frame:
    public class UserPage extends JFrame {
    public JFrame login1;
    public UserPage() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public UserPage(JFrame aFrame) {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    login1 = aFrame;
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void Back_actionPerformed(ActionEvent e) {
    System.out.println(login1.HField);
    this.setVisible(false);
    new Login().show();
    ( Back button is initialized also)
    So, what's the real problem? I understand virian's thought and try to tackle it but fail to do so......why I cannot create an instance of Login frame and retrieve it in other frame?

  • Can't get the arrangement I want in JPanel. Please Help!

    Hi all,
    I'm using a GridBagLayout to position several JLabels, JTextFields and JButtons...with the JLabels and it's respective JTextFields side by side and the JButtons at the bottom in a straight column.
    Thing is, no matter how I change the GridBagConstraints, the whole thing will still spread out to cover all the space available which is not what I want...is there a way to go about this using GridBagLayout??
    I've read about how you use the GridBagLayout in the Java doc but still unsure how the weightx and weighty works...suspect they might be the key to getting the result I want but so far no luck....
    can anyone please help? Thanks a lot :D

    hi yuhijen,
    when i replied to u last time, i ddin't explore the capabilities of the weightx or weighty fields of the GridBagConstraints!!
    so i'm sending u a code that'll give u exactly what u had wanted!! :-)
    import java.awt.*;
    import java.applet.*;
    /* <applet code="trialGridBL" width="500" height="400"></applet> */
    public class trialGridBL extends Applet{
         GridBagConstraints gbc;
         GridBagLayout gbl;
         Label L1,L2,Blank1,Blank2,Blank3;
         TextField T1,T2;
         Button B1,B2;
         public void init(){
              L1=new Label("Name");
              L2=new Label("Password");
              Blank1=new Label("");
              Blank2=new Label("");
              Blank3=new Label("");     
              T1=new TextField(15);
              T2=new TextField(15);
              B1=new Button("Submit");
              B2=new Button("Reset");
              gbc=new GridBagConstraints();
              gbl=new GridBagLayout();
              gbc.gridy=0;
              gbc.anchor=GridBagConstraints.WEST;
              gbc.weightx=1;
              gbl.setConstraints(L1,gbc);
              gbl.setConstraints(T1,gbc);
              gbl.setConstraints(Blank1,gbc);
              gbl.setConstraints(Blank2,gbc);
              gbc.gridwidth=GridBagConstraints.REMAINDER;
              gbl.setConstraints(Blank3,gbc);     
              gbc.gridy=1;
              gbc.gridwidth=1;
              gbl.setConstraints(L2,gbc);
              gbc.gridwidth=GridBagConstraints.REMAINDER;
              gbl.setConstraints(T2,gbc);
              gbc.gridy=2;
              gbc.weighty=5;
              gbc.anchor=GridBagConstraints.NORTHWEST;
              gbc.gridwidth=1;
              gbl.setConstraints(B1,gbc);
              gbc.gridwidth=GridBagConstraints.REMAINDER;
              gbl.setConstraints(B2,gbc);
              // now set the layout for the contentPane (by default its BorderLayout)
              setLayout(gbl);
              // finally add the components
              L1.setBackground(Color.orange);
              add(L1);
              add(T1);
              add(Blank1);
              add(Blank2);
              add(Blank3);
              add(L2);
              add(T2);
              add(B1);
              add(B2);
    this is for awt, u just change it for swings.
    rgds,
    JP

  • Please help me ( advanced graphical user interface)

    I have to finish this problem until 5 pm.
    Java How to program (Deitel & Deitel) - Third edition
    page 696
    please help me
    13-7 : write a program that displays a circle of random size and calculates and displays the area, radius, diameter and circumference. Use the following equations : diameter=2 * radius, area = 3.14(pie) * radius * radius, circumference = 2 * pie * radius. Use the constant Math.PI for pi. All drawing should be done on a subclass of JPanel and the result of the calculations should be displayed in a read-only JTextArea.
    13-10 : Write a program that uses the paint method to draw the current value of a JSlider on a subclass of JPanel. In addition, provide a JTextField where a specific value can be entered. The JTextField should display the current value of the JSlider at all times. A JLabel should be used to identify the JTextField. The JSlider methods setValue and getValue should be used.(Note : The setValue method is a public method that does not return a value and takes one integer arguement - the JSlider value, which determines the position of the thumb.)

    ... until 5 pm.What time zone? I can only see that your message was posted yesterday 7:30 PM, in some unknown time zone.
    And, you are more likely to get help if you show that you have tried to find a solution on your own. No sane person will do your work for you!

  • HI Please Help me with Zoom of a buffered image

    Hi All,
    Please help,
    I want to zoom the buffered image using Affine Transforms, the code shown below can rotate the buffered image now how to zoom the same buffered image using Affine Transforms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class RotationBounds extends JPanel implements ActionListener
        BufferedImage image;
        AffineTransform at = new AffineTransform();
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        double theta = 0;
        double thetaInc = Math.PI / 2;
        public void actionPerformed(ActionEvent e)
            theta += thetaInc;
            setTransform();
            repaint();
        private void setTransform()
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width = iw * cos + ih * sin;
            double height = ih * cos + iw * sin;
            double x = (getWidth() - iw) / 2;
            double y = (getHeight() - ih) / 2;
            at.setToTranslation(x, y);
            at.rotate(theta, iw / 2.0, ih / 2.0);
            x = (getWidth() - width) / 2;
            y = (getHeight() - height) / 2;
            // Set bounding rectangle that will frame the image rotated
            // with this transform. Use this width and height to make a
            // new BuffferedImage that will hold this rotated image.
            // AffineTransformOp doesn't have this size information in
            // the translation/rotation transform it receives.
            bounds.setFrame(x - 1, y - 1, width + 1, height + 1);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            setBackground(Color.gray);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            if (image == null)
                initImage();
            g2.drawRenderedImage(image, at);
            // g2.setPaint(Color.blue);
            g2.draw(bounds);
            g2.setPaint(Color.green.darker());
            g2.fill(new Ellipse2D.Double(getWidth() / 2 - 2,
                getHeight() / 2 - 2, 4, 4));
        private void initImage()
            int w = 360, h = 300;
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(220, 240, 240));
            g2.fillRect(0, 0, w, h);
            g2.setPaint(Color.red);
            g2.drawString("Text for test", 50, 50);
            g2.drawRect(0, 0, w - 1, h - 1);
            g2.dispose();
            g2.setTransform(at);
    //        setTransform();
        private JPanel getLast()
            JButton rotateButton = new JButton("Rotate");
            rotateButton.addActionListener(this);
             JButton zoomButton = new JButton("Zoom");
            JPanel panel = new JPanel();
            panel.add(rotateButton);
            panel.add(zoomButton);
            return panel;
        public static void main(String[] args)
            RotationBounds test = new RotationBounds();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLast(), "North");
            f.setSize(400, 400);
            f.setLocation(0, 0);
            f.setVisible(true);
    }Message was edited by:
    New_to_Java

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.event.*;
    public class RotationZoom extends JPanel {
        AffineTransform at = new AffineTransform();
        Point2D.Double imageLoc = new Point2D.Double(100.0, 50.0);
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        BufferedImage image;
        double theta = 0;
        double scale = 1.0;
        final int PAD = 20;
        public RotationZoom() {
            initImage();
        public void addNotify() {
            super.addNotify();
            setTransform();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);
            g2.setPaint(Color.red);
            g2.draw(bounds);
        public Dimension getPreferredSize() {
            return new Dimension((int)(imageLoc.x + Math.ceil(bounds.width))  + PAD,
                                 (int)(imageLoc.y + Math.ceil(bounds.height)) + PAD);
        private void update() {
            setTransform();
            revalidate();
            repaint();
        private void setTransform() {
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width  = iw*cos + ih*sin;
            double height = ih*cos + iw*sin;
            at.setToTranslation(imageLoc.x, imageLoc.y);
            at.rotate(theta, scale*iw/2.0, scale*ih/2.0);
            at.scale(scale, scale);
            double x = imageLoc.x - scale*(width - iw)/2.0;
            double y = imageLoc.y - scale*(height - ih)/2.0;
            bounds.setFrame(x, y, scale*width, scale*height);
        private void initImage() {
            int w = 240, h = 180;
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w,h,type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(new Color(220,220,240));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.red);
            g2.draw(new CubicCurve2D.Double(0, h, w*4/3.0, h/4.0,
                                            -w/3.0, h/4.0, w, h));
            g2.setPaint(Color.green.darker());
            g2.draw(new Rectangle2D.Double(w/3.0, h/3.0, w/3.0, h/3.0));
            g2.dispose();
        private JPanel getControls() {
            JSlider rotateSlider = new JSlider(-180, 180, 0);
            rotateSlider.setMajorTickSpacing(30);
            rotateSlider.setMinorTickSpacing(10);
            rotateSlider.setPaintTicks(true);
            rotateSlider.setPaintLabels(true);
            rotateSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    theta = Math.toRadians(value);
                    update();
            rotateSlider.setBorder(BorderFactory.createTitledBorder("theta"));
            int min = 50, max = 200, inc = 25;
            JSlider zoomSlider = new JSlider(min, max, 100);
            zoomSlider.setMajorTickSpacing(inc);
            zoomSlider.setMinorTickSpacing(5);
            zoomSlider.setPaintTicks(true);
            zoomSlider.setLabelTable(getLabelTable(min, max, inc));
            zoomSlider.setPaintLabels(true);
            zoomSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    scale = value/100.0;
                    update();
            zoomSlider.setBorder(BorderFactory.createTitledBorder("scale"));
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(rotateSlider, gbc);
            panel.add(zoomSlider, gbc);
            return panel;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JComponent> table = new Hashtable<Integer,JComponent>();
            for(int j = min; j <= max; j += inc) {
                JLabel label = new JLabel(String.format("%.2f", j/100.0));
                table.put(new Integer(j), label);
            return table;
        public static void main(String[] args) {
            RotationZoom test = new RotationZoom();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getControls(), "Last");
            f.setSize(500,500);
            f.setLocation(200,100);
            f.setVisible(true);
    }

Maybe you are looking for