问题描述:

I have created a java program that shows a grid of buttons and labels and i want to know how to pit a constraint on the labels and buttons so they dont re-size when window is dragged out.. can anyone help please?

this is my gridlayout class

package JFrameTester;

import java.awt.Dimension;

import java.awt.GridLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

public class layout extends JFrame {

JButton button1,button2,button3;

JLabel label1,Label2,Label3;

public layout (){

setLayout(new GridLayout(2, 2));

button1 = new JButton ("button1");

add(button1);

label1 = new JLabel ("label1");

add(label1);

button2 = new JButton ("button1");

add(button2);

Label2 = new JLabel ("Label2");

add(Label2);

button3 = new JButton ("button1");

add(button3);

Label3 = new JLabel ("Label3");

add(Label3);

}

}

and this is my main class

public class JFrameTester {

/**

* @param args

*/

public static void main(String[] args) {

layout Lay = new layout();

Lay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Lay.setVisible(true);

// JFrame frame = new JFrame("BUY COMPUTER");

Lay.setSize(800, 600);

//frame.pack();

// frame.setVisible(true);

Lay.addWindowListener(new MyWindowListener());

}

}

网友答案:

Place the labels and buttons inside a JPanel, and then add that JPanel to your GridLayout. GridLayout automatically resizes components to fit the size of the cell they are placed in and when a JFrame is resized it will adjust the components size as needed. If you place them in JPanels only the JPanel in that cell will be resized, not the components.

EDIT

In addition to that it's Java practice to name all classes with an uppercase letter, your layout should be Layout. However, the name Layout does not accurately convey the purpose of class Layout as your class is not a layout, it's a JFrame. Perhaps LayoutFrame would be a better class name.

And (this is default Java practice) variables should be camelcase, beginning with a lowercase letter and subsequent words having a capital letter e.g. thisIsAVariable. Alternatively you could use underscores which is not normal Java practice, this_is_a_varaible. Given that in Java classes generally start with a capital letter and variables start with a lowercase letter the statement layout Lay = new layout(); looks very strange and a bit confusing at first glance.

相关阅读:
Top