Please have a look the following code
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GUI extends JFrame
{
private JButton open, process;
private JLabel center;
private JScrollPane scroll;
private Box box;
private IplImage image;
public FirstGUI()
{
open = new JButton("Open Image");
open.setPreferredSize(new Dimension(70,20));
open.setMaximumSize(new Dimension(100,20));
open.addActionListener(new OpenImageAction());
process = new JButton("Process");
process.setPreferredSize(new Dimension(100,20));
process.setMinimumSize(new Dimension(100,20));
process.addActionListener(new ProcessAction());
System.out.println("Open Size: "+open.getSize()+" Process size: "+process.getSize());
box = new Box(BoxLayout.Y_AXIS);
box.add(open);
box.add(process);
center = new JLabel();
scroll = new JScrollPane(center);
getContentPane().add(box,"West");
getContentPane().add(scroll,"Center");
this.setSize(300,300);
this.pack();
this.validate();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new GUI();
}
catch(java.lang.Exception e)
{
JOptionPane.showMessageDialog(null,"GUI Error");
}
}
I want to make all the buttons in same size. In here, first one is wider than the second one. I need same width ans hight for both. As you can see, I have used all the availables like setPrefferedSize(), setMaximumSize(), setMinimumSize(), but it is still not working properly. Please help!
Here is one way to achieve this using a
GridLayout. I also introduced an additionalJPanelso that the buttons are not stretched when theJFrameis resized and I chose theGridBagLayoutfor it so that it will center the button panel vertically. There are definitely other ways to solve your issue.One thing you should try to avoid is to force preferred/maximum/minimum sizes. Delegate this to the L&F and the LayoutMananager’s.
If you call
pack()on aJFrame, it is useless to set its size previously, aspack()will change that anyway. Try to make the call tosetVisible(true);the last line of your GUI initialization.If you want to understand properly how layout, positioning, sizing, etc… works in Swing, I would strongly recommend to read the tutorial on LayoutManager’s.