Panel in swing

i want to display all the forms in a project within the same panel while clicking appropriate button

Start here: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/]

Similar Messages

  • Nested panels in Swing

    Hi, everyone
    i want to know about nested panels in detail. If we make heirarchy of panels at third level then how we can perform drawing in uppermost(last child). please suggest me ideas and give links that gives sufficient matter about it.
    Thanks in advance.
    Rakesh Ojha

    Hello DB sir
    thanks for gentle reply
    i m not getting the website address from your message on which layout managers are discussed in tutorial. If you mean sun.com then please tell me.
    Thanks
    Rakesh Ojha

  • Controlling Of Panels In Swing

    Hi,.. i have two jpanels in same frame i have divided the panels as left frame and right frame so when i click
    a component for example a button in left frame a GUI should appear on right frame and when i click another component
    in left frame the earlier GUI should disappear and new GUI with other components should appear i mean new panel on the right side shoud
    appear and the left Panel should be there itself how can i do that plz help...

    Dayananda B V wrote:
    you should go through the following linkThe question is ~5 months old and the OP never responded to the question asked - better focus on ACTIVE questions (which are 999/1000 times RECENT questions) if you don't want to waste your time. If you can't find one here, there are always dozens of questions to answer over on stackoverflow.

  • Updating different panels in Swing?

    I have a JTabbedPane with panel1, panel2, panel3
    and a JButton in panel1. I know I need to addActionListener, etc, but what code would change the display of panel3? (Let's say I just want to display a new JLabel there; ie "Button pressed")
    Thanks

    Use indexOftab(String) to get the tab index based on the caption of the tab you want.
    Use setSelectedIndex(String) to select the tab based on the index you specify.
    Use getSelectedComponent() to get the component from the selected tab, such as a JPanel. Then add a JLabel with the caption to this component.
    Look at: http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html for more info
    Hope this helps.
    Riz

  • Jmenuitem overlap with jchoice on a panel

    my jmenuitem ovelap with jchoice panel and look like the jmenuitem is at the back of the jchoice on a panel . is this a bug? how to overcome this?

    i think is because my jmenuitem and panel is swing component and my jchoice is awt component? can this be the reason? how to overcome this?

  • List of various line panels in a JPanel

    Hi,
    I'd like to code a panel which can contain various amounts of other panels which can be considered as "line elements". They consist of a JLable and JTextfield and are all of the same height.
    I'd like the main panel at a specified fixed size so I chosed a BoxLayout and Y-Axis and I've put it into a JScrollpane.
    Now real fun starts. When I have only two "line panels" in it, they will be streched to fit the size and when it contains more than the Scrollpane's viewport, the JScrollbars show up only if the panel's size is greater than the viewport. What happens if there are more line elements than the main panel can keep, I don't know.
    How can I solve this problem having a list of various line elements which keep their size and JScrollbars which show up if necessary? If there might be a better way to do that, please tell me!!!
    I wrote this demo-version (2 classes):
    The main class with frame and main panel:
    package gui;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.WindowConstants;
    public class PanOptions extends javax.swing.JPanel{
         private static final long serialVersionUID = 5833715021796955215L;
         private PanLine panLine1;
         private PanLine panLine2;
         private PanLine panLine7;
         private PanLine panLine6;
         private PanLine panLine5;
         private PanLine panLine4;
         private PanLine panLine3;
         private JScrollPane scrollPane;
         private JPanel panel;
         * Auto-generated main method to display this
         * JPanel inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new PanOptions());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
          * ctor.
         public PanOptions(){
              initGUI();
         private void initGUI() {
              panel = new JPanel();
              try {
                        this.setPreferredSize(new java.awt.Dimension(623, 140));
                   BoxLayout thisLayout = new BoxLayout( panel, javax.swing.BoxLayout.Y_AXIS);
                   panel.setLayout(thisLayout);
                        scrollPane = new JScrollPane();
                        this.add(scrollPane);
                        scrollPane.setViewportView( panel);
                             panLine1 = new PanLine();
                             panel.add(panLine1);
                             panLine2 = new PanLine();
                             panel.add(panLine2);
    //                    /* if the following part is commented the other two panels will be stretched?!
                             panLine3 = new PanLine();
                             panel.add(panLine3);
                             panLine4 = new PanLine();
                             panel.add(panLine4);
                             panLine5 = new PanLine();
                             panel.add(panLine5);
                             panLine6 = new PanLine();
                             panel.add(panLine6);
                             panLine7 = new PanLine();
                             panel.add(panLine7);
                        scrollPane.setSize(613, 140);
                        scrollPane.setPreferredSize(new java.awt.Dimension(613, 140));
              } catch (Exception e) {
                   e.printStackTrace();
    }The line element class:
    package gui;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    public class PanLine extends javax.swing.JPanel {
         private static final long serialVersionUID = 4932310577246348201L;
         private JLabel label;
         private JTextField tf;
          * Ctor
         public PanLine() {
              super();
              initGUI();
          * Inits GUI.
         private void initGUI() {
              try {
                   GridBagLayout thisLayout = new GridBagLayout();
                   thisLayout.rowWeights = new double[] {0.0,0.1};
                   thisLayout.rowHeights = new int[] {7,20};
                   thisLayout.columnWeights = new double[] {0.0,0.0,0.0,0.0,0.0};
                   thisLayout.columnWidths = new int[] {7,370,7,206,7};
                   this.setLayout(thisLayout);
                   this.setPreferredSize(new java.awt.Dimension(600, 27));
                        label = new JLabel();
                        this.add(label, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                        label.setText( "blablalba");
                        tf = new JTextField();
                        this.add(tf, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                        tf.setText( "blablalba");
              } catch (Exception e) {
                   e.printStackTrace();
    }

    Hi,
    I read thru the tuto and tried several things. I still have issues with the BoxLayout. For some strange reason glueing the excess space with Box.createVerticalGlue() doesn't work (at least I couldn't get it to work). So far I fixed the layout setting a maximum size for the line elements.
    To tell you the truth I don't really like this solution somehow - why does the glue not work in MY application? It seemed to be so easy in the tutorial and I can remember BoxLayout always having been nice to me?!
    This is just the modified main class, the elements are the same.. I'd like to get rid of having to set a max size for the element panels.
    package gui;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.WindowConstants;
    public class PanOptions01 extends javax.swing.JPanel{
         private static final long serialVersionUID = 5833715021796955215L;
         private PanLine panLine1;
         private PanLine panLine2;
         private PanLine panLine7;
         private PanLine panLine6;
         private PanLine panLine5;
         private PanLine panLine4;
         private PanLine panLine3;
         private JScrollPane scrollPane;
         private JPanel panel;
         * Auto-generated main method to display this
         * JPanel inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new PanOptions01());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
          * ctor.
         public PanOptions01(){
              initGUI();
         private void initGUI() {
              panel = new JPanel();
              try {
                        this.setPreferredSize(new java.awt.Dimension(623, 140));
                   BoxLayout thisLayout = new BoxLayout( panel, javax.swing.BoxLayout.Y_AXIS);
                   panel.setLayout(thisLayout);
                             panLine1 = new PanLine();
                             panel.add(panLine1);
    // it's only possible with lines like this:
                             panLine1.setMaximumSize(new java.awt.Dimension(610, 27));
                             panLine2 = new PanLine();
                             panel.add(panLine2);
    // it's only possible with lines like this:
                             panLine2.setMaximumSize(new java.awt.Dimension(610, 27));
                        /* if the following part is commented the other two panels will be stretched?!
                             panLine3 = new PanLine();
                             panel.add(panLine3);
                             panLine4 = new PanLine();
                             panel.add(panLine4);
                             panLine5 = new PanLine();
                             panel.add(panLine5);
                             panLine6 = new PanLine();
                             panel.add(panLine6);
                             panLine7 = new PanLine();
                             panel.add(panLine7);
    // this has rather no effect - why???
                        panel.add( Box.createVerticalGlue());
                        scrollPane = new JScrollPane();
                        this.add(scrollPane);
                        scrollPane.setSize(613, 140);
                        scrollPane.setPreferredSize(new java.awt.Dimension(613, 140));
                        scrollPane.setViewportView( panel);
                        panel.setPreferredSize(new java.awt.Dimension(610, 150));
              } catch (Exception e) {
                   e.printStackTrace();
    }

  • How do i parse data from the second jframe back to the first?

    Hello.
    I have a jFrame were I promt users to keep a list of Names in a jTable. (I keep data for something else, but lets say names.. ) Anyway, afterwords I want to add some extra parameters for each name. So I created a new frame, which is opened when user press an Edit button. The new frame opens and users can add for the specific name some extra data, like age, height, color, sex.. etc. that characterizes this person.
    On this second form i have a save button, which when its pressed i would like to keep this information for this name, so as when user press edit again from the first frame on the same Name the data that previously entered will be loaded (lets say that the user can not enter the say name again)
    I haven' t figured the code for the save Button, but with the rest I am fine.
    Can you give any ideas with structures that I have to use and how the action listener will have to be??
    When I set visible the new form i have made a constructor that loads the new form which have a label with the name of the person that is edited., but how do i parse data from the second form back to the first that is already opened??
    Thanks very much..

    I found it.. it was not so hard afterall..
    anyway, i quote the new code..
    package namelist;
    // Java core packages
    import java.awt.event.*;
    import java.util.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    public class NamesGUI extends javax.swing.JFrame {
        //Variables for managing the jTables
        DefaultTableModel tableModel;
        Vector rows,cols;
        String[] colName1 = {"List of Names"};
        ManageJTables mJT = new ManageJTables();
        Hashtable h;
        /** Creates new form ProsAgentGUI */
        public NamesGUI() {
            h = new Hashtable();
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            Panel = new javax.swing.JPanel();
            ToolBar = new javax.swing.JToolBar();
            ADD = new javax.swing.JButton();
            EDIT = new javax.swing.JButton();
            REMOVE = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();
            TScrollPane = new javax.swing.JScrollPane();
            Table = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Names");
            setBackground(new java.awt.Color(0, 51, 51));
            Panel.setBorder(javax.swing.BorderFactory.createTitledBorder("List of Names"));
            ToolBar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
            ADD.setText("ADD");
            ADD.setToolTipText("");
            ADD.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            ADD.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ADDActionPerformed(evt);
            ToolBar.add(ADD);
            EDIT.setText("EDIT");
            EDIT.setToolTipText("");
            EDIT.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            EDIT.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EDITActionPerformed(evt);
            ToolBar.add(EDIT);
            REMOVE.setText("REMOVE");
            REMOVE.setToolTipText("");
            REMOVE.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            REMOVE.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    REMOVEActionPerformed(evt);
            ToolBar.add(REMOVE);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            ToolBar.add(jButton1);
            rows=new Vector();
            cols= new Vector();
            cols=mJT.addColumns(colName1, cols);
            tableModel =new DefaultTableModel();
            tableModel.setDataVector(rows,cols);
            Table.setModel(tableModel);
            TScrollPane.setViewportView(Table);
            org.jdesktop.layout.GroupLayout PanelLayout = new org.jdesktop.layout.GroupLayout(Panel);
            Panel.setLayout(PanelLayout);
            PanelLayout.setHorizontalGroup(
                PanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(ToolBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                .add(TScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
            PanelLayout.setVerticalGroup(
                PanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(PanelLayout.createSequentialGroup()
                    .add(ToolBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(TScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE))
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(Panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(29, Short.MAX_VALUE)
                    .add(Panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            pack();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            System.out.println(h.toString());
    public void updateNamesTable (int id, String na){
         Integer i2 = new Integer(id);
         Object o2 = (Object)i2;
         if (h.containsKey(o2)){
            Name a = (Name)h.get(o2);
            a.name = na;
            h.put(o2,a);
         else {
             Name aa = new Name();
             aa.name=na;
             h.put(o2,(Object)aa);
        private void EDITActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            String name = Table.getValueAt(Table.getSelectedRow(),0).toString();
            int rowNum= Table.getSelectedRow();
            Integer i = new Integer(rowNum);
            Object o = (Object)i;
            updateNamesTable (rowNum, name);
            //public NameEditor(Name n,  Hashtable h, int id)
            NameEditor re = new NameEditor((Name)h.get(o), h, rowNum );
            re.setVisible(true);
        private void REMOVEActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            mJT.deleteRow(Table.getSelectedRow(), rows, Table);
        private void ADDActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            mJT.addRow(rows, Table);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NamesGUI().setVisible(true);
        // Variables declaration - do not modify
        javax.swing.JButton ADD;
        javax.swing.JButton EDIT;
        javax.swing.JPanel Panel;
        javax.swing.JButton REMOVE;
        javax.swing.JScrollPane TScrollPane;
        javax.swing.JTable Table;
        javax.swing.JToolBar ToolBar;
        javax.swing.JButton jButton1;
        // End of variables declaration
    public class NameEditor extends javax.swing.JFrame {
        Hashtable h;
        Name n;
        int id;
        /** Creates new form NameEditor */
        public NameEditor() {
            initComponents();
        public NameEditor(Name n,  Hashtable h, int id) {
            this.h=h;
            this.n=n;
            this.id=id;
            initComponents();
            NameField.setText(n.name);
            jTextField2.setText(n.weight);
            jTextField1.setText(n.height);
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            NameLabel = new javax.swing.JLabel();
            NameField = new javax.swing.JTextField();
            SaveBut = new javax.swing.JButton();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Name Editor");
            getAccessibleContext().setAccessibleName("Name Editor");
            NameLabel.setText("Name: ");
            NameField.setEditable(false);
            NameField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    NameFieldActionPerformed(evt);
            SaveBut.setText("SAVE");
            SaveBut.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    SaveButActionPerformed(evt);
            jLabel3.setText("Height");
            jLabel4.setText("Weight");
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(layout.createSequentialGroup()
                            .addContainerGap()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(layout.createSequentialGroup()
                                    .add(jLabel4)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(jLabel3)
                                        .add(NameLabel))
                                    .add(16, 16, 16)))
                            .add(17, 17, 17)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(NameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 138, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField2)
                                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE))))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(127, 127, 127)
                            .add(SaveBut)))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(NameLabel)
                        .add(NameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(30, 30, 30)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel3)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(12, 12, 12)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jLabel4)
                        .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 27, Short.MAX_VALUE)
                    .add(SaveBut)
                    .addContainerGap())
            pack();
        public void updateNameTable (){
         Integer i2 = new Integer(id);
         Object o2 = (Object)i2;
         h.put(o2,n);       
        private void SaveButActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
            n.height= jTextField1.getText();
            n.weight = jTextField2.getText();
        private void NameFieldActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NameEditor().setVisible(true);
        // Variables declaration - do not modify
        javax.swing.JTextField NameField;
        javax.swing.JLabel NameLabel;
        javax.swing.JButton SaveBut;
        javax.swing.JLabel jLabel3;
        javax.swing.JLabel jLabel4;
        javax.swing.JTextField jTextField1;
        javax.swing.JTextField jTextField2;
        // End of variables declaration
    }

  • How do I tak out the ink cartridge on HP Officejet Pro 8600?

    Need to remove my ink cartridge to buy a set backup.  How do you remove the old cartridge?

    The HP Office Pro 8600 series consists of 3 model variations. I have the Plus version. All functions similiar.
    With the power 'ON', grip the side of the front panel (left handed) just below the HP logo. The entire panel will swing down. The ink cartridge bay will move from the right to the left. Push on the cartridge, and it will pop-out.
    Manual, see pg 13 and 92.    WARNING per HP:    Never turn off the printer when ink cartridges are missing.
    I am a volunteer. I am not an HP employee.
    To say THANK YOU, press the "thumbs up symbol" to render a KUDO. Please click Accept as Solution, if your problem is solved. You can render both Solution and KUDO.
    The Law of Effect states that positive reinforcement increases the probability of a behavior being repeated. (B.F.Skinner). You toss me KUDO and/or Solution, and I perform better.
    (2) HP DV7t i7 3160QM 2.3Ghz 8GB
    HP m9200t E8400,Win7 Pro 32 bit. 4GB RAM, ASUS 550Ti 2GB, Rosewill 630W. 1T HD SATA 3Gb/s
    Custom Asus P8P67, I7-2600k, 16GB RAM, WIN7 Pro 64bit, EVGA GTX660 2GB, 750W OCZ, 1T HD SATA 6Gb/s
    Custom Asus P8Z77, I7-3770k, 16GB RAM, WIN7 Pro 64bit, EVGA GTX670 2GB, 750W OCZ, 1T HD SATA 6Gb/s
    Both Customs use Rosewill Blackhawk case.
    Printer -- HP OfficeJet Pro 8600 Plus

  • Positioning my objects

    how do you set the positioning of an object in java
    public class Panel extends JPanel{
    public void mymethod (int i){
    Graphics paper = this.getGraphics();
    paper.setColor(Color.black);
    Graphics hit = this.getGraphics();
    hit.setColor(Color.yellow);
    switch(i){
    case1:
    case2:
    public class Display extends JFrame{
    public static void main (String []args){
    Panel background = new Panel();
    Panel panel1 = new Panel(); ///////////////****************************
    Panel panel2 = new Panel(); ////////////////***********************************
    background.setPreferredSize(new Dimension(500, 200));
    MainWindow window = new MainWindow();
                    window.getContentPane().add(background);
    window.pack(); // Makes window display at proper size.
                    window.setVisible(true);
    }// main
    }I WANT TO ADD mypanel1 and mypanel2 to the background of Display which i have defined. But when i add it i want it to access the switch statment i.e panel1.mymethod(1); and panel2.mymehtod(2); and add this then put panel2 to the right 100 pixel of panel1
    I want to make instances of MyClass
    MyClass myclass1=new MyClass();
    MyClass myclass2=new MyClass();i then want to access the switch statment
    myclass1.mymehtod(1);
    myclass2.mymehtod(2);and i want to display these instances on a JPanel in another class which myclass1 should be on the left and myclass2 on the right 100 pixels away from the other.
    Please show any code

    surprise wrote:
    how do you set the positioning of an object in javaBefore you worry about this, you had better go through the Sun Swing tutorials. You are making a critical error trying to mix AWT components (i.e., Panels) with Swing components. Unless you really know what you are doing (and in this situation, you don't), this shouldn't be done.
    and i want to display these instances on a JPanel in another class which myclass1 should be on the left and myclass2 on the right 100 pixels away from the other.You should read up on the Layout managers. BoxLayout may work well here, though again, first go through the basic Swing tutorials.
    Please show any code???
    aw h�ll, you've already been told much of this in your cross-post. You've also got another cross-post in the Java-2D forum. Unless you are trying to piss us off, you'd best refrain from cross-posting.
    Edited by: Encephalopathic on Feb 18, 2008 9:53 AM

  • How do you create different shaped borders?

    I need to create lots of different shaped borders that can be selected for a particular component, I know that you have to either extend AbstractBorder or implement Border interface, but I don't really know how to get the shape that I want, the most basic of which is a circle.
    Also will the component 'know' how to size the border so that the child components fit within it with no overlap?
    if anyone has an example border class they could donate to ease my confusion, i would be most grateful

    I have attached code for a border that draws a circle. If the insets are not large enough, then the child component will overlap. The large the child component needs to be, the large the insets should be in order for the oval to not be broken.
    // Border class
    public class OvalBorder implements javax.swing.border.Border {
        // insets used by the parent component for sizing the child component
        java.awt.Insets insets;
        public OvalBorder( ) {
            this( new java.awt.Insets( 20, 20, 20, 20 ) );
        public OvalBorder( java.awt.Insets insets ) {
            this.insets = insets;
        // Tell the parent component not to pain a backgroun underneath the border.
        public boolean isBorderOpaque( ) {
            return false;
        // Paint a simple oval border.
        public void paintBorder( java.awt.Component component, java.awt.Graphics g, int x, int y, int width, int height ) {
            g.setColor( java.awt.Color.white );
            g.fillOval( x, y, width, height );
            g.setColor( java.awt.Color.black );
            g.drawOval( x, y, width, height );
        // Return the insets that the parent component will use to size
        // the child component
        public java.awt.Insets getBorderInsets( java.awt.Component p1 ) {
            // Must do a clone so an outside source does not mess up the inset object.
            return (java.awt.Insets)insets.clone( );
        // A simple frame example of the border
        public static void main( String[ ] args ) {
            javax.swing.JFrame frame = new javax.swing.JFrame( );
            frame.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE );
            javax.swing.JPanel panel = new javax.swing.JPanel( new java.awt.GridLayout( 2, 1, 0, 0 ) );
            panel.setBorder( new OvalBorder( ) );
            frame.setContentPane( panel );
            javax.swing.JButton add = new javax.swing.JButton( "Add" );
            javax.swing.JButton minus = new javax.swing.JButton( "Minus" );
            frame.getContentPane( ).add( add );
            frame.getContentPane( ).add( minus );
            Inc inc = new Inc( add, minus, frame );
            add.addActionListener( inc );
            minus.addActionListener( inc );
            frame.pack( );
            frame.setVisible( true );
    // A support class that will cause the frame to resize equaly in both directions.
    class Inc implements java.awt.event.ActionListener {
        javax.swing.JButton add;
        javax.swing.JButton minus;
        javax.swing.JFrame frame;
        java.awt.Dimension pref;
        public Inc( javax.swing.JButton add, javax.swing.JButton minus, javax.swing.JFrame frame ) {
            this.add = add;
            this.minus = minus;
            this.frame = frame;
            pref = minus.getPreferredSize( );
            pref.width = pref.height<<1;
        public void actionPerformed( java.awt.event.ActionEvent event ) {
            if ( event.getSource( ) == add ) {
                pref.width+=2;
                pref.height++;
            } else {
                pref.width-=2;
                pref.height--;
            add.setPreferredSize( pref );
            minus.setPreferredSize( pref );
            System.out.println( pref );
            frame.pack( );
    }

  • How to set image to JPanel

    Hi to all,
    How to set background image to panel in swing?
    If anyone knows tell me..

    Hi,
    Just modify and use this..
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import javax.swing.JCheckBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    import RboJComponents.RboJEmailTextField;
    import RboJComponents.RboJPanel;
    public class ImagePanel extends JPanel
    public static final int TILED = 0;
    public static final int SCALED = 1;
    public static final int ACTUAL = 2;
    private BufferedImage image;
    private int style;
    private float alignmentX = 0.5f;
    private float alignmentY = 0.5f;
    public ImagePanel(BufferedImage image)
    this(image, TILED);
    public ImagePanel(BufferedImage image, int style)
    this.image = image;
    this.style = style;
    setLayout( new BorderLayout() );
    public void setImageAlignmentX(float alignmentX)
    this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
    public void setImageAlignmentY(float alignmentY)
    this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
    public void add(JComponent component)
    add(component, null);
    public void add(JComponent component, Object constraints)
    component.setOpaque( false );
    if (component instanceof JScrollPane)
    JScrollPane scrollPane = (JScrollPane)component;
    JViewport viewport = scrollPane.getViewport();
    viewport.setOpaque( false );
    Component c = viewport.getView();
    if (c instanceof JComponent)
    ((JComponent)c).setOpaque( false );
    super.add(component, constraints);
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    if (image == null ) return;
    switch (style)
    case TILED :
    drawTiled(g);
    break;
    case SCALED :
    Dimension d = getSize();
    g.drawImage(image, 0, 0, d.width, d.height, null);
    break;
    case ACTUAL :
    drawActual(g);
    break;
    private void drawTiled(Graphics g)
    Dimension d = getSize();
    int width = image.getWidth( null );
    int height = image.getHeight( null );
    for (int x = 0; x < d.width; x += width)
    for (int y = 0; y < d.height; y += height)
    g.drawImage( image, x, y, null, null );
    private void drawActual(Graphics g)
    Dimension d = getSize();
    float x = (d.width - image.getWidth()) * alignmentX;
    float y = (d.height - image.getHeight()) * alignmentY;
    g.drawImage(image, (int)x, (int)y, this);
    public static void main(String [] args)throws Exception
    BufferedImage image = javax.imageio.ImageIO.read(new java.io.File("c:\\final.jpg"));
    //ImagePanel north = new ImagePanel(image, ImagePanel.ACTUAL);
    //north.setImageAlignmentY(1.0f);
    //JTextArea text = new JTextArea(5, 40);
    //JScrollPane scrollPane = new JScrollPane( text );
    //north.add( scrollPane );
    ImagePanel south = new ImagePanel(image, ImagePanel.SCALED);
    south.setPreferredSize(new Dimension(490, 340));
    south.setLayout(null);
    RboJPanel buttons = new RboJPanel();
    buttons.setBounds(15, 105, 350, 50);
    RboJEmailTextField toAddress = new RboJEmailTextField(28);
    //toAddress.setBounds(20,20,20,20);
    //toAddress.setCaretColor ( toAddress.getBackground () ) ;
    buttons.add(toAddress);
    //buttons.add(new JButton("Two"));
    /*JPanel boxes = new JPanel();
    boxes.add( new JCheckBox("One"));
    boxes.add( new JCheckBox("Two") );*/
    south.add(buttons);
    //south.add(boxes, BorderLayout.PAGE_END);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.getContentPane().add( north, BorderLayout.NORTH );
    frame.getContentPane().add( south);
    frame.pack();
    frame.setVisible(true);
    }Regards,
    Anees

  • JavaHelp initialization problem

    In my project, I used JavaHelp to create project help function. The following is party of HelpVolumeC.java source code.
    Here I used main thread to initialize main gui, at that time used another thread to invoke HelpVolumeC.getHvcInstance().
    at first time java help gui cannot be displayed. However when reinitialize main gui, then java help gui is ok.
    Somebody has meet this kind of issue? Could give me some advise? thanks!
    Here DefaultHelpBroker.initPresentation() is invoked in the second thread.
    I think it maybe when you use helpbroker, if it is not initialized completly, it will not be used correctly.
    that mean when you use helpbroker, it must be initialized completly. I dont know am I right.
    party of initializing of main gui in main thread
    // Set the plugin
    MjmController.setPlugin(this);
    // Create the controller
    mjm = MjmController.getPluginInstance();
    if (mjm != null) {
    _hvc = HelpVolumeC.getHvcInstance();
    // have to put this here, so we make sure it queued after the panel
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    running = mjm.isRunning();
    if (mjm.getFrameParent() != null) {
    mjm.getFrameParent().toFront();
    party of HelpVolumeC.java
    private static synchronized void loadLibrary() {
    if(!isLibraryLoaded() && !isLibraryLoading() && !libraryLoadFailed)
    try {
    URL hsURL = null;
    ClassLoader libraryClassLoader;
    if (HelpPropertiesC.getLibraryURL() == "") {
    report("loadLibrary(): Location of help system not defined.");
    libraryClassLoader = com/ops/inmP/commonuiP/helpP/HelpVolumeC.getClassLoader();
    } else {
    report((new StringBuilder()).append("loadLibrary(): Attempting to load help system from: ").append(HelpPropertiesC.getLibraryURL()).toString());
    libraryClassLoader = new URLClassLoader(new URL[] {new URL(HelpPropertiesC.getLibraryURL())}, null);
    hsURL = HelpSet.findHelpSet(libraryClassLoader, "master.hs");
    if (hsURL == null) {
    report("loadLibrary(): Failed to load helpset. Help unavailable.");
    libraryLoadFailed = true;
    } else {
    report("loadLibrary(): Found helpset - master.hs");
    theHelpSet = new HelpSet(null, hsURL);
    theHelpBroker = new DefaultHelpBroker();
    theHelpBroker.setHelpSet(theHelpSet);
    Runnable initHelp = new Runnable() {
    public void run() {
    try {
    HelpVolumeC.theHelpBroker.initPresentation();
    WindowPresentation pres = ((DefaultHelpBroker)HelpVolumeC.theHelpBroker).getWindowPresentation();
    java.awt.Window win = pres.getHelpWindow();
    JFrame helpWindow = (JFrame)win;
    ImageIcon nortelLogo = new ImageIcon(com/ops/inmP/commonuiP/helpP/HelpVolumeC.getResource("globemark.gif"));
    if(nortelLogo != null)
    helpWindow.setIconImage(nortelLogo.getImage());
    else
    HelpVolumeC.report("loadLibrary(): Failed to display Nortel Logo icon in Help window.");
    HelpVolumeC.libraryLoaded = true;
    HelpVolumeC.libraryLoading = false;
    } catch(Throwable t) {
    HelpVolumeC.report((new StringBuilder()).append("loadLibrary(): initHelp thread - initPresentation() failed. Help unavailable.Caught the throwable ").append(HelpVolumeC.getStackTrace(t)).toString());
    HelpVolumeC.libraryLoadFailed = true;
    HelpVolumeC.libraryLoading = false;
    Thread initHelpThread = new Thread(initHelp);
    initHelpThread.start();
    libraryLoading = true;
    HelpTriggerC.setHelpBroker(theHelpBroker);
    } catch(Throwable t) {
    report((new StringBuilder()).append("loadLibrary() - Library load failed. Help unavailable.Caught the throwable ").append(getStackTrace(t)).toString());
    libraryLoadFailed = true;
    private void initialize(String volumeName) {
    loadLibrary();
    if (isLibraryLoaded() || isLibraryLoading()) {
    triggers = new LinkedList();
    this.volumeName = volumeName;
    volumeExists = true;
    * @deprecated Method HelpVolumeC is deprecated
    public HelpVolumeC() {
    volumeExists = false;
    volumeName = "";
    triggers = null;
    initialize("");
    public static HelpVolumeC getHvcInstance() {
    if(theInstance == null)
    theInstance = new HelpVolumeC();
    return theInstance;
    }

    Yes u cannot do a Init after a Full.
    Make the Full Load a Repair Full.
    Se 38 - Source Code - RSSM_SET_REPAIR_FULL_FLAG
    Give the ODS name , Datasource & Source System n Make it Reparir Full
    Have a look at this note : Note 689964 - ODS object: Switching from a full to delta upload
    If this has to be done before loading - U can jst flag the Repair Full feature in Infopackage - Scheduler - Repair Full.
    Message was edited by:
            Jr Roberto

  • JFrame doesnt get refreshed

    Hi,
    I have a problem in refreshing the jframe. I m using netbeans. I am creating an application in which i create a jframe with a panel with a button. clicking on the button should result in replacing the contents on the screen with another panel.
    But all the new contents should come from another class.
    The code below removes the original contents of jframe, but doesnt add new contents.
    //Class FirstFrame
    package framerefreshtest;
    import javax.swing.*;
    import java.awt.*;
    public class FirstFrame extends javax.swing.JFrame {
        private JLabel label1;
        /** Creates new form FirstFrame */
        public FirstFrame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            panel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("Refresh Frame");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jLabel1.setText("This is the First Panel");
            javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
            panel1.setLayout(panel1Layout);
            panel1Layout.setHorizontalGroup(
                panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panel1Layout.createSequentialGroup()
                    .addGap(99, 99, 99)
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel1)
                        .addComponent(jButton1))
                    .addContainerGap(120, Short.MAX_VALUE))
            panel1Layout.setVerticalGroup(
                panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panel1Layout.createSequentialGroup()
                    .addGap(30, 30, 30)
                    .addComponent(jLabel1)
                    .addGap(28, 28, 28)
                    .addComponent(jButton1)
                    .addContainerGap(118, Short.MAX_VALUE))
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(51, 51, 51)
                    .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(34, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(46, 46, 46)
                    .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(41, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            panel1.removeAll();
                label1 = new JLabel("Message number TWO");
                panel1.add(label1,BorderLayout.SOUTH);
                SecondPanel panel2 = new SecondPanel();
                panel2.validate();
                panel2.setVisible(true);
                panel1.add(panel2,BorderLayout.NORTH);
                panel1.revalidate();
                panel1.repaint();
                panel2.revalidate();
                panel2.repaint();
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new FirstFrame().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JPanel panel1;
        // End of variables declaration
    * SecondPanel.java
    * Created on 10-Mar-2010, 10:57:33
    package framerefreshtest;
    * @author Main
    public class SecondPanel extends javax.swing.JPanel {
        /** Creates new form SecondPanel */
        public SecondPanel() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            jLabel1 = new javax.swing.JLabel();
            jButton1.setText("Go to First Panel");
            jLabel1.setText("This is the Second Panel");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(141, 141, 141)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jButton1))
                    .addContainerGap(144, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(51, 51, 51)
                    .addComponent(jLabel1)
                    .addGap(33, 33, 33)
                    .addComponent(jButton1)
                    .addContainerGap(179, Short.MAX_VALUE))
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        // End of variables declaration
    }any help ?

    b1l2u3m4 wrote:
    Hi,
    I have a problem in refreshing the jframe. I m using netbeans.You have my sympathies. When do you plan to learn how to code a GUI yourself?
    I am creating an application in which i create a jframe with a panel with a button. clicking on the button should result in replacing the contents on the screen with another panel.CardLayout
    db

  • Help needed refactoring my AutofillTextField

    Hello everyone,
    Implementing an autofill feature for JTextField raised several design issues, and I would like some help.
    First, source code, demo and a diagram can be found on my JRoller entry: http://www.jroller.com/page/handcream?entry=refactoring_challenge_autocomplete_jtextfield
    Most difficulties are due to the mix of input and output. I imply what was auto-filled by selecting that part of the text. This affects the input on the other end.
    An auto-filled selection doesn't behave like a normal one. Backspace will delete both the selection and an extra character. After that it immediately searches for a match, and auto-fills if necessary.
    Adding characters in the middle and getting a match, advances the caret as normal, but also auto-selects the text from that point. So the output "talks" to the input to get the normal caret position.
    To intercept text changes in JTextField I override PlainDocument, but other objects need access to the original, super-class methods. For this they use an inner class with methods wrapping the super-class methods.
    I wonder if this overriding forces some dirty code, or maybe I can always abstract it away. Maybe I must intercept text changes some other way to make everything cleaner, like removing all keyListeners and add my own. But I doubt that.
    My guess is that i'm just unable yet to see the right abstractions, and maybe I didn't go far enough with seperation. Anyway, I need help :). I tried not to ask, but this is going on for too long.
    Thanks,
    Yonatan.
    Some code:
    public interface Output {
         void showMatch(String userInput, String fixedInput, String fill);
         void showMismatch(String userInput);
    public interface Processor {
         void match(String userInput, Output output);
    public interface RealDocument {
         void insertString(int offset, String addition);
         void remove(int offset, int length);
         void clear();
         String getText();
    public class AutoFillDocument extends javax.swing.text.PlainDocument {
         @Override
         public void insertString(int offset, java.lang.String addition, javax.swing.text.AttributeSet attributes) throws javax.swing.text.BadLocationException {
              replacing = false;
              String proposedValue = new StringBuilder(real.getText()).insert(offset, addition).toString();
              TextFieldOutput output = new TextFieldOutput(field, real, new DefaultInsert(offset, addition));
              search.match(proposedValue, output);
              autoFilledState = output.autoFilled();
         @Override
         public void remove(int offset, int length) throws javax.swing.text.BadLocationException {
              if (replacing) {
                   real.remove(offset, length);
                   replacing = false;
              } else {
                   removeDirect(offset, length);
         private void removeDirect(int offset, int length) {
              if (backspacing && autoFilledState) {
                   offset--;
                   length++;
              removeDelegate(offset, length);
         private void removeDelegate(int offset, int length) {
              String proposedValue = new StringBuilder(real.getText()).delete(offset, offset + length).toString();
              TextFieldOutput output = new TextFieldOutput(field, real, new DefaultRemove(offset, length));
              search.match(proposedValue, output);
              autoFilledState = output.autoFilled();
         @Override
         public void replace(int arg0, int arg1, java.lang.String arg2, javax.swing.text.AttributeSet arg3) throws javax.swing.text.BadLocationException {
              replacing = true;
              super.replace(arg0, arg1, arg2, arg3);
         public AutoFillDocument(yon.ui.autofill.Processor search, javax.swing.JTextField field) {
              this.search = search;
              this.field = field;
              field.addKeyListener(new java.awt.event.KeyAdapter() {
                   public void keyPressed(java.awt.event.KeyEvent e) {
                        backspacing = java.awt.event.KeyEvent.VK_BACK_SPACE == e.getKeyCode();
         yon.ui.autofill.Processor search;
         javax.swing.JTextField field;
         boolean backspacing = false;
         boolean autoFilledState = false;
         boolean replacing = false;
         public final RealDocument real = new RealDocument();
         private class RealDocument implements yon.ui.autofill.RealDocument {
              public void insertString(int offset, String addition) {
                   try {
                        AutoFillDocument.super.insertString(offset, addition, null);
                   } catch (Exception ex) {
                        throw new RuntimeException(ex);
              public void remove(int offset, int length) {
                   try {
                        AutoFillDocument.super.remove(offset, length);
                   } catch (Exception ex) {
                        throw new RuntimeException(ex);
              public void clear() {
                   try {
                        AutoFillDocument.super.remove(0, AutoFillDocument.super.getLength());
                   } catch (Exception ex) {
                        throw new RuntimeException(ex);
              public String getText() {
                   try {
                        return AutoFillDocument.super.getText(0, AutoFillDocument.super.getLength());
                   } catch (Exception ex) {
                        throw new RuntimeException(ex);
         private class DefaultInsert implements yon.ui.autofill.TextFieldOutput.DefaultAction {
              public void execute() {
                   real.insertString(offset, addition);
              public DefaultInsert(int offset, String addition) {
                   this.offset = offset;
                   this.addition = addition;
              private int offset;
              private String addition;
         private class DefaultRemove implements yon.ui.autofill.TextFieldOutput.DefaultAction {
              public void execute() {
                   real.remove(offset, length);
              public DefaultRemove(int offset, int length) {
                   this.offset = offset;
                   this.length = length;
              private int offset;
              private int length;
    public class DefaultProcessor implements Processor {
         public void match(String userInput, Output output) {
              String match = startsWith(userInput);
              if (match == null) {
                   output.showMismatch(userInput);
              } else {
                   output.showMatch(userInput, match.substring(0, userInput.length()), match.substring(userInput.length()));
         public String startsWith(String prefix) {
              yon.utils.IsStringPrefix isPrefix = new yon.utils.IsStringPrefix(prefix);
              for (String option: options) {
                   if (isPrefix.of(option)) {
                        return option;
              return null;
         public DefaultProcessor(String[] options) {
              this.options = options;
         String[] options;
    public class TextFieldOutput implements Output {
         public void showMatch(String userInput, String fixedInput, String fill) {
              if (!userInput.isEmpty()) {
                   if (fill.isEmpty()) { // exact match
                        defaultAction.execute();
                        int caretPosition = field.getCaret().getDot();
                        field.getCaret().setDot(fixedInput.length());
                        field.getCaret().moveDot(caretPosition);
                   } else {
                        document.clear();
                        document.insertString(0, fixedInput + fill);
                        field.getCaret().setDot(fixedInput.length() + fill.length());
                        field.getCaret().moveDot(fixedInput.length());
                   autoFilled = field.getCaret().getDot() != field.getCaret().getMark();
              } else {
                   document.clear();
                   autoFilled = false;
         public void showMismatch(String userInput) {
              defaultAction.execute();
              autoFilled = false;
         public boolean autoFilled() {
              return autoFilled;
         public TextFieldOutput(javax.swing.JTextField field, yon.ui.autofill.RealDocument document, DefaultAction defaultAction) {
              this.field = field;
              this.document = document;
              this.defaultAction = defaultAction;
         private javax.swing.JTextField field;
         private yon.ui.autofill.RealDocument document;
         private DefaultAction defaultAction;
         private boolean autoFilled;
         public interface DefaultAction {
              void execute();
    public class AutoFillFeature {
         public void installIn(javax.swing.JTextField field) {
              Processor processor = new DefaultProcessor(options);
              AutoFillDocument document = new AutoFillDocument(processor, field);
              field.setDocument(document);          
         public AutoFillFeature(String[] options) {
              this.options = options;
         String[] options;
    }

    I made the code very simple in the interest of discussion in this forum.
    1) Now everything is in one class.
    2) I extend DocumentFilter instead of Document, which already implements the acrobatics I tried earlier.
    3) I Commented most parts of the code.
    How would you refactor it? It can be as simple as splitting into more methods, but you can also introduce more objects, and maybe even use a GoF pattern.
    Here is the code. Good luck :)
    package yon.ui.autofill;
    public class AutoFillFilter extends javax.swing.text.DocumentFilter {
         // Called when user tries to insert a string into a text-box.
         // bypass - can change the text without causing a recursion.
         // offset - where to insert
         // addition - what to insert
         // attributes - mostly ignored
         @Override
         public void insertString(FilterBypass bypass, int offset, String addition, javax.swing.text.AttributeSet attributes) throws javax.swing.text.BadLocationException {
              bypass.insertString(offset, addition, attributes);
              handleInput(bypass, currentValue(bypass));
         // Called when user tries to remove a string in a text-box.
         // bypass - can change the text without causing a recursion.
         // offset - where to start removal
         // length - how much to remove
         @Override
         public void remove(FilterBypass bypass, int offset, int length) throws javax.swing.text.BadLocationException {
              if (backspacing && autoFilled) {
                   offset--;
                   length++;
              bypass.remove(offset, length);
              handleInput(bypass, currentValue(bypass));
         // Called when user tries to replace a string in a text-box.
         // bypass - can change the text without causing a recursion.
         // offset - replaced section start
         // length - replaced section length
         // substitution - ...
         // attributes - mostly ignored
         @Override
         public void replace(FilterBypass bypass, int offset, int length, String substitution, javax.swing.text.AttributeSet attributes) throws javax.swing.text.BadLocationException {
              bypass.remove(offset, length);
              insertString(bypass, offset, substitution, null);
         // Searching for a match and auto-fill.
         // bypass - can change the text without causing a recursion.
         // input - user input
         private void handleInput(FilterBypass bypass, String input) {
              String match = options.firstStartsWith(input);
              handleMatchResult(match, input, bypass);
         // Check match and display in text-box accordingly.
         // match - result from searching options
         // input - raw input from user
         // bypass - can change the text without causing a recursion.
         private void handleMatchResult(String match, String input, FilterBypass bypass) {
              // If no match, or match was default (empty string is prefix of anything)
              //   leave text-box as it is.
              // If matched, imply by selecting the autu-filled section.
              if (match == null || input.isEmpty()) {
                   autoFilled = false;
              } else {
                   showMatch(bypass, match);
         // Displays text with auto selected section.
         // It knows where to start selecting according to the current caret state.
         private void showMatch(FilterBypass bypass, String match) {
              int caretPosition = field.getCaret().getDot();
              clear(bypass);
              bypassInsertString(bypass, 0, match);
              mark(match.length(), caretPosition);
              autoFilled = field.getCaret().getDot() != field.getCaret().getMark();
         // Convenience method to get the whole text-box text.
         private String currentValue(FilterBypass bypass) {
              try {
                   return bypass.getDocument().getText(0, bypass.getDocument().getLength());
              } catch (Exception ex) {
                   throw new RuntimeException(ex);
         // Convenience method to insert a string to text-box.
         private void bypassInsertString(FilterBypass bypass, int offset, String addition) {
              try {
                   bypass.insertString(offset, addition, null);
              } catch (Exception ex) {
                   throw new RuntimeException(ex);
         // Convenience method to clear all text from text-box
         private void clear(FilterBypass bypass) {
              try {
                   bypass.remove(0, bypass.getDocument().getLength());
              } catch (Exception ex) {
                   throw new RuntimeException(ex);
         // Convenience method to mark (select) a text-box section
         private void mark(int from, int to) {
              field.getCaret().setDot(from);
              field.getCaret().moveDot(to);
         // Constructor
         // Registers a listener to BACKSPACE typing, so we don't just delete a selection,
         //   but delete one extra character. otherwise users can't backspace more than once,
         //   if their input was auto-filled.
         // Registers a listener to text-box caret, so we know if a section of text-box is
         //   selected automatically by us. (it helps together with backspace to delete one
         //   extra character.
         public AutoFillFilter(javax.swing.JTextField field, Options options) {
              this.options = options;
              this.field = field;
              // Similar to C# delegator.
              this.field.addKeyListener(new java.awt.event.KeyAdapter() {
                   public void keyPressed(java.awt.event.KeyEvent e) {
                        backspacing = java.awt.event.KeyEvent.VK_BACK_SPACE == e.getKeyCode();
              // Similar to C# delegator.
              field.getCaret().addChangeListener(new javax.swing.event.ChangeListener() {
                   public void stateChanged(javax.swing.event.ChangeEvent arg0) {
                        autoFilled = false; // Factory trusts Output to set it only after changing caret, so next caret change fill cancel autofill.
         // Was the current text auto-filled and now in an auto-selection state?
         private boolean autoFilled;
         // Options to match against when trying to auto-fill.
         private Options options;
         // Did the user just pressed Backspace?
         private boolean backspacing = false;
         // The text-box.
         javax.swing.JTextField field;
    // One extra class if anyone wants to build and run it.
    package yon.ui.autofill;
    public class Options {
         public String firstStartsWith(String prefix) {
              yon.utils.IsPrefix isPrefix = new yon.utils.IsPrefix(prefix);
              for (String option: options) {
                   if (isPrefix.of(option)) {
                        return option;
              return null;
         public Options(String... options) {
              this.options = options;
         String[] options;
    // Oh and this one for prefix checking:
    package yon.utils;
    public class IsPrefix {
         public boolean of(String str) {
              return str.regionMatches(true, 0, prefix, 0, prefix.length());
         public IsPrefix(String prefix) {
              this.prefix = prefix;
         String prefix;
    // And a demo so you have a quick start.
    package yon.ui.autofill;
    public class MiniApp {
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        javax.swing.JTextField field = new javax.swing.JTextField();
                        Options options = new Options("English", "Eng12lish", "French", "German", "Heb", "Hebrew");
                        makeAutoFill(field, options);
                        javax.swing.JLabel label = new javax.swing.JLabel("English, Eng12lish, French, German, Heb, Hebrew");
                        javax.swing.JPanel panel = new javax.swing.JPanel();
                        panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.PAGE_AXIS));
                        panel.add(field);
                        panel.add(javax.swing.Box.createVerticalStrut(10));
                        panel.add(label);
                        javax.swing.JFrame frame = new javax.swing.JFrame();
                        frame.add(panel);
                        frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
                        frame.pack();
                        frame.setVisible(true);
         public static void makeAutoFill(javax.swing.JTextField field, Options options) {
              javax.swing.text.PlainDocument document = new javax.swing.text.PlainDocument();
              document.setDocumentFilter(new AutoFillFilter(field, options));
              field.setDocument(document);     
    }

  • Jdeveloper jar communication

    hi!
    Problem: I have created a main application using swing that class extends JFrame. This main application consists of two parts. One left side panel and one right side panel. Left side panel contains JTree component. Each item in that tree refers to a class file located in a separate jar file.i.e that acts as a separate application. If we are executing separately that jar file class, I am able to see that small application running. If I am selecting an item in JTree during runtime, I should place that small application from the respective jar file in the right side panel of the main application. I can locate the jar file and even I can create object to that particular class file. But I cannot execute the application even separately and also not able to place in the right side panel of the main application.
    with regards
    s.senthilkumar

    Hi,
    I don't understan dthe problem from how you describe it. Jar files are a place to store Java classes. It doesn't make a difference if all classes are part of one or many jar files as long as they are available in teh application class path.
    Object instaces can be passsed from one panel in Swing to another using either a method or a constructor.
    Frank

Maybe you are looking for

  • Encore Projects built on older version does not open in new Encore

    I have built many projects on older version of Encore 1.5. They will not open in CS5 version of Encore. What is a poor guy supposed to do? How can I open these Encore files and make another copy? Any suggestions welcome! Thanks.

  • I have a new ipad mini 3 and the sync will not complete and import iphoto pictures

    I have a new ipad mini 3 and the sync will not complete and import iphoto pictures

  • Aperture Facebook Connection Issues

    So I just installed Aperture 3 and want to connect to Facebook but cannot or do not know how to.  Please help!  I also installed the plug-in but do not seem to be able to even know how or where to access or use that either.  I have been reading and s

  • LINQ and Crystal Reports

    Post Author: Lawrence007 CA Forum: Crystal Reports Hi, I am currently working with LINQ and was wondering if LINQ would work with Crystal Reports? If it would how? Are there any samples out there? Thanks

  • IPhoto crashes on Lion

    I am having trouble getting iPhoto to start on Lion. To give you a little info about why I'm having this problem, first our iMac purchased in 2011 experieced a 'sibling link error' out of nowhere. Took it into Apple and was told to re-install the OS