JTextField in a JPanel

It's been a couple years since I worked with GridBagLayout. I'm trying to add a JTextField
to a JPanel but it does not seem to be working - it ignores the GridBagConstraints fill and anchor, changes
to the JTextField are only visible when resizing the window, and if the text is longer than the
component it disappears altogether. All I'm trying to do is add some padding around the
component.
I'm using 1.6.0u12. Is this related to [this bug|http://bugs.sun.com/view_bug.do?bug_id=4238932]?
import java.awt.*;
import javax.swing.*;
public class Example{
public static void main(String[] args){
     new Example().start();
public void start(){
     JTextField tf = new JTextField();
     GridBagLayout gbl = new GridBagLayout();
     GridBagConstraints gbc = new GridBagConstraints();
     gbc.insets = new Insets(7, 7, 7, 7);
     gbc.gridx = 0;
     gbc.gridy = 0;
     gbc.gridwidth = 1;
     gbc.gridheight = 1;
     gbc.fill = GridBagConstraints.BOTH;
     gbc.anchor = GridBagConstraints.EAST;
     JPanel box = new JPanel();
     box.setBackground(Color.YELLOW);
     box.setLayout(gbl);
     box.add(tf, gbc);
     JFrame frame = new JFrame();
     frame.setContentPane(box);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(800, 600);
     frame.setLocationRelativeTo(null);
     frame.setVisible(true);
}

Apparently x, y, width, height are optional, but the weight is necessary.From the doco
If all the weights are zero, all the extra space appears between the grids of the cell and the left and right edges.
There's a gothcha when using weights in a multi column/row GBLayout that's clearly documented but often overlooked: the extra space is distributed in the proportion of the weights. Not the total space. And how the GBLayout treats the weight when gridwidth/height > 1 is anybody's guess, since all that's said is
The grid bag layout manager calculates the weight of a column to be the maximum weightx of all the components in a column.
How are you?Same old, same old. Counting down to my retirement next year, [b3]if the posers that be don't raise the retirement age yet again ;-)
I stop in occasionally, but I see less and less of the people I remember.Yup, we see less and less of TP too :P
Has everyone jumped ship to another forum?Well, camickr is spreading the Swing joy at about 4 forums nowadays, but I think this is still his 'home' forum. E'hic you may better know as petes1234. Some other regulars have indeed disappeared, most notably BDLH and his MIPs. No news about any of them though.
Darryl

Similar Messages

  • Getting values from a JTextField on a JPanel in another class

    I have created a class which extends a JPanel and added a JTextField to it, which has an addActionListener for getting the values typed in the JTextField. I want to use the class created in another class and retrieve the values typed in the JTextField, so how do i go about that? I have the class created below so the problem is how to retrieve content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
      int val;
      public TextFieldChooser(String str){
        val = 0;     
        setLayout(new FlowLayout());
        add(new JLabel(str));
        JTextField txtf = new JTextField(5);
        txtf.addActionListener(new TextFieldListener());
        add(txtf);
      }//end constructor     
      private class TextFieldListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
           val = Integer.parseInt(e.getActionCommand());
      }//end text field listener
      public int getValue(){
        return val;     
    }//class

    The problem is which listener can be programmed to handle the event performed on the class TextFieldChooser in the other class?
    I have created a class which extends a JPanel and
    added a JTextField to it, which has an
    addActionListener for getting the values typed in the
    JTextField. I want to use the class created in
    another class and retrieve the values typed in the
    JTextField, so how do i go about that? I have the
    class created below so the problem is how to retrieve
    content of val[val] in another class?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class TextFieldChooser extends JPanel{
    int val;
    public TextFieldChooser(String str){
    val = 0;
    setLayout(new FlowLayout());
    add(new JLabel(str));
    JTextField txtf = new JTextField(5);
    txtf.addActionListener(new TextFieldListener());
    add(txtf);
    }//end constructor
    private class TextFieldListener implements
    s ActionListener{
    public void actionPerformed(ActionEvent e) {
    val = Integer.parseInt(e.getActionCommand());
    }//end text field listener
    public int getValue(){
    return val;
    }//class

  • JTextFields inside a JPanel inside a JTable

    I have a JTable of one column, in which each row is a JPanel. The JPanel has JTextFields and JComboBoxs. The JPanel implements TableCellRenderer and TableCellEditor. It also declares an attribute as follows;
    DefaultCellEditor defCellEd = new DefaultCellEditor(new JComboBox);.
    All of the TableCellEditor methods are implemented in the same manner as the following method (except getCellEditorComponent(...)), i.e. they all pass the implementation onto the declared DefaultCellEditor;
    public boolean stopCellEditing()
         return defCellEd.stopCellEditing();
    getCellEditorComponent(...) is implemented to
    return (java.awt.Component)value;
    All seems to work fine, with one minor exception. My textfields are right justified, so for text that exceeds the default size of the textfield it is in, the first n characters are not visible initially. I would rather have it left justified with the trailing characters being not visible.
    If I do not set the cell editor for the panel (just setting the renderer) the text is left justified - problem there is, none of the fields are editable. Furthermore, testing of the JPanel standalone has the textfields left justified, also.
    Any help is appreciated, thanks in advance.

    I'm glad that helped.
    Basically, every text component has a caret, and the caret wants to be visible all the time, setText() moves the caret to the end, that's why setting the caret to null prevents this behavior.
    It appears that Sun doesn't intend to change this behavior so this fix is as far as I know the best we could do for now. See http://developer.java.sun.com/developer/bugParade/bugs/4227520.html for more information.

  • Using setBounds on JTextFields within JPanel

    Hi folks,
    I hope someone can help me with this.
    Basically the heirarchy of my UI is as follows:
    The top level JFrame has a borderlayout. The north contains a couple of JButtons and the center contains a JTabbedPane.
    Each tab in the JTabbedPane is borderlayout, with the South having another JTabbedPane, and the Center having a JPanel containing other UI elements.
    In one of these JPanels I want to show a schematic of a plant and on top if over textfields in different locations to current values for different sensors. lets call this JPanel schematicPanel
    For schematicPanel I have set the layout to OverlayLayout. The bottom layer for the schematicPanel is a JLabel that is the actual schematic of the plant. The next layer of the schematicPanel is a JPanel that contains all the JTextFields. This JPanel is set to be transparent using setOpaque(false)
    For the JPanel that contains the JTextFields I have not set a layout. What I want to do is use setBounds, or setLocation to place the JTextFields in the correct locations. Unfortunately those methods have no affect what so ever.
    I have no idea what is wrong.
    Thanks for any help that anyone can offer
    Shabbir
    PS. I tried place the JTextFields directly on the schematicPanel but using setAlignmentX and setAlignmentY does not work very well, and is very cumbersome. If there is a way to make it work I am open to suggestions. Thanks.

    Firstly, in swing the default layout is BorderLayout.
    So when you have not set any layouts the layout is Borderlayout.Now if you want the setBounds(),setLocation() etc methods to take effect for any component the Layout needs to be expicitely set to null.
    ThereFore,set the Layout of the JPanel where you want to place JTextFields to null for eg panel.setLayout(null) and then see how the setBounds(),setLocation() etc methods take effect.
    Got It!!!
    PK

  • Reading values from JTextField and using them?

    Hello,
    I am trying to make a login screen to connect to an oracle database. Im pretty new to creaing GUI. I need help with reading the values from the JTextField and to be able to use them for my connection. So do I need to apply a listener? How do I go about doing that in this project. Thanks for any code or advice.
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.sql.*;
    public class UserDialog
        String databaseURL;
        String driver;
        String database;
        String username;
        String password;
        String hostname;
        String port;
        UserDialog() {
            getInfo();
        static String[] ConnectOptionNames = { "Login", "Cancel" };
        static String   ConnectTitle = "Login screen";
        public void getInfo() {
            JPanel      connectionPanel;
            JLabel     databaseURLLabel = new JLabel("Database URL:   ", JLabel.LEFT);
         JTextField databaseURLField = new JTextField("");
         JLabel     driverLabel = new JLabel("Driver:   ", JLabel.LEFT);
         JTextField driverField = new JTextField("");
            JLabel     databaseLabel = new JLabel("Database:   ", JLabel.LEFT);
         JTextField databaseField = new JTextField("");
            JLabel     usernameLabel = new JLabel("User Name:   ", JLabel.LEFT);
         JTextField usernameField = new JTextField("");
            JLabel     passwordLabel = new JLabel("Password:   ", JLabel.LEFT);
         JTextField passwordField = new JPasswordField("");
            JLabel     hostnameLabel = new JLabel("Host Name:   ", JLabel.LEFT);
         JTextField hostnameField = new JTextField("");
            JLabel     portLabel = new JLabel("Port:   ", JLabel.LEFT);
         JTextField portField = new JTextField("");
         connectionPanel = new JPanel(false);
         connectionPanel.setLayout(new BoxLayout(connectionPanel,
                                  BoxLayout.X_AXIS));
         JPanel namePanel = new JPanel(false);
         namePanel.setLayout(new GridLayout(0, 1));
         namePanel.add(databaseURLLabel);
         namePanel.add(driverLabel);
            namePanel.add(databaseLabel);
            namePanel.add(usernameLabel);
            namePanel.add(passwordLabel);
            namePanel.add(hostnameLabel);
            namePanel.add(portLabel);
         JPanel fieldPanel = new JPanel(false);
         fieldPanel.setLayout(new GridLayout(0, 1));
         fieldPanel.add(databaseURLField);
            fieldPanel.add(driverField);
            fieldPanel.add(databaseField);
            fieldPanel.add(usernameField);
         fieldPanel.add(passwordField);
            fieldPanel.add(hostnameField);
            fieldPanel.add(portField);
         connectionPanel.add(namePanel);
         connectionPanel.add(fieldPanel);
            // Connect or quit
            databaseURL = databaseURLField.getText();
            driver = driverField.getText();
            database = databaseField.getText();
            username = usernameField.getText();
            password = passwordField.getText();
            hostname = hostnameField.getText();
            port = portField.getText();
            int n = JOptionPane.showOptionDialog(null, connectionPanel,
                                            ConnectTitle,
                                            JOptionPane.OK_CANCEL_OPTION,
                                            JOptionPane.PLAIN_MESSAGE,
                                            null, ConnectOptionNames,
                                            ConnectOptionNames[0]);
            if (n == 0) {
                System.out.println("Attempting login: " + username);
                String url = databaseURL+hostname+":"+port+":"+database;
             // load the JDBC driver for Oracle
             try{
                   DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                   Connection con =  DriverManager.getConnection (url, username, password);
                System.out.println("Congratulations! You are connected successfully.");
                con.close();
                System.out.println("Connection is closed successfully.");
             catch(SQLException e){
                System.out.println("Error: "+e);
            else if (n == 1)
                    System.exit(0);
        public static void main (String args []) {
             UserDialog ud = new UserDialog();
    }thanks again,
    James

    the reason why you can't get the text is because you are reading the value before some actually inserts anything in any fields.
    Here is what you need to do:
    Create a JDialog/JFrame. Create a JPanel and set that panel as contentPane (dialog.setContentPane(panel)). Insert all the components, ie JLabels and JTextFields. Add two buttons, Login and Cancel to the panel as well. Now get the username and password field values using getText() inside the ActionListener of the Login.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LoginDialog extends JDialog
    String username, password;
      public LoginDialog( ){
        setTitle( "Login" );
        JPanel content = new JPanel(new GridLayout(0, 2) ); // as many rows, but only 2 columns.
        content.add( new JLabel( "User Name" ) );
        final JTextField nameField = new JTextField( "" );
        content.add( nameField );
        content.add( new JLabel( "Password" ) );
        final JTextField passField = new JTextField( "" );
        content.add( passField );
        JButton login = new JButton( "Login" );
        login.addActionListener( new ActionListener(){
          public void actionPerformed( ActionEvent ae ){
            username = nameField.getText();
            password = passField.getText();
            // call a method or write the code to verify the username and login here...
        content.add( login );
        JButton cancel = new JButton( "Cancel" );
        cancel.addActionListener( new ActionListener( ){
          public void actionPerformed( ActionEvent ae ){
            dispose(); // close the window or write any code that you want here.
        content.add( cancel );
        pack( ); // pack everything in the dialog for display.
        show(); // show the dialog.

  • I can't edit my JTextField

    hi all,
    i add a JTextField in a JPanel but I can't edit it, should it has to have an actionListener to allow it?
    thanks and sorry for my ignorance.

    this is my code, and i'm still without knowing where is the problem because yours works fine!!!
    thanxs for your help!!!
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    import java.awt.Font;
    public class Inserta_Cliente{
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(
                   UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) { }
              JWindow window = new JWindow();
              window.getContentPane().setLayout(null);
              window.setBounds (0, 0, 1024, 768);
              /*Panel para consulta de clientes*/
              JPanel panel = new JPanel();
              panel.setLayout(null);
              TitledBorder title = BorderFactory.createTitledBorder("clientes");
              title.setTitleFont(new Font("", Font.BOLD, 13));
              panel.setBorder(title);
              panel.setSize(400, 250);
              panel.setLocation(40, 60);
              JLabel labelNif = new JLabel("nif:");
              JTextField textNif = new JTextField(25);
              labelNif.setLocation(20, 40);
              labelNif.setSize(50, 20);
              labelNif.setFont(new Font("", Font.PLAIN, 12));
              labelNif.setHorizontalAlignment(JLabel.RIGHT);
              textNif.setLocation(100, 40);
              textNif.setSize(60, 20);
              textNif.setFont(new Font("", Font.PLAIN, 12));
              panel.add(labelNif);
              panel.add(textNif);
              window.getContentPane().add(panel);
              window.show();
    }

  • Cursor becomes invisible in JTextField after using default button

    In my application there is an update screen (JPanel). I am using default button in that panel. The input field is a normal JTextField. When the update is over the cursor goes back to the input JTextField.
         Now my problem is that when I carry out update with mouse, the cursor is correctly placed into the input JTextField and is visible after the update is over. On the other hand, if I carry out the same update operation using default button (using keyboard), the cursor gets placed correctly in the input JTextfield column, but becomes invisible. If I minimize and then again maximize the window, the cursor appears back. What am I missing ? Note that I am using component.requestFocusInWindow() to get focus back to the input JTextField.
    regards,
    nirvan

    While trying to reproduce the behaviour for SSCCE, I found that it is the JOptionPane.showMessageDialog() that is causing the problem. Here is the SSCCE.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.WindowConstants;
    public class TestFocus extends javax.swing.JFrame {
        // Variables declaration - do not modify
        private JTextField field1;
        private JTextField field2;
        private JPanel jPanel1;
        private JButton reset;
        private JButton update;
        // End of variables declaration
        public TestFocus() {
            initComponents();
            setDefaultButton();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new JPanel();
            field1 = new JTextField();
            field2 = new JTextField();
            update = new JButton();
            reset = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            field1.setPreferredSize(new Dimension(40, 20));
            jPanel1.add(field1);
            field2.setPreferredSize(new Dimension(40, 20));
            jPanel1.add(field2);
            update.setText("Update");
            update.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    updateActionPerformed(evt);
            jPanel1.add(update);
            reset.setText("Reset");
            reset.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    resetActionPerformed(evt);
            jPanel1.add(reset);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-385)/2, (screenSize.height-258)/2, 385, 258);
        }// </editor-fold>
        public void setDefaultButton(){
            this.getRootPane().setDefaultButton(update);
        private void updateActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
            JOptionPane.showMessageDialog(this,"Activity Updated Succesfully in Database.",
                                            "Information",
                                            JOptionPane.INFORMATION_MESSAGE);
            update.setEnabled(false);
            field1.setEditable(false);
            reset.setEnabled(true);
            this.getRootPane().setDefaultButton(reset);
        private void resetActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
            field1.requestFocusInWindow();
            field1.setText("");
            field1.setEditable(true);
            reset.setEnabled(false);
            update.setEnabled(true);
            this.getRootPane().setDefaultButton(update);
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TestFocus().setVisible(true);
    }If I remove the JOptionPane.showMessageDialog() method, everything works fine with mouse as well as keyboard.
    regards,
    nirvan.

  • Can't work FlowLayout with a JPanel, but can with contentPane...

    Hi,
    I usually use setBounds to layout my components but I am trying FlowLayout and GridLayout this time. I tried FlowLayout and got it to work when not using a JPanel. But when I try adding the JTextField to a JPanel like in the code below, the JTextField doesn't appear and only the yellow background appears. I don't know why. Thanks for your help.
           Container contentPane = getContentPane();
           contentPane.setBackground( Color.YELLOW );
           registerJPanel = new JPanel();
           registerJPanel.setLayout(new FlowLayout());
           usernameloginJTextField = new JTextField("hi");
           registerJPanel.add(usernameloginJTextField);
           setTitle( "Application");
           setSize( 400,400);
           setVisible( true );

    know how i can put each new component on a new line?
    registerJPanel.setLayout(new GridLayout(0,1));

  • How to setText from tab1's JTextField to tab2's JTextField?

    Hi, How to setText from tab1's JTextField to tab2's JTextField, anyone can help me? When I press a button, it cannot pass the tab1's txt1.getText() to tab2's txt2.setText(). I have a 3 simple class that show below:
    ** Tabmain.java **
    ===================================================
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    public class Tabmain extends JFrame{
         JTabbedPane tab;
         JPanel panel1, panel2;
         JTextField txt1,txt2;
         JButton jb;
         public Tabmain(){
              super();
              addWindowListener( new WindowAdapter() {
         public void windowClosing(WindowEvent e)
         {System.exit(0);} });
              getContentPane().setLayout(new BorderLayout());
              tab = new JTabbedPane();
              tab.add("Tab1",new Tab1());
              tab.add("Tab2",new Tab2());
              getContentPane().add(tab,BorderLayout.CENTER);
              this.setSize(500,400);          
              this.setVisible(true);
         public static void main(String args[]){
              Tabmain tabmain = new Tabmain();
    ** Tab1.java **
    =======================================================
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Tab1 extends JPanel{
         private JTextField txt1;
         private JButton jb;
         private JPanel panel1;
         public Tab1(){
              super();
              this.setLayout(new BorderLayout());
              this.add(getPanel1());
         public JPanel getPanel1(){
              panel1 = new JPanel();
              panel1.setLayout(new BorderLayout());          
              txt1 = new JTextField();
              txt1.setBounds(new Rectangle(10, 10, 100, 12));          
              panel1.add(txt1,BorderLayout.NORTH);
              jb = new JButton("OK");
              jb.addActionListener(new Action());
              panel1.add(jb,BorderLayout.SOUTH);
              return panel1;
         class Action implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   String jbtxt = ((JButton)event.getSource()).getText();
                   if(jbtxt=="OK")
                        String str = txt1.getText();     
                        Tab2 tab2 = new Tab2();
                        tab2.txt2.setText(str);                    
    ** Tab2.java **
    ======================================================
    import java.awt.*;
    import javax.swing.*;
    public class Tab2 extends JPanel{
         public JTextField txt2;
         private JPanel panel2;
         public Tab2(){
              super();
              this.setLayout(new BorderLayout());
              this.add(getPanel2());
              public JPanel getPanel2(){
                   panel2 = new JPanel();
                   panel2.setLayout(new BorderLayout());          
                   txt2 = new JTextField();
                   txt2.setBounds(new Rectangle(10, 10, 100, 12));          
                   panel2.add(txt2,BorderLayout.NORTH);               
                   return panel2;
         public void setTXT(String str){
              txt2.setText(str);
    }

    in actionPerformed
    ((JTabbedPane)Tab1.this.getParent()).setSelectedIndex(1);but this will break if you add Tab1 to another panel, then add otherPanel to the tabbedPane
    doing it by passing a reference of the tabbedPane to Tab1 might be better
    //Tab1 t1 = new Tab1();
    Tab1 t1 = new Tab1(tab);
    public Tab1(){
      super();
      this.setLayout(new BorderLayout());
      this.add(getPanel1());
    change to
    public Tab1(final JTabbedPane tp){
      super();
      this.setLayout(new BorderLayout());
      this.add(getPanel1());
      jb.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          tp.setSelectedIndex(1);
    }

  • UI and JTextField

    Hello,
    I wrote my own TableUI to draw a JPanel instead of some rows.
    This works fine:
    public void paintPanel(Graphics g, JPanel infoPanel, int rowIndex)
    int yPos = 0;
    for(int i = 0; i < rowIndex; i++) {
    yPos += at.myTable.getJTable().getRowHeight(i);
    // Fast paint: use the table's renderer pane...
    rendererPane.paintComponent(g, infoPanel, null, 0, yPos, at.myTable.getJTable().getWidth(), at.infoHeight + 2);
    g.translate(0, at.infoHeight);
    The problem is that I have a JTextField inside my JPanel and it is not editable when I click on it. I'm not surprised as I only draw the JPanel.
    Could someone tell me what I have to add to have the JPanel and its JTextField working properly.
    Thanks in advance.
    Joe

    Ouch..... a panel as a cell in a table?
    Anyway, you'll have to implement a cell editor for the panel because JTable has no idea what editor to use with it. If there are more than one data entry areas in your panel, I suggest you implment an editor that will trigger a JDialog with the entire panel added to its content pane.
    ;o)
    V.V.

  • Repeated use of the same JTextField

    Does Java allow multi-use of JTextFields in multiple JPanels? What I'm trying to do in essence is I'm trying to click on a button that will allow a dialogue box to open. This dialogue box would contain a JTextField which I am also using (for the same purpose and information) elsewhere.
    Here's the scenario:
    you click on a button (say open account) and a dialogue box pops up to ask you which account to open. The JTextField I am using in the dialogue box would retain it's value when the account opens, though it is visible on the new window as well...
    If you know the answer to this, I would a preciate the help, thanks!
    Geyegeroffe

    considering that it's the same value in either
    container, does it matter if I make a reference? it
    should simply update the value wherever it was used
    last... correct?
    GeyeU can update the value by using setText method and the textfield can be added to different containers yet retaining the value. u have to keep on removing and adding the textfield between containers.
    May i know why u wanted the same textfield when infact u can create another one for another window and pass the string from the old textfield to the new textfield. That is the most simplest and effective job. what if many threads try to access the textfield from different classes. that sure would open the floodgates for a program to hang/freeze.

  • Popup menu does not show in JTextField

    I have a JPanel with a popup menu that works perfectly, as long as the right mouse button is clicked on the JPanel. However the popup menu does not show if the right mouse button is clicked on a JTextField that is within the JPanel.
    What has to be done that the popup menu shows always?
    this.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseReleased(MouseEvent e)
    this_mouseReleased(e);
    protected void this_mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    popPopup.show(this, e.getX(), e.getY());

    There are up to 20 JTextFields in the JPanels an the application has a lot of JPanels of course. Adding the listener to each and every JTextField means a lot of extra code. Is there really no generic solution to this problem???

  • A strange JPanel problem

    i have a JPanel which have a picture as a background the problem is when i wnat to add a JLabel or JTextField into this JPanel it didnt word but it works for labels bat JLabels no???why??
    here u are the code
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    public class d extends Container
        JTextField text1,text2,text3,text4,text5,text6;
         ImageIcon icon ;
       public d()
    {  super();
       setLayout(null );                                                                         
        setBackground(Color.RED);                                                                                                 
        text1=new JTextField();
       text2=new JTextField();
       text3=new JTextField();
       text4=new JTextField();
       text5=new JTextField();
        text6=new JTextField();
        panel p=new panel();
       p.setBounds(10,10,500,500);
         p.setLayout(null);
         p.setOpaque(true);
    p.setBackground(Color.WHITE);
    text1.setBounds(160,30,100,20);
    p.add(text1);
    text2.setBounds(10,30,100,20);
      p.add(text2);
      text3.setBounds(300,30,100,20);
      p.add(text3);
      text4.setBounds(10,100,100,20);
      p.add(text4);
    text5.setBounds(160,100,100,20);
      p.add(text5);
      text6.setBounds(300,100,100,20);
      p.add(text6);
    JLabel l1=new JLabel("touti");
    l1.setBackground(Color.WHITE);
      l1.setBounds(10,10,80,15);
      add(p);
       class panel extends JPanel
           public  void paint(Graphics g) {
           super.paint(g);
           icon=new ImageIcon("c:/bachir.jpg");
            g.drawImage(icon.getImage(),0,0, this);
    public static void main(String args[])
       JFrame frm = new JFrame( "test panel back ground" );
            frm.setBounds( 100, 100, 800, 800 );
            frm.getContentPane().setLayout( new BorderLayout() );
        d pnl=new d();
            frm.getContentPane().add(pnl , BorderLayout.CENTER );
      frm.setIconImage(Toolkit.getDefaultToolkit().getImage("c:/java/oicon.gif"));
            frm.setVisible( true );
    }

    You seem to be mixing AWT and Swing. You should use all AWT or all Swing but not a mixture. Try changing
    public class d extends Container
    to
    public class d extends JPanel.
    P.S. Your choice of class name stinks! It does not describes the role the class plays and it does not meet the Sun recommended coding standards.
    Message was edited by:
    sabre150

  • Adding same object(jtextfield) to different cards in card layout

    Have a combo box with 3 items which changes cards in a cardLayout.
    Have 3 panels as card in a cardLayout.
    Want to reuse the field txtName, lblName in pnlName and reuse txtAge, lblAge in pnlAge in all the cards.
    It only appears in the last card3 panel(i.e the last panel referenced)
    Is there a way I can show the same object(pnlName, pnlAge) in all the cards,
    Below is the code, any solution is welcome.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CardLayoutTest implements ItemListener {
    JPanel cards; //a panel that uses CardLayout
    public void addComponentToPane(Container pane) {
    //Put the JComboBox in a JPanel to get a nicer look.
    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    String comboBoxItems[] = { "Name", "ShortDetail","FullDetail"};
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);
              JLabel lblName, lblAddress, lblAge;
              JCheckBox chkMarried;
              JRadioButton rdbMale, rdbFemale;
              JTextField txtName, txtAddress, txtAge, txtSex;
              JPanel pnlName = new JPanel(new FlowLayout(FlowLayout.LEFT));
              pnlName.add(lblName = new JLabel("Name"));
              pnlName.add(txtName = new JTextField(10));
              JPanel pnlAddress = new JPanel(new FlowLayout(FlowLayout.LEFT));
              pnlAddress.add(lblAddress = new JLabel("Address"));
              pnlAddress.add(txtAddress = new JTextField(10));
              JPanel pnlAge = new JPanel(new FlowLayout(FlowLayout.LEFT));
              pnlAge.add(lblAge = new JLabel("Age"));
              pnlAge.add(txtAge = new JTextField(3));
              JPanel pnlSex = new JPanel(new FlowLayout(FlowLayout.LEFT));
              pnlSex.add(rdbMale = new JRadioButton("Male"));
              pnlSex.add(rdbFemale = new JRadioButton("Female"));
              JPanel pnlMarried = new JPanel(new FlowLayout(FlowLayout.LEFT));
              pnlMarried.add(chkMarried = new JCheckBox("Married"));
              //pnl3.add(lblName = new JTextField(10));
              JPanel card1 = new JPanel(new GridLayout(0,1));
              card1.add(new JLabel("Card1"));
              card1.add(pnlName);
              card1.add(pnlAge);
              JPanel card2 = new JPanel(new GridLayout(0,1));
              card2.add(new JLabel("Card2"));
              card2.add(pnlName);
              card2.add(pnlAge);
              card2.add(pnlAddress);
              JPanel card3 = new JPanel(new GridLayout(0,1));
              card3.add(new JLabel("Card3"));
              card3.add(pnlName);
              card3.add(pnlAge);
              card3.add(pnlSex);
              card3.add(pnlMarried);
    //Create the "cards".
    JPanel card1 = new JPanel();
    card1.add(new JButton("Button 1"));
    card1.add(new JButton("Button 2"));
    card1.add(new JButton("Button 3"));
    JPanel card2 = new JPanel();
    card2.add(new JTextField("TextField", 20));
         JPanel card3 = new JPanel();
    card3.add(new JLabel("Label"));
         JPanel card4 = new JPanel();
    card4.add(new JCheckBox("Hello Holla"));
    JPanel card5 = new JPanel();
              cards.add();
    //Create the panel that contains the "cards".
    cards = new JPanel(new CardLayout());
    cards.add(card1, "Name");
    cards.add(card2, "ShortDetail");
    cards.add(card3, "FullDetail");
    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(cards, BorderLayout.CENTER);
    public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    private static void createAndShowGUI() {
    JFrame frame = new JFrame("CardLayoutTest");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    CardLayoutTest demo = new CardLayoutTest();
    demo.addComponentToPane(frame.getContentPane());
         frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    }

    I'm 99% sure that you cannot have the same txtfields/combos in different JPanels at the same time, which explains why they only appear in the last panel they are added to... but I guess you already knew that.
    You could add these components to the panel you wish to show each time you change panels.
    Or
    you could have a panel which contains these components and add it to each of the 3 panels that you show on your cardLayout.
    Or
    you could store the values selected in the components in globals to your class and replicate each of the components with this data in each of your three panels.

  • Border not rendering properly on JPanel

    This is just a general question to see if I'm the only one having this problem or whether it is just a bug.
    I've got a Jframe with a couple of Jpanels within it. I want a border round one of the panels but for some reason the border only shows fully around 3 edges and only partly along the edge adjacent to the other JPanel.
    I thought this might be a layering problem with the panel without the border being placed on top of the border itself but I've had a similar problem with some JTextField. I've got 3 JTextFields in a JPanel each having their own border but every now and again the border will disappear from around the bottom JTextField.
    I realise this may well be a problem specific to my system or OS (Win 2000) but I thought I'd just check.
    Thanks, Clarkie

    Thanks for replying so quickly. Here is a cut down version of my code. I appologise now for using NetBeans as I believe this is frowned upon by many users of these forums.
    * NewJFrame.java
    * Created on 14 August 2006, 15:17
    package ets;
    import java.awt.*;
    import javax.swing.*;
    * @author  administrator
    public class sscce extends javax.swing.JFrame
        /** Creates new form NewJFrame */
        public sscce()
            initComponents();
            this.setIconImage(new ImageIcon("images/redtick48x48.gif").getImage());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents()
            java.awt.GridBagConstraints gridBagConstraints;
            panelCont = new javax.swing.JPanel();
            panelNav = new javax.swing.JPanel();
            panelBtnsAndImg = new javax.swing.JPanel();
            panelNavBtns = new javax.swing.JPanel();
            btnNav_client = new javax.swing.JButton();
            btnNav_job = new javax.swing.JButton();
            btnNav_inv = new javax.swing.JButton();
            btnNav_cert = new javax.swing.JButton();
            btnNav_admin = new javax.swing.JButton();
            panelLogout = new javax.swing.JPanel();
            panelMain = new javax.swing.JPanel();
            panelClientMenu = new javax.swing.JPanel();
            panelClientMent_title = new javax.swing.JPanel();
            labClientMent_title = new javax.swing.JLabel();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("ETS - Client Management System");
            setBackground(new java.awt.Color(255, 255, 255));
            setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
            setName("mainFrame");
            panelCont.setLayout(new java.awt.BorderLayout());
            panelCont.setBackground(new java.awt.Color(255, 255, 255));
            panelNav.setLayout(new java.awt.BorderLayout());
            panelNav.setBackground(new java.awt.Color(255, 255, 255));
            panelNav.setMaximumSize(new java.awt.Dimension(150, 150));
            panelNav.setPreferredSize(new java.awt.Dimension(150, 100));
            panelBtnsAndImg.setLayout(new java.awt.GridLayout(0, 1));
            panelBtnsAndImg.setBackground(new java.awt.Color(255, 255, 255));
            panelBtnsAndImg.setMaximumSize(new java.awt.Dimension(150, 32767));
            panelNavBtns.setLayout(new java.awt.GridLayout(0, 1));
            panelNavBtns.setBackground(new java.awt.Color(255, 255, 255));
            btnNav_client.setText("Clients");
            panelNavBtns.add(btnNav_client);
            btnNav_job.setText("Jobs");
            panelNavBtns.add(btnNav_job);
            btnNav_inv.setText("Invoices");
            panelNavBtns.add(btnNav_inv);
            btnNav_cert.setText("Certificates");
            panelNavBtns.add(btnNav_cert);
            btnNav_admin.setText("Admin");
            panelNavBtns.add(btnNav_admin);
            panelBtnsAndImg.add(panelNavBtns);
            panelNav.add(panelBtnsAndImg, java.awt.BorderLayout.NORTH);
            panelLogout.setLayout(new java.awt.BorderLayout());
            panelLogout.setBackground(new java.awt.Color(255, 255, 255));
            panelLogout.setMaximumSize(new java.awt.Dimension(150, 32767));
            panelNav.add(panelLogout, java.awt.BorderLayout.CENTER);
            panelCont.add(panelNav, java.awt.BorderLayout.WEST);
            panelMain.setLayout(new java.awt.CardLayout());
            panelMain.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            panelClientMenu.setLayout(new java.awt.GridBagLayout());
            panelClientMenu.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            panelClientMent_title.setLayout(new java.awt.BorderLayout());
            labClientMent_title.setFont(new java.awt.Font("Tahoma", 0, 36));
            labClientMent_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            labClientMent_title.setText("Main Panel");
            panelClientMent_title.add(labClientMent_title, java.awt.BorderLayout.CENTER);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.ipadx = 5;
            gridBagConstraints.ipady = 15;
            panelClientMenu.add(panelClientMent_title, gridBagConstraints);
            panelMain.add(panelClientMenu, "card2");
            panelCont.add(panelMain, java.awt.BorderLayout.CENTER);
            getContentPane().add(panelCont, java.awt.BorderLayout.CENTER);
            jMenu1.setText("Menu");
            jMenuBar1.add(jMenu1);
            setJMenuBar(jMenuBar1);
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[])
            Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    sscce s = new sscce();
                    s.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
                    s.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton btnNav_admin;
        private javax.swing.JButton btnNav_cert;
        private javax.swing.JButton btnNav_client;
        private javax.swing.JButton btnNav_inv;
        private javax.swing.JButton btnNav_job;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JLabel labClientMent_title;
        private javax.swing.JPanel panelBtnsAndImg;
        private javax.swing.JPanel panelClientMent_title;
        private javax.swing.JPanel panelClientMenu;
        private javax.swing.JPanel panelCont;
        private javax.swing.JPanel panelLogout;
        private javax.swing.JPanel panelMain;
        private javax.swing.JPanel panelNav;
        private javax.swing.JPanel panelNavBtns;
        // End of variables declaration
    }Also, I sometimes get a diagonal line going from the top left corner of a container to the first element when the JFrame is resized or reloaded from the Taskbar.
    Thanks again, Clarkie

Maybe you are looking for

  • No Item Catogoty available

    Hie Guyss.... I pricing procedure for Free goods... When I create a sales order it says "No Item Catogory Available (table T184 OR NORM FREE TAN) Can any one help me getting rid of this Error??? Best regards, Lata.

  • Disk Utility stopped verifying "Macintosh HD"

    I verify my disk and disk permissions every month or so, when I tried to verify the disk today I received the following message - "Disk Utility stopped verifying "Macintosh HD" The alert goes on to recommend I restart using my installion disk - since

  • Oracle 8.1.7 on Redhat Advanced Server 2.1

    According to this link http://www.redhat.com/oracle_cert/ RH AS 2.1 is certified for Oracle 8.1.7. But I couldn't find any information about installing oracle 8.1.7 on RH AS 2.1 on the internet. Could some one help me? I need step by step installatio

  • Error when using 64-bit host in send port

    Guys, I am trying out a simple message routing scenario. I have created a send pipeline and have used the MIME/SMIME component in the encoding stage of the pipeline. My application has a receive and a send port with receive port configured to receive

  • Finding serial number in Office X

    Is there a way to get my serial number from Office X though one of the programs?