1

I am new for Java. I have searched how to set the size of the JTextField and JButton, but I still cannot make it work. Hope someone tell me how to solve it. I declare the height and width, but the component seems doesn't take it. The JTextField and JButton with red & yellow background should be same height. Also the JTextField width is very long.

enter image description here

There is my code:

package MyPackage;

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.ComponentOrientation;
import javax.swing.JTextField;   

public class MainForm extends JFrame implements ActionListener  {

private PDFNotesBean PDFNotesBean = null;
private JMenuItem cascade = new JMenuItem("Cascade");
private  int numInterFrame=0;
private  JDesktopPane desktop=null;
private ArrayList<File> fileList=new  ArrayList<File>();
private static int categoryButtonWidth= 40;
private static int categoryTextFieldWidth=60;
private static int categoryHight=40;

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run()
        {               
            new MainForm();
        }
    });


}

public  MainForm(){
    super("Example");

    //it is equal to this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    // Name the JMenu & Add Items
    JMenu menu = new JMenu("File");
    menu.add(makeMenuItem("Open"));
    menu.add(makeMenuItem("Save"));
    menu.add(makeMenuItem("Quit"));


    // Add JMenu bar
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    //menuBar.add(menuWindow);
    setJMenuBar(menuBar);


    this.setMinimumSize(new Dimension(400, 500));        
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    desktop = new JDesktopPane();   
    this.setLayout(new BorderLayout());   


    setCategoryPanel();
    this.add(desktop, BorderLayout.CENTER);        
    setVisible(true);        

}


private void setCategoryPanel(){
 //set the color label category       

 JPanel panelCategory=new JPanel();             
 panelCategory.setLayout(new BoxLayout(panelCategory, BoxLayout.LINE_AXIS));

 JButton btnCategory_1=new JButton("");    
 btnCategory_1.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
 btnCategory_1.setBackground(Color.red);
 btnCategory_1.addActionListener(this);
 panelCategory.add(btnCategory_1);

 JTextField txtCategory_1 = new JTextField();
 txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
 panelCategory.add(txtCategory_1);


 JButton btnCategory_2=new JButton("");
 btnCategory_2.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));      
 btnCategory_2.setBackground(Color.YELLOW);
 btnCategory_2.addActionListener(this);
 panelCategory.add(btnCategory_2);

 JTextField txtCategory_2 = new JTextField( );
 txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
 panelCategory.add(txtCategory_2);

 this.add(panelCategory,  BorderLayout.NORTH);
 }

public void actionPerformed(ActionEvent e) {

    // Menu item actions
    String command = e.getActionCommand();      

    if (command.equals("Quit")) {
        System.exit(0);
    } else if (command.equals("Open")) {
        // Open menu item action
        JFileChooser fileChooser = new JFileChooser();     
        int returnVal = fileChooser.showOpenDialog(MainForm.this);
        if (returnVal ==  fileChooser.APPROVE_OPTION) {
            numInterFrame=numInterFrame+1;
            File file = fileChooser.getSelectedFile();
            fileList.add(file);
            AddNote(file);


            // Load file
        } else if (returnVal == JFileChooser.CANCEL_OPTION ) {
            // Do something else
        } 
    } 


     else if (command.equals("Save")) {
        // Save menu item action
        System.out.println("Save menu item clicked");
    }
}

private JMenuItem makeMenuItem(String name) {
    JMenuItem m = new JMenuItem(name);
    m.addActionListener(this);
    return m;
}

    private void AddNote(File file){        
        JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
                + file.getName(), true, true, true, true);      
       internalFrame.setBounds(0, 0, 600, 100);
       desktop.add(internalFrame);    

       PDFPanel p=new PDFPanel();
       JPanel e =p.getJPanel(file);     
       internalFrame.add(e, BorderLayout.CENTER);            
       internalFrame.setVisible(true);
       this.add(desktop, BorderLayout.CENTER);

      //resize the internal frame as full screen  
      Dimension size = desktop.getSize();
      int w = size.width ; 
      int h = size.height ; 
      int x=0;
      int y=0;
      desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user819774
  • 1,456
  • 1
  • 19
  • 48
  • 1
    Have you tried overriding `getPreferredSize()` for the component you want to resize? Although, if you want all your components having the same size, simply put them in a `GridLayout` – xav Mar 21 '14 at 22:15
  • 2
    1) *"set the size of the `JTextField` and `JButton`"* Which text field? Which button? For better help sooner, post a [MCTaRE](http://stackoverflow.com/help/mcve) (Minimal Complete Tested and Readable Example). .. – Andrew Thompson Mar 22 '14 at 00:58
  • 3
    .. 2) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement **or sizing** of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). Other ways to alter size: `JTextField` a) number of columns. b) font size. `JButton` a) font or icon size. b) insets/margin. – Andrew Thompson Mar 22 '14 at 00:59
  • @xav the row of button and textfield is on left to right and it shows on the frame 2/3 width. How can I do it? – user819774 Mar 25 '14 at 18:12
  • @user819774: Sorry I don't understand... – xav Mar 25 '14 at 18:20
  • @xav If I set it as GridLayout. I want the width of the row of the button and text field is 2/3 of JFrame width. How can I set it? – user819774 Mar 25 '14 at 20:02
  • You cannot, sorry. I really advice you to apply @AndrewThompson advices above. You should not try to set components size this way. – xav Mar 25 '14 at 22:30

1 Answers1

1

Don't use the setPreferredSize() method.

All Swing components will have a preferred size.

For a JTextField you can use:

JTextField textField = new JTextField(5);

to indication how many characters you want to display at one time.

For the JButton, the width is determined by the text you add to the button.

When you use a BoxLayout, the width of the components is increased to fill the available space.

Just use a FlowLayout (which is the default for a JPanel) and the components will be displayed at their preferred sizes.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • how can I make the button and text field form left to right. I added this code panelCategory.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT ), but all button and text fields in the center. – user819774 Mar 25 '14 at 17:47
  • I replace the setPreferredSize() to setSize and also modified the button like this JButton btnCategory_2=new JButton(" "). It isn't show the height as I want. I want the text field and button has the same height. Also how can I make the button and text field form left to right. I added this code panelCategory.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT ), but all button and text fields in the center. Thanks for your help – user819774 Mar 25 '14 at 18:11
  • ... u can just use a null layout and invoke ElementName.setBounds(x,y,w,h); – clockw0rk Aug 31 '20 at 22:44
  • @clockw0rk, Swing was designed to be used with layout managers. Don't use a null layout!!! – camickr Aug 31 '20 at 23:57