Регулировка кнопок сверху вниз в GUI Java Swing - PullRequest
0 голосов
/ 03 апреля 2020

приведенный ниже код является GUI для преобразования шестнадцатеричного значения в десятичное и двоичное. Проблема в том, что кнопки печатаются сверху, я также приложил некоторое изображение для справки о том, как я хочу, чтобы результат был.

class MyFrames implements ActionListener
{

    JFrame DancingFinchFrame;

    static JLabel NewLabel, DecimalValue, BinaryValue, FinchSpeed;
    static JTextField textField, DecimalText, BinaryText, SpeedText;
    static JButton Convert, Dance;
    static String Hexadecimal, Binary;
    static int Decimal, Speed;


    MyFrames()  

    { 
        // creates a frame
        DancingFinchFrame=new JFrame("Calculator");
        DancingFinchFrame.setTitle("Dancing Finch");
        DancingFinchFrame.setSize(320, 280);
        DancingFinchFrame.setLocationRelativeTo(null);
        DancingFinchFrame.setResizable(false);
        DancingFinchFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        NewLabel = new JLabel("Please enter a hexadecimal value");
        NewLabel.setVerticalAlignment(SwingConstants.TOP);
        NewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        NewLabel.setFont(new Font("Arial", Font.BOLD, 15));

        textField = new JTextField();
        textField.setHorizontalAlignment(SwingConstants.CENTER);
        textField.setColumns(20);

        Convert = new JButton("CONVERT");       
        Convert.setBounds(10, 400, 100, 40);


        DecimalValue = new JLabel("Decimal Value is ");
        DecimalValue.setVisible(false);
        DecimalValue.setFont(new Font("Arial", Font.BOLD, 15));
        DecimalValue.setVisible(false);

        DecimalText = new JTextField();
        DecimalText.setEditable(false);
        DecimalText.setVisible(false);
        DecimalValue.setLabelFor(DecimalText);
        DecimalText.setColumns(10);

        BinaryValue = new JLabel("Binary Value is ");
        BinaryValue.setVisible(false);
        BinaryValue.setFont(new Font("Arial", Font.BOLD, 15));
        BinaryValue.setToolTipText("");

        BinaryText = new JTextField();
        BinaryText.setEditable(false);
        BinaryText.setVisible(false);
        BinaryValue.setLabelFor(BinaryText);
        BinaryText.setColumns(10);

        FinchSpeed = new JLabel("Finch Speed is ");
        FinchSpeed.setVisible(false);
        FinchSpeed.setFont(new Font("Arial", Font.BOLD, 15));

        SpeedText = new JTextField();
        SpeedText.setVisible(false);
        SpeedText.setEditable(false);
        FinchSpeed.setLabelFor(SpeedText);
        SpeedText.setColumns(10);

        Dance = new JButton("DANCE");
        Dance.setVisible(false);**


        // creates the panel 
        JPanel mypanel = new JPanel();

        //adds action listeners and initialises the event handling for the buttons
        Convert.addActionListener(this); 
        Dance.addActionListener(this); 
        textField.addActionListener(this);

        // adds elements to the panel 
        mypanel.add(Convert); 
        mypanel.add(Dance); 
        mypanel.add(NewLabel); 
        mypanel.add(textField); 
        mypanel.add(DecimalValue); 
        mypanel.add(DecimalText); 
        mypanel.add(BinaryValue); 
        mypanel.add(BinaryText); 
        mypanel.add(FinchSpeed); 
        mypanel.add(SpeedText); 

        mypanel.setBackground(Color.white); 

        // adds panel to frame 
        DancingFinchFrame.add(mypanel); 
        DancingFinchFrame.setSize(320, 280); 
        DancingFinchFrame.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {

        Hexadecimal = textField.getText();
        Decimal = DecimalConverter.HexaToDecimal(Hexadecimal);
        Binary = BinaryConverter.HexaToBinary(Hexadecimal);
        Speed = SpeedCalculator.Speed(Decimal);


        if(e.getSource()==Convert)

        {
            if (Decimal >= 144 && Decimal <= 255)

            {
                DecimalValue.setVisible(true);
                DecimalText.setVisible(true);
                BinaryValue.setVisible(true);
                BinaryText.setVisible(true);
                Dance.setVisible(true);
                FinchSpeed.setVisible(true);
                SpeedText.setVisible(true);
                DecimalText.setText(""+ Decimal);
                BinaryText.setText(""+ Binary);
                SpeedText.setText("" + Speed);
            }
            else
            {
                try
                {
                    JOptionPane.showMessageDialog(null, "Please enter a valid input!", "ERROR", JOptionPane.ERROR_MESSAGE);
                }
                catch (Exception ne) 
                {
                    ne.printStackTrace();
                }
            }
        }


        else if (e.getSource()==Dance)  

        {
            int decimal = Integer.parseInt(SpeedText.getText());
            String binary = BinaryText.getText();

            FinchCommands Command = new FinchCommands();
            Command.Dance(decimal, binary);
        }
    }

    public JFrame getDancingFinchFrame() 

    {
        return DancingFinchFrame;
    }


}

Проблема в том, что кнопка конвертировать / танцевать печатается на top

Buttons get printed on top

Это то, что я хочу получить

the result that i want

Спасибо Вы заранее !!

Ответы [ 2 ]

1 голос
/ 03 апреля 2020

Этот макет:

enter image description here

Может быть произведен с использованием этого кода:

JPanel ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(10,40,10,40));

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 2;
gbc.insets = new Insets(5,5,5,5);

ui.add(new JLabel("Please enter a hexadecimal value"), gbc);
gbc.gridy = 1;
ui.add(new JTextField("90", 10), gbc);
gbc.gridy = 2;
ui.add(new JButton("Convert"), gbc);
gbc.gridy = 6;
ui.add(new JButton("Dance"), gbc);

gbc.gridwidth = 1;
String[] name = {"Decimal Value", "Binary Value", "Finch Speed"};
for (int ii=0; ii<3; ii++) {
    gbc.gridy = ii+3;
    gbc.gridx = 0;
    ui.add(new JLabel(name[ii]), gbc);
    gbc.gridx = 1;
    ui.add(new JTextField(6), gbc);
}
1 голос
/ 03 апреля 2020

Прежде всего, вы объявляете переменные с первой заглавной буквой, которая не является стандартной и может быть трудной для обработки, когда ваша программа будет расти или через несколько лет делать другие вещи.

Во-вторых, вы делаете не использовать макет. Вы используете FlowLayout, потому что он кажется по умолчанию. Но с помощью простого BorderLayout вы сможете определять области для ваших элементов управления и полей.

Чтобы глубже изучить и научиться их использовать, я предоставлю вам хорошую ссылку: https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html!

...