how to stop panel / J Button /J TextField from resizing
I added a text field and a button to the panel and added it to the JFrame.But whenever I maximize the window the button also gets maximised I used setMaximumSize and MinimumSize but it doesnt work..Neither did the setBounds.The following code is what i tried out..If the resizing can be controlled thru setSize or set preferred sizeplease let me know how to use it..
thanks,,,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Demo
{
public static void buildGUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(1,1));
JButton button = new JButton("I'm a Swing button!");
pane.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
pane.add(button);
frame.getContentPane().add(pane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//thread safe
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
buildGUI();
}
});
}
}
>>But whenever I maximize the window the button also gets maximised
Its because of the layout manager, it all depends upon the layout manager you are using
>>I used setMaximumSize and MinimumSize but it doesnt work
Not all the Layout managers respect these preferredSize methods
>>Neither did the setBounds
setBounds will work perfectly only if you use cutom Layout manager-your own layout-for this, First you have to set the layout manager of the container/component as null by
urcomponent.setLayout(null); then you can use the setBounds(...)method
okay here i post two versions of the modified code
-ver1. check this if u want to use a layout manager
public static void buildGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JButton button = new JButton("I'm a Swing button!");
button.setPreferredSize(new Dimension(200,20));
pane.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
pane.add(button);
pane.setBorder(new javax.swing.border.LineBorder(Color.BLUE));
pane.setPreferredSize(new Dimension(300,60));
frame.getContentPane().add(pane,BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
--ver2. learn how to use custom layout
public static void buildGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
JButton button = new JButton("I'm a Swing button!");
pane.setLayout(null);
pane.add(button);
button.setBounds(20,20,200,60);
pane.setBorder(new javax.swing.border.LineBorder(Color.BLUE));
pane.setBounds(20,20,250,100);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(pane);
frame.setSize(300,300);
frame.setVisible(true);
}