Add Divider to JComboBox

Hello,
I was wondering how I can add a divider after I add each symbol to this JComboBox? Is JSeparator a good idea?
Please help out.
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JSeparator;
public class MyComboBoxDividerTest extends JComboBox {
     private DefaultComboBoxModel myModel = new DefaultComboBoxModel();
     public MyComboBoxDividerTest()
          setModel(myModel);
          setEditable(true);
     public void generateComboBox()
          ArrayList list = new ArrayList();
          list.add("symbol1");
          list.add("symbol2");
          list.add("symbol3");
          list.add("symbol4");
          list.add("symbol5");
          JFrame frame = new JFrame("My ComboBox");
          for(int i=0;i<list.size();i++)
               myModel.addElement(list.get(i));
               //TODO: ADD SEPARATOR HERE (I think)
          JComboBox comboBox = new JComboBox(myModel);
          frame.getContentPane().add(comboBox);
          frame.setSize(200,55);
          frame.setVisible(true);
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          MyComboBoxDividerTest test = new MyComboBoxDividerTest();
          test.generateComboBox();
}

You dont need to add a JSeparator at all. This is not a model level issue but a renderer level issue. In other words you'll have to modify you JComboBox cell renderer instead of its model
From the ListCellRenderer documentation with modifications. Check Out the commented addition:
class MyCellRenderer extends JLabel implements ListCellRenderer {
     public MyCellRenderer() {
         setOpaque(true);
     public Component getListCellRendererComponent(JList list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {
         setText(value.toString());
         // you can draw the line using a MatteBorder
         // you may need to implement a CompoundBorder to get add spacing around the text using an EmptyBorder
         setBorder( new MatteBorder(0,0,2,0, Color.black) ); //
         Color background;
         Color foreground;
         // check if this cell represents the current DnD drop location
         JList.DropLocation dropLocation = list.getDropLocation();
         if (dropLocation != null
                 && !dropLocation.isInsert()
                 && dropLocation.getIndex() == index) {
             background = Color.BLUE;
             foreground = Color.WHITE;
         // check if this cell is selected
         } else if (isSelected) {
             background = Color.RED;
             foreground = Color.WHITE;
         // unselected, and not the DnD drop location
         } else {
             background = Color.WHITE;
             foreground = Color.BLACK;
         setBackground(background);
         setForeground(foreground);
         return this;
// once you have the Renderer, connect it to your JComboBox
JComboBox box = new JComboBox();
   box.setRenderer( new MyCellRenderer() );Cheers, ICE

Similar Messages

  • How to add JPanel in  JComboBox?

    Hi.
    How to add JPanel in JComboBox...?
    Regards
    Bilal

    I do not know much about Cardlayout.
    As far as I know, it is a layout which let you assign a serveral 'card' and exist together. By consider the order of the card, you could change the view of each page by using method- first, last, next etc. However, I would like to know what if I got a number of buttons, say A B C D E F, and having cards called a b c d e f,I know I could change from a to b, but what if I want to change from c to e by pressing the button E (assuming it showing the c card now).
    Actually, I was able to create the code now which adding one JPanel to another now. First create a JPanel with prefer size, min max size.
    then add a JPanel into the CENTER of the above JPanel, both using borderlayout.
    But having a little difficulties, could I add more JPanel into the CENTER such that one overlapping each other, by those Buttons, through action and event, hide those which I do not want to show?
    Like A B C buttons, a b c panels. When press A hide b c and show a, so on.
    Could I use method like movetofront(something like that, forgot detail which read in a book) to do this?
    Cheers

  • JTable with JComboBox

    Hi friends,
    I am adding JComboBox in JTable its working properly
    But data is not adding dynamically to JComboBox
    I am Sending my Code plz give me reply
    I am Struggleing from 1 week on wards
    package com.dnt.autopopulation;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.event.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.TableModelEvent;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;
    import java.text.SimpleDateFormat;
    import java.util.Vector;
    import javax.swing.border.*;
    import com.dnt.eaip.Connectmagr;
    import com.dnt.eaip.*;
    import com.dnt.util.*;
    import javax.swing.plaf.ButtonUI;
    import com.dnt.admin.EndStartDateCheck;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    public class AutoPopRollBack extends JPanel {
    boolean selection = false;
    public static final int HAND_CURSOR = 12;
    Cursor cursor = new Cursor(HAND_CURSOR);
    int selectedRow = -1;
    ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
    JLabel HeaderLabe = new JLabel(headertop1);
    Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
    Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
    new Color(154, 254, 211), new Color(108, 178, 148),
    new Color(37, 60, 50), new Color(53, 87, 72));
    DefaultTableModel dm = new DefaultTableModel();
    Vector searchlist = new Vector();
    Vector rows = new Vector();
    Vector returnList;
    Connectmagr objConnectmagr = new Connectmagr();
    JFrame frame = new JFrame();
    JLabel headlab = new JLabel();
    JCalendarComboBox EndDateTxt;
    JLabel HawbLab = new JLabel();
    JTextField HawbTxt = new JTextField();
    JLabel AgentLab = new JLabel();
    JLabel StartDateLab = new JLabel();
    JCalendarComboBox StartDateTxt;
    JComboBox AgentLBox = new JComboBox();
    JLabel EnddateLab = new JLabel();
    JPanel ReviewJobsPane = new JPanel();
    JButton SearchBtn = new JButton();
    ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
    ArrayList AgentList = new ArrayList();
    JComboBox DocTypeLBox = new JComboBox();
    JLabel doctypelab = new JLabel();
    JPanel displayPanel = new JPanel();
    ButtonGroup group1;
    JRadioButton rb;
    JTable table;
    public ArrayList jobList = new ArrayList();
    public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
    this.frame = frame;
    this.AgentList = agentArrayList;
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public void jbInit() throws Exception {
    Calendar cal = Calendar.getInstance();
    Locale loc = new Locale("");
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    HeaderLabe.setBackground(new Color(250, 233, 216));
    HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
    this.setLayout(null);
    this.setBackground(SystemColor.control);
    headlab.setBackground(new Color(250, 233, 216));
    headlab.setFont(new java.awt.Font("Verdana", 1, 12));
    headlab.setForeground(Color.blue);
    headlab.setHorizontalAlignment(SwingConstants.CENTER);
    headlab.setText(" :: Auto Population Rollback");
    headlab.setBounds(new Rectangle(39, 2, 247, 25));
    EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
    EndDateTxt.setBackground(Color.white);
    EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EndDateTxt.setForeground(Color.blue);
    EndDateTxt.setBorder(null);
    HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
    HawbLab.setForeground(Color.blue);
    HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
    HawbLab.setText("Job No/Airway Bill No:");
    HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
    HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
    HawbTxt.setText("");
    HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    HawbTxt.setForeground(Color.blue);
    HawbTxt.setBorder(border1);
    AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
    AgentLab.setForeground(Color.blue);
    AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
    AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
    AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
    StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    StartDateLab.setForeground(Color.blue);
    StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    StartDateLab.setText("Start Date:");
    StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
    StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
    StartDateTxt.setBackground(Color.white);
    StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    StartDateTxt.setForeground(Color.blue);
    StartDateTxt.setBorder(null);
    AgentLBox.setBackground(Color.white);
    AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    AgentLBox.setForeground(Color.blue);
    AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
    AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    EnddateLab.setForeground(Color.blue);
    EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    EnddateLab.setText("End Date:");
    EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
    ReviewJobsPane.setBackground(new Color(240, 233, 216));
    ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
    ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
    ReviewJobsPane.setLayout(null);
    SearchBtn.setUI(ui);
    SearchBtn.setCursor(cursor);
    SearchBtn.setBackground(new Color(76, 125, 104));
    SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
    SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
    SearchBtn.setForeground(Color.white);
    SearchBtn.setBorder(border2);
    SearchBtn.setOpaque(true);
    SearchBtn.setFocusPainted(false);
    SearchBtn.setText("Search");
    SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
    for (int i = 0; i < AgentList.size(); i++)
    AgentLBox.addItem( (String) AgentList.get(i));
    DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    DocTypeLBox.setForeground(Color.blue);
    DocTypeLBox.setMinimumSize(new Dimension(22, 19));
    DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
    DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    DocTypeLBox.addItem("New Jobs");
    DocTypeLBox.addItem("Draft jobs");
    DocTypeLBox.addItem("Finished jobs");
    doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
    doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
    doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
    doctypelab.setForeground(Color.blue);
    doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
    displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
    this.add(headlab, null);
    this.add(HeaderLabe, null);
    this.add(ReviewJobsPane, null);
    ReviewJobsPane.add(HawbLab, null);
    ReviewJobsPane.add(AgentLab, null);
    ReviewJobsPane.add(AgentLBox, null);
    ReviewJobsPane.add(StartDateLab, null);
    ReviewJobsPane.add(StartDateTxt, null);
    ReviewJobsPane.add(HawbTxt, null);
    ReviewJobsPane.add(EnddateLab, null);
    ReviewJobsPane.add(EndDateTxt, null);
    ReviewJobsPane.add(DocTypeLBox, null);
    ReviewJobsPane.add(doctypelab, null);
    this.add(SearchBtn, null);
    this.add(displayPanel, null);
    //this.add(scrollPaneView, null);
    // scrollPaneView.getViewport().add(displayPanel, null);
    this.setVisible(true);
    void FieldEditable(boolean str) {
    StartDateTxt.setEnabled(str);
    EndDateTxt.setEnabled(str);
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    ArrayList agentlist = new ArrayList();
    agentlist.add(0, "BF0651");
    agentlist.add(1, "PF0010");
    AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
    frame.getContentPane().add(objAutoPopRollBack);
    frame.setBounds(new Rectangle(0, 0, 820, 593));
    frame.setVisible(true);
    void SearchBtn_actionPerformed(ActionEvent e) {
    displayPanel.setVisible(false);
    Vector data=new Vector();
    rows.removeAllElements();
    boolean flag = true;
    String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
    try {
    if(HawbTxt.getText().equalsIgnoreCase("")){
    if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(this, "Please Select Start Date",
    "Warning", JOptionPane.WARNING_MESSAGE);
    flag = false;
    else if (!che.equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
    flag = false;
    }else{
    FieldEditable(true);
    if (flag) {
    try {
    displayPanel.removeAll();
    } catch (Exception ex) {
    rows.removeAllElements();
    data.removeAllElements();
    SearchBtn.setEnabled(true);
    searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
    if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
    searchlist.add(1, HawbTxt.getText().toString().trim());
    else
    searchlist.add(1, "");
    searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
    String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
    String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
    Vector columns = new Vector();
    columns.add(0, "");
    columns.add(1, "JOB No");
    columns.add(2, "Status");
    columns.add(3, "Current Form Type");
    columns.add(4, "New Form Type");
    System.out.println("Before calling Data Base");
    jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
    if (jobList.size() > 0) {
    for (int i = 0; i < jobList.size(); i++) {
    ArrayList temp = new ArrayList();
    temp = (ArrayList) jobList.get(i);
    Vector col = new Vector();
    col.add(0, new Boolean(false));
    col.add(1, temp.get(0).toString().trim());
    col.add(2, temp.get(1).toString().trim());
    col.add(3, temp.get(2).toString().trim());
    Vector tempstr=new Vector();
    String [] tem=temp.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    col.add(4, new JComboBox(tempstr));
    data.add(col);
    dm.setDataVector(data, columns);
    table = new JTable(dm) {
    public void tableChanged(TableModelEvent e) {
    super.tableChanged(e);
    public boolean isCellEditable(int rowIndex, int vColIndex) {
    return true;
    JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(false);
    table.setBackground(SystemColor.inactiveCaptionText);
    table.setRowHeight(20);
    JTableHeader head = table.getTableHeader();
    head.setSize(850, 75);
    table.setTableHeader(head);
    table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
    table.getTableHeader().setBackground(new Color(130, 170, 150));
    table.getTableHeader().setForeground(Color.BLUE);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
    table.setForeground(new Color(125, 25, 0));
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setMinWidth(75);
    col.setMaxWidth(75);
    TableColumn col1 = table.getColumnModel().getColumn(1);
    col1.setMinWidth(150);
    col1.setMaxWidth(150);
    TableColumn col2 = table.getColumnModel().getColumn(2);
    col2.setMinWidth(150);
    col2.setMaxWidth(150);
    TableColumn col3 = table.getColumnModel().getColumn(3);
    col3.setMinWidth(150);
    col3.setMaxWidth(150);
    TableColumn col4 = table.getColumnModel().getColumn(4);
    col4.setMinWidth(160);
    col4.setMaxWidth(160);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
    Vector tempstr=new Vector();
    for(int j=0;j<jobList.size();j++){
    ArrayList temlist=(ArrayList)jobList.get(j);
    String [] tem=temlist.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    JComboBox portTypesCombo = new JComboBox(tempstr);
    col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
    col4 = table.getColumnModel().getColumn(4);
    col4.setCellEditor(new MyComboBoxEditor(tempstr));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
    System.out.println(tempstr);
    displayPanel.setLayout(new BorderLayout());
    displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    table.setEditingColumn(0);
    int column = 0;
    if (e.getClickCount() == 1) {
    Point p = e.getPoint();
    selectedRow = table.rowAtPoint(p);
    column = table.columnAtPoint(p);
    System.out.println(table.isCellEditable(selectedRow, column));
    if (column != 0) {
    selectedRow = -1;
    returnList = new Vector();
    returnList = (Vector) rows.get(selectedRow);
    else if (column == 0) {
    table.revalidate();
    table.repaint();
    scroll.getViewport().add(table);
    displayPanel.add(scroll, BorderLayout.CENTER);
    displayPanel.setVisible(true);
    else {
    JOptionPane.showMessageDialog(this, "No Data Available");
    } catch (Exception e1) {
    e1.printStackTrace();
    class MyItemListener implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if (source instanceof AbstractButton == false)return;
    boolean checked = e.getStateChange() == ItemEvent.SELECTED;
    for (int x = 0, y = table.getRowCount(); x < y; x++) {
    table.setValueAt(new Boolean(checked), x, 0);
    class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
    AutoPopRollBack adaptee;
    AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.SearchBtn_actionPerformed(e);
    class RadioButtonRenderer implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value == null)return null;
    return (Component) value;
    class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
    private JRadioButton button;
    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row,
    int column) {
    if (value == null)return null;
    button = (JRadioButton) value;
    button.addItemListener(this);
    return (Component) value;
    public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
    protected static Border m_noFocusBorder;
    public CheckCellRenderer() {
    super();
    m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(m_noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (value instanceof Boolean) {
    Boolean b = (Boolean) value;
    setSelected(b.booleanValue());
    setBackground(isSelected && !hasFocus ?
    table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected && !hasFocus ?
    table.getSelectionForeground() : table.getForeground());
    setFont(table.getFont());
    setBorder(hasFocus ? UIManager.getBorder(
    "Table.focusCellHighlightBorder") : m_noFocusBorder);
    return this;
    class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
    protected CheckBoxHeader rendererComponent;
    protected int column;
    protected boolean mousePressed = false;
    public CheckBoxHeader(ItemListener itemListener) {
    rendererComponent = this;
    rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    rendererComponent.setForeground(header.getForeground());
    rendererComponent.setBackground(header.getBackground());
    rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
    header.addMouseListener(rendererComponent);
    setColumn(column);
    rendererComponent.setText("Select All");
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return rendererComponent;
    protected void setColumn(int column) {
    this.column = column;
    public int getColumn() {
    return column;
    protected void handleClickEvent(MouseEvent e) {
    if (mousePressed) {
    mousePressed = false;
    JTableHeader header = (JTableHeader) (e.getSource());
    JTable tableView = header.getTable();
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
    doClick();
    public void mouseClicked(MouseEvent e) {
    handleClickEvent(e);
    ( (JTableHeader) e.getSource()).repaint();
    public void mousePressed(MouseEvent e) {
    mousePressed = true;
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    // Select the current value
    setSelectedItem(value);
    return this;
    class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    and Bringing data from data base by using this method
    if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
    else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
    st = con.createStatement();
    System.out.println("---new jobs search-->" + sqlString);
    rs = st.executeQuery(sqlString);
    while (rs.next()) {
    retVector = new ArrayList();
    retVector.add(0, rs.getString("JOBNO"));
    retVector.add(1, "New Job");
    retVector.add(2, rs.getString("DOC_TYPE"));
    String temp="";
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    temp="K8I|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
    temp="K8E";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
    // temp="K1|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
    temp="K1|K8I";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
    temp="K2";
    retVector.add(3,temp);
    retVector.add(3, rs.getString("AGENT_CODE"));
    retVectorlist.add(retVector);
    i am sending data To ComboBox like this
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    K8I and K8T
    if K2 adding k8E and for other types as mentioned above
    But for ComboBoxes it is showing same Items not changing
    Please any body can help to me
    Thanks and Regards
    Ravichandra

    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • Incorporate: For, and while loop,a nested pair for both,and to add graphics

    // I have done the class but
    need help one adding one while loop, one for loop, and a nested pair loops using for and while, and if posbile to add on a dynamite graphics. // i am doing this for a brithday present for my brother who is a java programer
    and would be happy to see his little brother make a java programe for him
    //class file
    import java.awt.*;
    public class ZZZCalculator
            private double amount;
            public ZZZCalculator (double x)
                    amount= x;
            public void addAmt (double inputNumber)
                    amount= amount +inputNumber;
            public void divideAmt (double inputNumber)
                    amount=amount/inputNumber;
            public void subtractAmt (double inputNumber)
                    amount=amount-inputNumber;
            public void multiplyAmt (double inputNumber)
                    amount=amount*inputNumber;
            public void display (Graphics g)
                    g.drawString (""+ amount, 150,100);
            public void setAmt(double x)
                    amount= x;
      // Pgm file
    import java.awt.*;
    import java.applet.Applet;
    import java.awt.event.*;
    public class ZZZCalc extends Applet implements ActionListener {
            ZZZCalculator henrietta;
            TextField amtPlace;
            Button adder;
            Button divide;
            Button subtract;
            Button multiply;            
            public void init()
                    henrietta=new ZZZCalculator(0.0);
                    amtPlace=new TextField(10);
                    amtPlace.addActionListener(this);
                    add(amtPlace);
                    adder=new Button ("+");
                    adder.addActionListener(this);
                    add(adder);
                    divide=new Button ("/");
                    divide.addActionListener(this);
                    add(divide);
                    subtract=new Button ("-");
                    subtract.addActionListener(this);
                    add(subtract);
                    multiply=new Button ("*");
                    multiply.addActionListener(this);
                    add(multiply);
            public void paint (Graphics g)
                    g.drawString("amount:", 100,100);
                    henrietta.display(g);
            public void actionPerformed(ActionEvent e)
                    if (e. getSource()==amtPlace)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.setAmt(amt);
                    repaint();
                    if(e.getSource()==adder)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.addAmt(amt);
                    repaint();
                    if(e.getSource()==divide)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.divideAmt(amt);
                    repaint();
                    if(e.getSource()==subtract)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.subtractAmt(amt);
                    repaint();
                    if(e.getSource()==multiply)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta. multiplyAmt(amt);
                   repaint();
    //thank you for the help
    i have just started working on java and this is my frist program i am working on and any help i can get would inprove my understanding of java.
    Thank you very much for you help

    hey there... this is Rebecca
    try this somewhere in the prog.
    n = Math.pow(x,y)
    where n is an int you declare...
    and x and y are the numbers... as in
    n = 10^3
    where 10 = x and 3 = y

  • Fill JComboBox with Vector from database

    Hi there,
    I have a problem with filling a JComboBox with data from a database. I can print the data in the console, but it seems to be impossible to do it in a ComboBox ...
    I tried this:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    *package client;*
    *import data.Raum;*
    *import data.RaumImpl;*
    *import java.net.MalformedURLException;*
    *import java.rmi.Naming;*
    *import java.rmi.NotBoundException;*
    *import java.rmi.RemoteException;*
    *import java.sql.SQLException;*
    *import javax.swing.JComboBox;*
    *import javax.swing.JFrame;*
    *import java.util.Vector;*
    *import verwaltung.*;
    import server.DraServer;
    * @author philipp
    public class ComboBox extends JFrame
        ComboBox(String title) throws RemoteException, SQLException, NullPointerException, MalformedURLException, NotBoundException {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DraVerwaltung verwaltung = (DraVerwaltung) Naming.lookup ("rmi://localhost/DRA");
        System.out.println("Remote object created...");
        Vector raeume = verwaltung.RaumAusleser();
        Raum r;
        for (int i = 0; i < raeume.size(); i++)
            r = (Raum)raeume.elementAt(i);
    //      System.out.println ("Raum: " + r.getRaumname());
    //      System.out.println ("Raumid: " + r.getIdRaum());
         JComboBox jcb = new JComboBox(r.getRaumname());
        getContentPane().add(jcb);
        setSize(200, 50);
        setVisible(true);      
      public static void main(String[] args) throws RemoteException, SQLException, NullPointerException, MalformedURLException, NotBoundException {
        new ComboBox("Test");
    }In this case I get the following for JComboBox (line 44):
    "cannot find symbol
    symbol: constructor JComboBox(java.lang.string)
    location: class javax.swing.JComboBox"
    I tried:
    -> change "JComboBox jcb = new JComboBox(r.getRaumname());" to "JComboBox jcb = new JComboBox(raeume);"
    then I got the JComboBox, but with ... I don't know how to describe the content. It seems like a (very long) reference.
    All other tries can't be tested, because I got the problem with constructor again.
    I'm happy for an early response.
    Regards

    Now, it works!
    It looks like that:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package client;
    import data.Raum;
    import data.RaumImpl;
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.sql.SQLException;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import java.util.Vector;
    import verwaltung.*;
    import server.DraServer;
    * @author philipp
    public class ComboBox extends JFrame
        ComboBox(String title) throws RemoteException, SQLException, NullPointerException, MalformedURLException, NotBoundException {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DraVerwaltung verwaltung = (DraVerwaltung) Naming.lookup ("rmi://localhost/DRA");
        System.out.println("Remote object created...");
        Vector raeume = verwaltung.RaumAusleser();
        Raum r = new RaumImpl();
        Vector vJcb = new Vector();
        for (int i = 0; i < raeume.size();i++){
            r = (Raum)raeume.elementAt(i); 
            vJcb.add(r.getRaumname());
        JComboBox jcb = new JComboBox(vJcb);
        getContentPane().add(jcb);
        setSize(200, 50);
        setVisible(true);     
        public static void main(String[] args) throws RemoteException, SQLException, NullPointerException, MalformedURLException, NotBoundException {
           new ComboBox("Combo box Demo1");
    }Thanks in advantage to all!

  • Putting dividing lines in Reports 6i

    Hi everyone,
    I created a report in Reports 6i and I would like to know how can I add dividing lines to each column and row so people can read the values better.
    Thanks in advance!!
    Edited by: user626836 on May 13, 2011 5:12 AM

    dividing lines to each column and rowThat is actually a frame around each field.
    In the layout editor, click on a field and select a line color in the tool palette.

  • Dividing a Frame

    Greetings to All:
    I was wondering if and how I can add dividing lines in my frame. I have created a frame with a grid layout and used JPanels to build each of the grid sections. I want to be able to show dividing lines between the different grid sections to show a clear division between the sections.

    You can use a JSeparator.

  • Synchronize 2 Jcombobox

    Hi there,
    Could someone tell me how to synchronize 2 Jcomboboxs?
    The 2 Jcomboboxs use the same set of data, but they display different values.
    E.g., box1 shows the Name and box2 shows Address
    What I want to do is when someone select Name1, the corresponding Address1 will appear (selected) on box2
    Any idea wouls be appreicated.
    Thanks

    That's a good solution but if you want to work only with combobox, you need to add a listener :
    JComboBox myCB1 = new JComboBox(...);
    JComboBox myCB2 = new JComboBox(...);
    myCB1.addActionListener(
       new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             int index = myCB1.getSelectedIndex();
             myCB2.setSelectedIndex(index);
    myCB2.addActionListener(
       new ActionListener() {
          public void actionPerformed(ActionEvent e) {
             int index = myCB2.getSelectedIndex();
             myCB1.setSelectedIndex(index);
    );

  • JTree - JComboBox interaction

    I have a program that displays editable information for each node in a tree. I've run into a problem where a user may update the contents of a JComboBox and then click on a new node without saving their changes. If the information was just lost (as it is with a JTextField), I would have no problem, but the information is saved under the node that was just clicked. Below is an oversimplified example of my problem.
    1) Click TreeNode 1, type something in the JComboBox, hit enter, and then click back and forth from TreeNode 2. Everything is as it should be.
    2) Now restart the example (there is only a problem if the JComboBox is blank to begin with), and do the same thing without hitting enter.
    In the actual program I have a custom TreeModel, a custom TreeSelectionListener, a custom TreeRenderer, etc. but nothing I've tried does any good (and I've tried so many different things, including creating a previousNode variable and an isBeingEditted variable, all to no avail).
    The JComboBox and the automatic update both serve important purposes, so I'd like to keep that functionality. Any help would be greatly appreciated.
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.awt.event.*;
    import java.awt.*;
    public class TreeComboBoxProblem extends JFrame {
        private JTree tree;
        private JLabel nodeName;
        private JComboBox nodeValue;
        public TreeComboBoxProblem(String name) {
            super(name);
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(new TreeNode("TreeNode 0"));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 1")));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 2")));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 3")));
            getContentPane().add( tree = new JTree(top), BorderLayout.NORTH );
            tree.addTreeSelectionListener( new TreeListener() );
            JPanel info = new JPanel();
            info.add( nodeName = new JLabel("TreeNode 0"));
            info.add( nodeValue = new JComboBox());
            nodeValue.setPreferredSize(new Dimension(102, 20));
            nodeValue.setEditable(true);
            nodeValue.addActionListener(new infoActionListener());
            getContentPane().add( info, BorderLayout.SOUTH );
        class TreeNode {
            String name;
            String value;
            public TreeNode(String name) {
                this.name = name;
                value = "";
            public String toString() {
                return name;
        protected class TreeListener implements TreeSelectionListener {
            public void valueChanged(TreeSelectionEvent e) {
                showInfo();
        public void showInfo() {
            TreeNode node = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
            nodeName.setText(node.name);
            nodeValue.setSelectedItem(node.value);
        protected class infoActionListener implements ActionListener {
            public void actionPerformed(ActionEvent ae) {
                updateInfoSource();
        public void updateInfoSource() {
            TreeNode node = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
            node.value = (String)nodeValue.getSelectedItem();
        public static void main(String[] args) {
            JFrame frame = new TreeComboBoxProblem("TreeComboBoxProblem");
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible( true );
    }

    This is another solution for the problem:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class TreeComboBoxProblem extends JFrame {
        private JTree tree;
        private JLabel nodeName;
        private JComboBox nodeValue;
        private TreeNode selectedNode;
        public TreeComboBoxProblem(String name) {
            super(name);
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(new TreeNode("TreeNode 0"));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 1")));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 2")));
            top.add(new DefaultMutableTreeNode(new TreeNode("TreeNode 3")));
            getContentPane().add( tree = new JTree(top), BorderLayout.NORTH );
            tree.addTreeSelectionListener( new TreeListener() );
            JPanel info = new JPanel();
            info.add( nodeName = new JLabel("TreeNode 0"));
            info.add( nodeValue = new JComboBox(new String[] {}));       
            nodeValue.setPreferredSize(new Dimension(102, 20));
            nodeValue.setEditable(true);
            nodeValue.addActionListener(new infoActionListener());
            getContentPane().add( info, BorderLayout.SOUTH );
        class TreeNode {
            String name;
            String value;
            public TreeNode(String name) {
                this.name = name;
                value = "";
            public String toString() {
                return name;
        protected class TreeListener implements TreeSelectionListener {
            public void valueChanged(TreeSelectionEvent e) {
                showInfo();
        public void showInfo() {
            if (selectedNode != null)
                selectedNode.value = nodeValue.getEditor().getItem().toString();
            selectedNode = (TreeNode)((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent()).getUserObject();
            nodeName.setText(selectedNode.name);
            nodeValue.getEditor().setItem(selectedNode.value);
            nodeValue.setSelectedItem(selectedNode.value);
        protected class infoActionListener implements ActionListener {
            public void actionPerformed(ActionEvent ae) {
                updateInfoSource();
        public void updateInfoSource() {
            selectedNode.value = (String)nodeValue.getSelectedItem();
        public static void main(String[] args) {
            JFrame frame = new TreeComboBoxProblem("TreeComboBoxProblem");
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible( true );
    }

  • The component  couldn't get smaller  using gridbaglayout

    There is a vertical jsplitpane ,the upper part contains button,jtable,combox using gridbaglayout,I have set the GridBagConstraints.weightx,weighty to 1. The problem is when I drag divider to change upper size,it couldn't get smaller, even if I set all of the upper components' minimumsize to a tiny value.
    here is the code, I wrote it in windowsbuilder (a kind of eclipse swing plugin), I guess you can see it using ve too.
    package frame;
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import java.awt.Rectangle;
    import javax.swing.JSplitPane;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JLabel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import java.awt.Color;
    import javax.swing.JComboBox;
    import javax.swing.JButton;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    public class FrmMain extends JFrame {
         private JPanel contentPane;
         private JTable table;
          * Launch the application.
         public static void main(String[] args) {
              createWin();
          * Create the frame.
         public FrmMain() {
              setTitle("Notebook");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setBounds(100, 100, 573, 465);
              setBounds(new Rectangle(0, 0, 980, 738));
              contentPane = new JPanel();
              contentPane.setBounds(new Rectangle(0, 0, 980, 0));
              contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
              contentPane.setLayout(new BorderLayout(0, 0));
              setContentPane(contentPane);
              JSplitPane splAll = new JSplitPane();
              splAll.setDividerSize(10);
              splAll.setOneTouchExpandable(true);
              contentPane.add(splAll, BorderLayout.CENTER);
              JSplitPane splRight = new JSplitPane();
              splRight.setContinuousLayout(true);
              splRight.setDividerSize(10);
              splRight.setOneTouchExpandable(true);
              splRight.setOrientation(JSplitPane.VERTICAL_SPLIT);
              splAll.setRightComponent(splRight);
              JPanel pnlRightUp = new JPanel();
              splRight.setLeftComponent(pnlRightUp);
              GridBagLayout gbl_pnlRightUp = new GridBagLayout();
              gbl_pnlRightUp.columnWidths = new int[]{36, 54, 227, 88, 88, 211, 0};
              gbl_pnlRightUp.rowHeights = new int[]{23, 363, 0};
              gbl_pnlRightUp.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
              gbl_pnlRightUp.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
              pnlRightUp.setLayout(gbl_pnlRightUp);
              JLabel label = new JLabel("\u5F53\u524D\u6709");
              GridBagConstraints gbc_label = new GridBagConstraints();
              gbc_label.anchor = GridBagConstraints.WEST;
              gbc_label.insets = new Insets(0, 0, 5, 5);
              gbc_label.gridx = 0;
              gbc_label.gridy = 0;
              pnlRightUp.add(label, gbc_label);
              JLabel lblCount = new JLabel("New label");
              lblCount.setForeground(Color.BLUE);
              GridBagConstraints gbc_lblCount = new GridBagConstraints();
              gbc_lblCount.anchor = GridBagConstraints.WEST;
              gbc_lblCount.insets = new Insets(0, 0, 5, 5);
              gbc_lblCount.gridx = 1;
              gbc_lblCount.gridy = 0;
              pnlRightUp.add(lblCount, gbc_lblCount);
              JComboBox tfKey = new JComboBox();
              GridBagConstraints gbc_tfKey = new GridBagConstraints();
              gbc_tfKey.fill = GridBagConstraints.HORIZONTAL;
              gbc_tfKey.insets = new Insets(0, 0, 5, 5);
              gbc_tfKey.gridx = 2;
              gbc_tfKey.gridy = 0;
              pnlRightUp.add(tfKey, gbc_tfKey);
              JLabel label_1 = new JLabel("\u6761");
              GridBagConstraints gbc_label_1 = new GridBagConstraints();
              gbc_label_1.anchor = GridBagConstraints.WEST;
              gbc_label_1.insets = new Insets(0, 0, 5, 5);
              gbc_label_1.gridx = 2;
              gbc_label_1.gridy = 0;
              pnlRightUp.add(label_1, gbc_label_1);
              JButton btnSearch = new JButton("\u641C\u7D22");
              GridBagConstraints gbc_btnSearch = new GridBagConstraints();
              gbc_btnSearch.anchor = GridBagConstraints.NORTH;
              gbc_btnSearch.fill = GridBagConstraints.HORIZONTAL;
              gbc_btnSearch.insets = new Insets(0, 0, 5, 5);
              gbc_btnSearch.gridx = 3;
              gbc_btnSearch.gridy = 0;
              pnlRightUp.add(btnSearch, gbc_btnSearch);
              JButton btnType = new JButton("\u7C7B\u522B\u7EF4\u62A4");
              GridBagConstraints gbc_btnType = new GridBagConstraints();
              gbc_btnType.anchor = GridBagConstraints.NORTH;
              gbc_btnType.fill = GridBagConstraints.HORIZONTAL;
              gbc_btnType.insets = new Insets(0, 0, 5, 5);
              gbc_btnType.gridx = 4;
              gbc_btnType.gridy = 0;
              pnlRightUp.add(btnType, gbc_btnType);
              JButton button_2 = new JButton("\u91CD\u65B0\u6253\u5F00\u7A97\u53E3");
              GridBagConstraints gbc_button_2 = new GridBagConstraints();
              gbc_button_2.anchor = GridBagConstraints.NORTHWEST;
              gbc_button_2.insets = new Insets(0, 0, 5, 0);
              gbc_button_2.gridx = 5;
              gbc_button_2.gridy = 0;
              pnlRightUp.add(button_2, gbc_button_2);
              JScrollPane spData = new JScrollPane();
              GridBagConstraints gbc_spData = new GridBagConstraints();
              gbc_spData.fill = GridBagConstraints.BOTH;
              gbc_spData.gridwidth = 6;
              gbc_spData.gridx = 0;
              gbc_spData.gridy = 1;
              gbc_spData.weightx=1;
              gbc_spData.weighty=1;
              pnlRightUp.add(spData, gbc_spData);
              table = new JTable();
              spData.setViewportView(table);
              JScrollPane scrollPane = new JScrollPane();
              splRight.setRightComponent(scrollPane);
              JTextArea taContent = new JTextArea();
              scrollPane.setViewportView(taContent);
              splRight.setDividerLocation(400);
              JScrollPane scrollPane_1 = new JScrollPane();
              splAll.setLeftComponent(scrollPane_1);
              JList lstType = new JList();
              scrollPane_1.setViewportView(lstType);
              splAll.setDividerLocation(180);
         public static void  createWin(){
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             try {
                               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                           } catch (ClassNotFoundException e) {
                               e.printStackTrace();
                           } catch (InstantiationException e) {
                               e.printStackTrace();
                           } catch (IllegalAccessException e) {
                               e.printStackTrace();
                           } catch (UnsupportedLookAndFeelException e) {
                               e.printStackTrace();
                             FrmMain frame = new FrmMain();
                             frame.setVisible(true);
                        } catch (Exception e) {
                             e.printStackTrace();
    }thanks.

    I found the reason. the code below defines the jtable height as 363 pixels,so the divider couldn't make the upper part less than 363 pixels. I don't know why divider cound't but draging win could. Gridbaglayout is so complex.
    gbl_pnlRightUp.rowHeights = new int[]{23, 363, 0};if I use BorderLayout and put jtable into center in the upper part of splitpane, everything is ok. But if I had to use gridbaglayout,what was I gonna do?

  • Calculator square root event listener

    I am trying to write a calculator using JButtons added onto Jpanels. Getting numbers to add , divide, multilpy etc. is simple enough, but i need to write an event handler for a button which calculates the square root of a given number. This is easy enough if you want the square root of 4,9,16,25 etc but if you enter a number which produces a decimal point value it doesn't work.
    I am trying to do this using a variable "number" which is of type double, but have tried using it as a float, but it still doesn't work! here is my code for handling a click on the Square root JButton.
         if(e.getActionCommand().equals("Sqrt")){
         number = new Double(jtf.getText().trim()).doubleValue();
         double rootNum = 1.000;
         while(rootNum*rootNum <= number){
              double rootTester = rootNum * rootNum;
              if(rootTester == number){
                   jtf.setText(String.valueOf(rootNum));
    rootNum = rootNum+1;

    How about
    double answer = Math.sqrt(number);

  • 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

  • Help with Layout

    I've got a simple layout but I need to get it looking more like this picture: http://members.lycos.nl/ghanswebsite/Layout.JPG
    Now I got a simple GridBag. I tried a few other layouts but they got me errors so until now I evaded them .. :-(.
    // Fig. 12.26: GridLayoutDemo.java
    // Demonstrating GridLayout.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.Color.*;
    public class GridLayoutDemo extends JFrame implements ActionListener {
         private boolean toggle = true;
         private Container c;
         private GridLayout grid1;
         private JButton zoek;
         private Connection connection;
         private JTextField vDag, aDatum, vTijd, aTijd, vlucht;
         Statement opdracht = null;
        boolean inAnApplet = true;
        final boolean shouldFill = true;
        final boolean shouldWeightX = true;
         Color myPink1 = new Color(254,224,192);
        private JComboBox vertrek, naar, vdag, vmaand, volwassenen, kinderen, babys;
         // vertrekdag
         private String dag[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18","19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
         // vetrekmaand+jaar
         private String maand[] = { "April 2003" , "Mei 2003"};
         // volwassenen
         private String volwassen[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
         // kinderen
         private String kind[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
         // baby's.
         private String baby[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
         //vetrekplaatsen-combobox
         private String vPlaatsen[] = { "Amsterdam", "Rotterdam" };
         private String[] plaats = null;
         // aangeven wat in het combobox van Rotterdam mag staan
         private String raPlaatsen[] = { "Alicante", "Faro" };
         // aangeven wat in het combobox van Amsterdam
         private String aaPlaatsen[] = { "Bacelona", "Antalya", "Arrecife", "Alicante", "Bodrun" };
         //thread-safe gui changing with swingUtilities.invokeLater( Runnable )
         private Runnable run = new Runnable(){
         public void run(){
              getContentPane().invalidate();
              getContentPane().removeAll();
              getContentPane().add(vertrek);
              getContentPane().add(naar = new JComboBox( plaats ));
              getContentPane().add(vdag);
              getContentPane().add(vmaand);
              getContentPane().add(volwassenen);
              getContentPane().add(kinderen);
              getContentPane().add(babys);
              getContentPane().add(zoek);
              getContentPane().add(vDag);
              getContentPane().add(aDatum);
              getContentPane().add(vTijd);
              getContentPane().add(aTijd);
              getContentPane().add(vlucht);
              getContentPane().validate();
       public GridLayoutDemo()
         super( "GridLayout Demo" );
              // The URL specifying the Books database to which
                // this program connects using JDBC to connect to a
                // Microsoft ODBC database.
                String url = "jdbc:odbc:vluchtinformatie";
                // Load the driver to allow connection to the database
                try {
                   Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
                   connection = DriverManager.getConnection( url );
                     opdracht = connection.createStatement();
                catch ( ClassNotFoundException cnfex ) {
                   System.err.println(
                      "Failed to load JDBC/ODBC driver." );
                   cnfex.printStackTrace();
                   System.exit( 1 );  // terminate program
                catch ( SQLException sqlex ) {
                   System.err.println( "Unable to connect" );
                   sqlex.printStackTrace();
                   System.exit( 1 );  // terminate program
        grid1 = new GridLayout( 4, 3, 10, 10 );
         Container c = getContentPane();
         c.setLayout( grid1 );
         setSize(500,200);
         vertrek = new JComboBox(vPlaatsen);
         vertrek.setName("vertrek");
         vertrek.setMaximumRowCount(2);
         vertrek.addActionListener( this );
         c.add(vertrek);
        show();
         vdag = new JComboBox(dag);
         vdag.setName("dag");
         vdag.setMaximumRowCount(5);
         vdag.addActionListener( this );
         c.add(vdag);
         show();
         vmaand = new JComboBox(maand);
         vmaand.setName("maand");
         vmaand.setMaximumRowCount(5);
         vmaand.addActionListener( this );
         c.add(vmaand);
         show();
         volwassenen = new JComboBox(volwassen);
         volwassenen.setName("volwassen");
         volwassenen.setMaximumRowCount(5);
         volwassenen.addActionListener( this );
         c.add(volwassenen);
         show();
         kinderen = new JComboBox(kind);
         kinderen.setName("kind");
         kinderen.setMaximumRowCount(5);
         kinderen.addActionListener( this );
         c.add(kinderen);
         show();
         babys = new JComboBox(baby);
         babys.setName("baby");
         babys.setMaximumRowCount(5);
         babys.addActionListener( this );
         c.add(babys);
         show();
         zoek = new JButton( "Zoek vlucht" );
         zoek.addActionListener( this );
         c.add(zoek);
         show();
         vDag = new JTextField( "Vertrekdatum" );
         c.add(vDag);
         show();
         aDatum = new JTextField( "Aankomstdatum" );
         c.add(aDatum);
         show();
         vTijd = new JTextField( "Vertrektijd" );
         c.add(vTijd);
         show();
         aTijd = new JTextField( "Aankomsttijd" );
         c.add(aTijd);
         show();
         vlucht = new JTextField("Vluchtnummer" );
         c.add(vlucht);
         show();
    public void actionPerformed(ActionEvent e)     {
       Object source = e.getSource();
            if (source instanceof JComboBox)
                 JComboBox combo = (JComboBox) source;
                 if (combo.getName().equals("vertrek"))
                      if (((String) combo.getSelectedItem()).equals(vPlaatsen[0]))
                           plaats = aaPlaatsen;
                           SwingUtilities.invokeLater( run );
                           else if (((String) combo.getSelectedItem()).equals(vPlaatsen[1]))
                                plaats = raPlaatsen;
                                SwingUtilities.invokeLater( run );
       Object source1 = e.getSource();
            if (source1 instanceof JComboBox)
                 JComboBox combo1 = (JComboBox) source1;
                 if (combo1.getName().equals("vertrek"))
                      if (((String) combo1.getSelectedItem()).equals(vPlaatsen[0]))
                        String gebruikersVertrekplaats = "Amsterdam";
                           else if (((String) combo1.getSelectedItem()).equals(vPlaatsen[1]))
                        String gebruikersVertrekplaats = "Rotterdam";
                      try
                        ResultSet gegevens;
                        gegevens = opdracht.executeQuery("SELECT * FROM vluchtinformatie WHERE vertrekplaats LIKE '"+ gebruikersVertrekplaats +"' AND aankomstplaats LIKE '"+gebruikersAankomstplaats+"';");
                   catch (Exception e)
                        e.printStackTrace();
       public static void main( String args[] )
                      try {
                            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
                     catch (Exception e) { }
          GridLayoutDemo app = new GridLayoutDemo();
          app.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                   System.exit( 0 );
    }

    When asking about layout (or any question about how a site works or looks), give us a link to the site. Read the Forum FAQ about it and the reasons why.
    I will say that a quick look indicates that you have gone overboard with Divs--66 of them (!). And most serve no purpose. The point of a Div is to hold a bunch of stuff to make it easy to control them. Divs with only one item in them make no sense. And divs
    that are always paired should be combined into one div (if they are even necessary at all).
    Why isn't this one div? These 3 always appear exactly like this:
     <div class="category">
         <div class="categoryheader">
           <h3>Services</h3>
         </div>
         <div class="categorycontent">
    A horse walks into a bar. The bartender asks "Why the long face?"
    "Because I was born into servitude and when I die my hooves will be used to make glue."
    It was at this point that the bartender realized he would not be getting a tip.

  • HELP PLEASE - WHATS WRONG WITH THIS CODE

    Hi. I get this message coming up when I try to compile the code,
    run:
    java.lang.NullPointerException
    at sumcalculator.SumNumbers.<init>(SumNumbers.java:34)
    at sumcalculator.SumNumbers.main(SumNumbers.java:93)
    Exception in thread "main"
    Java Result: 1
    BUILD SUCCESSFUL (total time: 2 seconds)
    I am not sure whats wrong with the code. Any assistance would be nice. The code is below.
    package sumcalculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SumNumbers extends JFrame implements FocusListener {
    JTextField value1;
    JTextField value2;
    JLabel equals;
    JTextField sum;
    JButton add;
    JButton minus;
    JButton divide;
    JButton multiply;
    JLabel operation;
    public SumNumbers() {
    SumNumbersLayout customLayout = new SumNumbersLayout();
    getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
    getContentPane().setLayout(customLayout);
    value1.addFocusListener(this);
    value2.addFocusListener(this);
    sum.setEditable(true);
    value1 = new JTextField("");
    getContentPane().add(value1);
    value2 = new JTextField("");
    getContentPane().add(value2);
    equals = new JLabel("label_1");
    getContentPane().add(equals);
    sum = new JTextField("");
    getContentPane().add(sum);
    add = new JButton("+");
    getContentPane().add(add);
    minus = new JButton("-");
    getContentPane().add(minus);
    divide = new JButton("/");
    getContentPane().add(divide);
    multiply = new JButton("*");
    getContentPane().add(multiply);
    operation = new JLabel();
    getContentPane().add(operation);
    setSize(getPreferredSize());
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void focusGained(FocusEvent event){
    try {
    float total = Float.parseFloat(value1.getText()) +
    Float.parseFloat(value2.getText());
    sum.setText("" + total);
    } catch (NumberFormatException nfe) {
    value1.setText("0");
    value2.setText("0");
    sum.setText("0");
    public void focusLost(FocusEvent event){
    focusGained(event);
    public static void main(String args[]) {
    SumNumbers window = new SumNumbers();
    window.setTitle("SumNumbers");
    window.pack();
    window.show();
    class SumNumbersLayout implements LayoutManager {
    public SumNumbersLayout() {
    public void addLayoutComponent(String name, Component comp) {
    public void removeLayoutComponent(Component comp) {
    public Dimension preferredLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    Insets insets = parent.getInsets();
    dim.width = 711 + insets.left + insets.right;
    dim.height = 240 + insets.top + insets.bottom;
    return dim;
    public Dimension minimumLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    return dim;
    public void layoutContainer(Container parent) {
    Insets insets = parent.getInsets();
    Component c;
    c = parent.getComponent(0);
    if (c.isVisible()) {c.setBounds(insets.left+24,insets.top+48,128,40);}
    c = parent.getComponent(1);
    if (c.isVisible()) {c.setBounds(insets.left+256,insets.top+48,128,40);}
    c = parent.getComponent(2);
    if (c.isVisible()) {c.setBounds(insets.left+408,insets.top+48,56,40);}
    c = parent.getComponent(3);
    if (c.isVisible()) {c.setBounds(insets.left+488,insets.top+48,152,40);}
    c = parent.getComponent(4);
    if (c.isVisible()) {c.setBounds(insets.left+128,insets.top+136,72,40);}
    c = parent.getComponent(5);
    if (c.isVisible()) {c.setBounds(insets.left+248,insets.top+136,72,40);}
    c = parent.getComponent(6);
    if (c.isVisible()) {c.setBounds(insets.left+368,insets.top+136,72,40);}
    c = parent.getComponent(7);
    if (c.isVisible()) {c.setBounds(insets.left+488,insets.top+136,72,40);}
    c = parent.getComponent(8);
    if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+48,56,40);}
    }

    Thank you. How do i amend this? I have defined value1though.Yes, you did - but after the call to addFocusListener(...). It needs to be before it.
    BTW, you did the same thing with "value2.addFocusListener(this)" and "sum.setEditable(true)" on the next two lines. You're attempting to call a method on an object that doesn't exist yet (i.e., you haven't called new yet).

  • Trying to make a WrappingComboBox

    Inspired by a fairly straightforward WrappingList, I thought I'd try to make a Wrapping JScrollPane. The goal is a ScrollPane that automatically wraps the text inside it. I've just about got it, but I have one thing that's not working. If I just put the JTextArea{s} in as the Editor, then you lose the any text that doesn't fit inside whatever the initial size was. Instead, I put the JTextAreas inside a JScrollPane which works fine, except that I still have to determine the size of the JScrollPane in advance. I would like to make each Editor/JScrollPane start out with just a single line of text and expand until it reaches a certain small number of lines.
    Here is my attempt at a WrappingComboBox
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.LayoutManager;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.InputMethodEvent;
    import java.awt.event.InputMethodListener;
    import java.util.Vector;
    import javax.swing.BoxLayout;
    import javax.swing.ComboBoxEditor;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JViewport;
    import javax.swing.ListCellRenderer;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    import javax.swing.event.EventListenerList;
    import javax.swing.plaf.basic.BasicComboBoxUI;
    import javax.swing.plaf.basic.BasicComboPopup;
    import javax.swing.plaf.basic.ComboPopup;
    import javax.swing.text.View;
    import debibdup.ScrollablePanel.ScrollableSizeHint;
    * @author jfolson
    public class WrappingComboBox extends JComboBox {
         WrappingComboBox() {
              super();
              this.setUI(new WrappingComboBoxUI());
         WrappingComboBox(Vector<?> items) {
              super(items);
              this.setUI(new WrappingComboBoxUI());
         public static class WrappingComboBoxUI extends BasicComboBoxUI {
              WrappingHelper wrappingHelper;
              public WrappingComboBoxUI() {
                   super();
              public WrappingHelper getWrappingHelper() {
                   if (wrappingHelper == null)
                        wrappingHelper = new WrappingHelper();
                   return wrappingHelper;
              /* Since my Editor, Renderer and Popup are not UIResources, I have to overload these methods
               * or else installUI would call BasicComboBoxUI.createXXX anyway and replace mine
              @Override
              protected ComboBoxEditor createEditor() {
                   return new WrappingComboBoxEditor();
              /* See note for createEditor()
              @Override
              protected ListCellRenderer createRenderer() {
                   return new WrappingList.WrappingListCellRenderer();
              /* See note for createEditor()
              @Override
              protected ComboPopup createPopup() {
                   return new BasicComboPopup(comboBox) {
                        @Override
                        protected JList createList() {
                             // use the WrappingList for the popup to make it update its
                             // sizes
                             return new WrappingList(comboBox.getModel());
                             // BasicComboPopup overrides default, apparently fixes some
                             // bug but I can't use it because BasicGraphicsUtils
                             // functions are private
                             /*return new JList(comboBox.getModel()) {
                                  @Override
                                  public void processMouseEvent(MouseEvent e) {
                                       if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
                                            // Fix for 4234053. Filter out the Control Key
                                            // from the list.
                                            // ie., don't allow CTRL key deselection.
                                            Toolkit toolkit = Toolkit.getDefaultToolkit();
                                            e = new MouseEvent((Component) e.getSource(), e
                                                      .getID(), e.getWhen(), e.getModifiers()
                                                      ^ toolkit.getMenuShortcutKeyMask(), e
                                                      .getX(), e.getY(), e.getXOnScreen(), e
                                                      .getYOnScreen(), e.getClickCount(), e
                                                      .isPopupTrigger(), MouseEvent.NOBUTTON);
                                       super.processMouseEvent(e);
              /*Have to overrige getMinimumSize, rectangleForCurrentValue and layoutContainer in the Helper class
               * to make a smaller (reasonable) sized popup button, otherwise, for multi-line combobox you get
               *  ridiculously large buttons.
              @Override
              public Dimension getMinimumSize(JComponent c) {
                   if (!isMinimumSizeDirty) {
                        return new Dimension(cachedMinimumSize);
                   Dimension size = getDisplaySize();
                   Insets insets = getInsets();
                   // calculate the width and height of the button
                   int buttonHeight = size.height;
                   if (buttonHeight > arrowButton.getPreferredSize().width)
                        buttonHeight = arrowButton.getPreferredSize().width;
                   int buttonWidth = arrowButton.getPreferredSize().width;
                   // adjust the size based on the button width
                   size.height += insets.top + insets.bottom;
                   size.width += insets.left + insets.right + buttonWidth;
                   cachedMinimumSize.setSize(size.width, size.height);
                   isMinimumSizeDirty = false;
                   return new Dimension(size);
               * Returns the area that is reserved for drawing the currently selected
               * item.
              @Override
              protected Rectangle rectangleForCurrentValue() {
                   int width = comboBox.getWidth();
                   int height = comboBox.getHeight();
                   Insets insets = getInsets();
                   int buttonSize = height - (insets.top + insets.bottom);
                   if (arrowButton != null) {
                        buttonSize = arrowButton.getWidth();
                   if (true) {// BasicGraphicsUtils.isLeftToRight(comboBox)) { // this
                        // method is not visible
                        return new Rectangle(insets.left, insets.top, width
                                  - (insets.left + insets.right + buttonSize), height
                                  - (insets.top + insets.bottom));
                   } else { // if I could tell, put the box on the other side for right
                        // to left checkboxes
                        return new Rectangle(insets.left + buttonSize, insets.top,
                                  width - (insets.left + insets.right + buttonSize),
                                  height - (insets.top + insets.bottom));
              @Override
              protected LayoutManager createLayoutManager() {
                   return getWrappingHelper();
              private class WrappingHelper implements LayoutManager {
                   // LayoutManager
                   /* Need to override layoutContainer to put in a smaller popup button
                   public void addLayoutComponent(String name, Component comp) {} // Can't
                   // do
                   // this
                   public void removeLayoutComponent(Component comp) {}
                   public Dimension preferredLayoutSize(Container parent) {
                        return parent.getPreferredSize();
                   public Dimension minimumLayoutSize(Container parent) {
                        return parent.getMinimumSize();
                   public void layoutContainer(Container parent) {
                        JComboBox cb = (JComboBox) parent;
                        int width = cb.getWidth();
                        int height = cb.getHeight();
                        Insets insets = getInsets();
                        int buttonHeight = height - (insets.top + insets.bottom);
                        int buttonWidth = buttonHeight;
                        if (arrowButton != null) {
                             if (buttonHeight > arrowButton.getPreferredSize().width)
                                  buttonHeight = arrowButton.getPreferredSize().width;
                             Insets arrowInsets = arrowButton.getInsets();
                             buttonWidth = arrowButton.getPreferredSize().width
                                       + arrowInsets.left + arrowInsets.right;
                        Rectangle cvb;
                        if (arrowButton != null) {
                             if (true) {// BasicGraphicsUtils.isLeftToRight(cb)) { //
                                  // this method is not visible
                                  arrowButton.setBounds(width
                                            - (insets.right + buttonWidth), insets.top,
                                            buttonWidth, buttonHeight);
                             } else { // if I could tell, put the box on the other side
                                  // for right to left checkboxes
                                  arrowButton.setBounds(insets.left, insets.top,
                                            buttonWidth, buttonHeight);
                        if (editor != null) {
                             cvb = rectangleForCurrentValue();
                             editor.setBounds(cvb);
         public static class WrappingComboBoxEditor extends JScrollPane implements
                   ComboBoxEditor, ComponentListener {
              EventListenerList listenerList = new EventListenerList();
              LineAwareTextArea text;
              public WrappingComboBoxEditor() {
                   super();
                   this.text = new LineAwareTextArea();
                   this.setViewportView(text);
                   setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                   setPreferredSize(new Dimension(100, 30));
                   this.setItem("");
                   text.setLineWrap(true);
                   text.setWrapStyleWord(false);
                   text.setEditable(true);
                   text.addInputMethodListener(new InputMethodListener() {
                        @Override
                        public void caretPositionChanged(InputMethodEvent arg0) {}
                        @Override
                        public void inputMethodTextChanged(InputMethodEvent arg0) {
                             Object[] listeners = WrappingComboBoxEditor.this.listenerList
                                       .getListenerList();
                             // Process the listeners last to first, notifying
                             // those that are interested in this event
                             ActionEvent actionEvent = null;
                             for (int i = listeners.length - 2; i >= 0; i -= 2) {
                                  if (listeners[i] == ActionListener.class) {
                                       if (actionEvent == null)
                                            actionEvent = new ActionEvent(this,
                                                      ActionEvent.ACTION_PERFORMED, null);
                                       ((ActionListener) listeners[i + 1])
                                                 .actionPerformed(actionEvent);
                   text.addComponentListener(this);
              @Override
              public void addActionListener(ActionListener l) {
                   listenerList.add(ActionListener.class, l);
              @Override
              public Component getEditorComponent() {
                   return this;
              @Override
              public Object getItem() {
                   return text.getText();
              @Override
              public void removeActionListener(ActionListener l) {
                   listenerList.remove(ActionListener.class, l);
              @Override
              public void setItem(Object anObject) {
                   if (anObject == null)
                        text.setText("");
                   else
                        text.setText(String.valueOf(anObject));
              @Override
              public void selectAll() {
                   text.selectAll();
              public void componentHidden(ComponentEvent arg0) {}
              public void componentMoved(ComponentEvent arg0) {}
              @Override
              public void componentResized(ComponentEvent arg0) {
                   JViewport view = this.getViewport();
                   Dimension viewDim = view.getExtentSize();
                   Insets insets = view.getInsets();
                   System.out.println("actual view height: " + viewDim.height);
                   Dimension wantDim = text.getPreferredScrollableViewportSize();
                   if (wantDim.height > viewDim.height) {
                        viewDim.height = wantDim.height + insets.top + insets.bottom;
                        view.setPreferredSize(viewDim);
                        view.revalidate();
                        ((JComponent) this.getParent()).revalidate();
                        //SwingUtilities.windowForComponent(this).pack(); //even this doesn't work
              @Override
              public void componentShown(ComponentEvent arg0) {}
          * Only really need to expose rowHeight but might as well determine the
          * correct size it wants its viewport
          * @author jfolson
         public static class LineAwareTextArea extends JTextArea {
              private int maxVisibleRows = 3;
              public LineAwareTextArea() {
                   super();
              public LineAwareTextArea(String text) {
                   this();
                   setText(text);
              @Override
              public Dimension getPreferredScrollableViewportSize() {
                   Dimension d = this.getPreferredSize();
                   float hspan = getWidth();
                   View view = (getUI()).getRootView(this);
                   view.setSize(hspan, Float.MAX_VALUE);
                   float vspan = view.getPreferredSpan(View.Y_AXIS);
                   Insets insets = getInsets();
                   int rows = (d.height / this.getRowHeight());
                   if (rows > maxVisibleRows)
                        rows = maxVisibleRows;
                   d.height = rows * getRowHeight() + insets.top + insets.bottom;
                   System.out.println("prefer view height: " + d.height + " (" + rows
                             + " line(s))");  // this is here just so I can see that it's getting the right number of desired lines.
                   return d;
              public void setMaxVisibleRows(int rows) {
                   this.maxVisibleRows = rows;
              public int getMaxVisibleRows() {
                   return this.maxVisibleRows;
         public static class ComboTest extends JFrame {
              public ComboTest() {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   init();
                   pack();
                   show();
              private void init() {
                   ScrollablePanel mainPanel = new ScrollablePanel();
                   mainPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
                   ScrollablePanel fieldPanel = new ScrollablePanel();
                   fieldPanel.setLayout(new BoxLayout(fieldPanel, BoxLayout.X_AXIS));
                   fieldPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   Vector<String> items = new Vector<String>();
                   items.add("Item One");
                   JComboBox list = new WrappingComboBox(items);
                   list.setEditable(true);
                   JLabel fieldLabel = new JLabel("Label: ");
                   fieldLabel.setAlignmentY(TOP_ALIGNMENT);
                   list.setAlignmentY(TOP_ALIGNMENT);
                   fieldPanel.add(fieldLabel);
                   fieldPanel.add(list);
                   mainPanel.add(fieldPanel);
                   fieldPanel = new ScrollablePanel();
                   fieldPanel.setLayout(new BoxLayout(fieldPanel, BoxLayout.X_AXIS));
                   fieldPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   items
                             .add("Item Two content content content content Item Two content content content content Item Two content content content content Item Two content content content content");
                   list = new WrappingComboBox(items);
                   list.setEditable(true);
                   fieldLabel = new JLabel("Label: ");
                   fieldLabel.setAlignmentY(TOP_ALIGNMENT);
                   list.setAlignmentY(TOP_ALIGNMENT);
                   fieldPanel.add(fieldLabel);
                   fieldPanel.add(list);
                   mainPanel.add(fieldPanel);
                   JScrollPane mainScrolls = new JScrollPane(mainPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   mainScrolls.setPreferredSize(new Dimension(200, 200));
                   setContentPane(mainScrolls);
         public static void main(String[] args) {
              new ComboTest();
    }And here is the WrappingList that it references
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.plaf.basic.BasicListUI;
    import javax.swing.text.View;
    * List that wraps its text! Whenever the list's layout (e.g. size) changes the
    * list's UI is instructed to update its layout too.
    public class WrappingList extends JList {
         public WrappingList() {
              setUI(new WrappingListUI());
              setCellRenderer(new WrappingListCellRenderer());
         public WrappingList(ListModel model) {
              super(model);
              setUI(new WrappingListUI());
              setCellRenderer(new WrappingListCellRenderer());
         @Override
         public void doLayout() {
              ((WrappingListUI) getUI()).updateLayoutState();
              super.doLayout();
         @Override
         public boolean getScrollableTracksViewportWidth() {
              return true;
          * ListUI implementation that exposes the method for updating its layout
         private static class WrappingListUI extends BasicListUI {
              @Override
              public void updateLayoutState() {
                   super.updateLayoutState();
          * List cell renderer that uses the list's width to alter its preferred size
          * TODO - override bound properties in the same way as
          * DefaultListCellRenderer
         public static class WrappingListCellRenderer extends JTextPane implements
                   ListCellRenderer {
              public WrappingListCellRenderer() {
                   setBorder(new EmptyBorder(1, 1, 1, 1));
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean selected, boolean hasFocus) {
                   setBackground(selected ? list.getSelectionBackground() : list
                             .getBackground());
                   setForeground(selected ? list.getSelectionForeground() : list
                             .getForeground());
                   // TODO - border, font etc.
                   setText(String.valueOf(value));
                   float hspan = list.getWidth();
                   View view = (getUI()).getRootView(this);
                   view.setSize(hspan, Float.MAX_VALUE);
                   float vspan = view.getPreferredSpan(View.Y_AXIS);
                   Insets insets = getInsets();
                   setPreferredSize(new Dimension(insets.left + insets.right
                             + (int) hspan, insets.top + insets.bottom + (int) vspan));
                   return this;
         public static void main(String[] args) {
              new Test();
         public static class Test extends JFrame {
              public Test() {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   init();
                   pack();
                   show();
              private void init() {
                   JList list = new WrappingList();
                   list
                             .setListData(new Object[] {
                                       "Item One",
                                       "Item Two content content content content Item Two content content content content Item Two content content content content Item Two content content content content" });
                   setContentPane(new JScrollPane(list,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    }You can verify (in System.out) that the preferred size is larger than the actual default size once you switch to the longer value in the combo box, but the actual size doesn't change. I've tried setSize, setMinimumSize, nothing makes the JScrollPane/Editor any larger. I've also tried calling and not calling various combinations of revalidate(), getParent().revalidate() and getViewport().revalidate(). What am I missing?
    Edited by: inspired2apathy on Oct 16, 2010 7:22 PM

    inspired2apathy wrote:
    ... The goal is a ScrollPane that automatically wraps the text inside it. I've just about got it, but I have one thing that's not working. If I just put the JTextArea{s} in as the Editor, then you lose the any text that doesn't fit inside whatever the initial size was. Instead, I put the JTextAreas inside a JScrollPane which works fine, except that I still have to determine the size of the JScrollPane in advance. I would like to make each Editor/JScrollPane start out with just a single line of text and expand until it reaches a certain small number of lines.
    ... What am I missing?THE BASICS. See if this isn't what you are trying to do.
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Test
      public static void main(String[] args) {
        JTextArea ta = new JTextArea();
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        JScrollPane sp = new JScrollPane(ta);
        JFrame f = new JFrame();
        f.getContentPane().add(sp, "Center");
        f.setBounds(0, 0, 400, 300);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        f.setVisible(true); 
    }OP, your code was too long and complicated for me to compile and run. However, aren't you forgetting the two simple methods <tt>JTextArea.setLineWrap()</tt> and <tt>JTextArea.setWrapStyleWord()</tt>? Furthermore, I absolutely see no need for you to extend SWING components for demonstration this simple -- that is, if I understand your problem correctly.

Maybe you are looking for