سؤال

I am trying to create a form manually with code rather than the designer, I have already created using the designer.

enter image description here

This is the manual code that I came up with so far but I am having problem aligning the label and textfield side by side

mport java.awt.*;
import javax.swing.*;
/**
 *
 * @author jackandjill
 */
public class summinup_copy extends JFrame
{
    private JLabel lblTitle, lblOctal, lblDecimal, lblMessage ;

private JTextField txtOctal, txtDecimal;

private JButton calculate_btn;




public  summinup_copy()       

{

JPanel panel = (JPanel)this.getContentPane();

panel.setLayout(new BorderLayout());

JPanel panCentre = new JPanel();

panCentre.setLayout(new GridLayout(3,3));

lblTitle = new JLabel("Area of Triangle");

lblTitle.setFont(new Font("Arial", 1, 20));

lblTitle.setHorizontalAlignment(JLabel.CENTER);

lblOctal = new JLabel("Octal");

lblOctal.setHorizontalAlignment(JLabel.CENTER) ;

//lblDecimal = new JLabel("Decimal");
//
//lblDecimal.setHorizontalAlignment(JLabel.CENTER);

lblMessage = new JLabel("Result will be displayed here");

lblMessage.setForeground(Color.red);

lblMessage.setHorizontalAlignment(JLabel.CENTER);

txtOctal = new JTextField("0", 5);

txtOctal.setHorizontalAlignment(JLabel.CENTER); 
//txtDecimal = new JTextField("0", 5);
//
//txtDecimal.setHorizontalAlignment(JLabel.CENTER);

calculate_btn = new JButton("Calculate Area");



//AHandlerClass aListener = new AHandlerClass() ;

//btnOtoD.addActionListener(aListener);

//btnDtoO.addActionListener(aListener);

panCentre.add(lblOctal);

//panCentre.add(lblDecimal);

panCentre.add(txtOctal);

//panCentre.add(txtDecimal);

panCentre.add(calculate_btn);

//panCentre.add(btnDtoO);

panel.add(lblTitle, BorderLayout.NORTH);

panel.add(lblMessage,BorderLayout.SOUTH);


panel.add(panCentre, BorderLayout.CENTER);

}

public static void main(String args[]) {

summinup_copy myGui = new summinup_copy();

myGui.setTitle("Bharath");

myGui.setSize(400, 200);

myGui.setVisible(true);
}

}
هل كانت مفيدة؟

المحلول

As you have already figured out, you have to use LayoutManagers when coding a Swing GUI by hand. Here are some links that can help you figure out which LayoutManager is appropriate for a given look:

http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

In order to place a JLabel next to a JTextField or other component, I usually use GridLayout or GridBagLayout. I find that it takes a lot of trial and error trying to get components to look the way I want. Often you have to have layers of embedded JPanels to get it just right.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top