开发者

How the swing's BoxModel works?

Let's say I would like to create a simple calculator. It consists of 3 fields. Text field to show result, field with checkb开发者_JAVA技巧oxes to select system and field with numbers.

What kind of component should I use for each element ? How can I position elements in my window ? How can I position elements inside component (ie checkboxes) ?

This is what I'm trying to achieve.

http://img28.imageshack.us/img28/7691/lab8c.jpg


I would use

  • JTextField for the number-window
  • JRadioButton for the radio buttons, and
  • JButton for the buttons.

The layout of the components should be deferred to a so called layout-manager. (Have a look at Using Layout Managers. In this case a GridLayout and/or a GridBagLayout would do fine.

This code should get you started:

import java.awt.*;

import javax.swing.*;


public class FrameTest {

    public static void main(String[] args) {
        final JFrame f = new JFrame("Frame Test");

        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        panel.add(new JTextField(), gbc);


        JPanel numSysPanel = new JPanel(new GridLayout(1, 3));
        numSysPanel.setBorder(BorderFactory.createTitledBorder("Number System"));
        numSysPanel.add(new JRadioButton("oct"));
        numSysPanel.add(new JRadioButton("dec"));
        numSysPanel.add(new JRadioButton("hex"));
        panel.add(numSysPanel, gbc);

        JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
        for (int i = 0; i < 16; i++)
            buttons.add(new JButton("" + i));
        panel.add(buttons, gbc);

        f.setContentPane(panel);
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

How the swing's BoxModel works?


First off, you start with determining, which LayoutManager you should use, to arrange your three fields. GridBagLayout will definitely do what you want, but is quite hard to program. You could try to get away with the simpler BorderLayout, which will make your application look odd, while resizing. You can use GroupLayout too. BoxLayout, GridLayout and FlowLayout are not what you want to use. Now you have a lot of options, to lay out you top elements.

Use a JTextField for the result. Use JCheckBox for the checkboxes, which you put insider a JPanel with an etched border (via JPanel.setBorder(BorderFactory.createEtchedBorder())) and a FlowLayout. Don't forget to put the checkboxes in a CheckboxGroup. Last but not least use a JPanel to group the JButtons for the, uhh, buttons. Use a GridLayout (5 rows, 4 columns) to arrange these buttons.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜