Re: JButton question



Z.K. wrote:
I have a simple java gui that I wrote which adds 3 buttons and some
text. It seems to work, but the buttons seem like they are all
different sizes. How to I get them to be all the same size. I tried
setSize(), but that did not seem to work. My code is below.

Z.K.


code:

import javax.swing.*;
import java.awt.*;

public class NotHelloWorld
{
public static void main(String[] args)
{
NotHelloWorldFrame frame = new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

}

class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
NotHelloWorldPanel panel = new NotHelloWorldPanel();
add(panel);


}

public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}

class NotHelloWorldPanel extends JPanel
{

public NotHelloWorldPanel()
{
NotHelloWorldButtonPanel bpanel = new NotHelloWorldButtonPanel();
add(bpanel);

}
public void paintComponent(Graphics g)
{
g.drawString("Not a Hello World program", MESSAGE_X, MESSAGE_Y);


}

public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;

}

class NotHelloWorldButtonPanel extends JPanel
{

public NotHelloWorldButtonPanel()
{
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");

//redButton.setSize(5,10);
//yellowButton.setSize(5,10);
//blueButton.setSize(5,10);

add(yellowButton);
add(blueButton);
add(redButton);



}

}
At times I use:
Dimension dim = new Dimension(( 90,26 );
yellowButton.setPreferredSize( dim );
yellowButton.setMaximumSize( dim );
yellowButton.setMinimumSize( dim );

And yes use a layout manager. I usually use the GridBagLayout manager
and set any resize constraints to NONE. This way the button does not
stretch to fill its horizontal space or change size when you resize the
window. Of course this is really meant to set a minimum and maximum
size for your buttons,

Rich
.



Relevant Pages

  • Re: JButton question
    ... NotHelloWorldFrame frame = new NotHelloWorldFrame; ... class NotHelloWorldFrame extends JFrame ... public static final int DEFAULT_HEIGHT = 200; ... class NotHelloWorldPanel extends JPanel ...
    (comp.lang.java)
  • JButton question
    ... NotHelloWorldFrame frame = new NotHelloWorldFrame; ... class NotHelloWorldFrame extends JFrame ... public static final int DEFAULT_HEIGHT = 200; ... class NotHelloWorldPanel extends JPanel ...
    (comp.lang.java)