Adding a JLabel in relative position to buttons

我的梦境 提交于 2019-12-11 18:14:44

问题


OK, this is the relative code I have so far.

  for (int i = gameLines - 1; i > 0; i--)
  {
     for (int j = 0; j < i; j++)
     {
        JButton jButton = new JButton();
        jButton.setSize(buttonWidth, buttonHeight);
        jButton.setText("" + line[i].charAt(j));
        int x = ((buttonWidth / 2 * gameLines + 1) - (buttonWidth / 2 * i) + (buttonWidth * j));
        int y = (gameLines - (i + 1)) * buttonHeight;
        jButton.setLocation(x, y);
        panel.add(jButton);
        button[i][j] = jButton;
        button[i][j].setActionCommand(Integer.toString(i) + "." + Integer.toString(j));
        button[i][j].addActionListener(this);
     }
  }

The code creates and places all my buttons where I want them to be. This took me a while to figure out. I'm originally an AppleSoft BASIC programmer, I'm sorry about the i & j variable names.

Now for the fun. To the right of the bottom 3 rows of buttons, I want to place a jLabel. The right edge of the jLabel is to align with the right edge of the rightmost button in the top row. The text in each will be right justified, ending with a : and an up-to 4 digit number.

I'm thinking I can simply calculate the position like I did the button positions. The text, I was going to add based on a switch/case.

I'm having an trouble understanding JLabels, so I'd appreciate ANY help I can get.

My current thoughts are: to be inserted after the j loop

if (i < 4)
{
    JLabel jLable = new JLabel();
    JLabel.setSize(???, buttonHeight);
    Calculate value of X;
    int y = (gameLines - (i +1)) * buttonHeight;
    jLabel.setLocation(x,y);
    switch (i)
    {
       case 3:
          jLabel.setText("Buttons Clicked: " + buttonsClicked);
          break;
       case 2:
          etc.
    }
    panel.add(jLabel);
}

HELP please


回答1:


For a bag of reasons, I would avoid absolute layouts. The moment you run it on some other PC, the whole thing begins to fall apart, instead, you should rely on the layout manager API available in Swing.

The following example uses a compound layout approach. Each row is it's own container (JPanel) and each row is then added to the main panel.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ButtonPyramid {

    public static void main(String[] args) {
        new ButtonPyramid();
    }

    public ButtonPyramid() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private String[] lines;

        public TestPane() {
            lines = new String[]{
                "AAFITQPNXBE",
                "?AXOPKMSUR",
                "TGKFREUDI",
                "DFEAAEOY",
                "ZDE?VIF",
                "G@RMLC",
                "YUJGO",
                "NSCP",
                "KO@",
                "MI",
                "Y",
                "B",
            };

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.gridy = 1;
            gbc.gridx = 0;
            for (String line : lines) {
                JPanel panel = new JPanel(new GridBagLayout());
                for (char ch : line.toCharArray()) {
                    JButton btn = new JButton(Character.toString(ch));
                    btn.setMargin(new Insets(10, 10, 10, 10));
                    panel.add(btn);
                }
                add(panel, gbc);
                gbc.gridy++;
            }
            JLabel label = new JLabel(":1234");
            gbc.gridy -= 3;
            gbc.gridx++;
            gbc.anchor = GridBagConstraints.NORTH;
            add(label, gbc);
        }
    }

}

If you would prefer the text not to take up another column, there is a little trick you can try, change the label layout constraints to look like the following instead...

JLabel label = new JLabel(":1234");
gbc.gridy -= 3;
gbc.anchor = GridBagConstraints.NORTHEAST;
add(label, gbc);

Check out Laying out Components within a Container for ideas and details

           lines = new char[][]{...};

           for (int outter = 0; outter < lines.length; outter++) {
                JPanel panel = new JPanel(new GridBagLayout());
                for (int inner = 0; inner < lines[outter].length) {
                    char ch = lines[outter][inner];
                    JButton btn = new JButton(Character.toString(ch));
                    btn.setMargin(new Insets(10, 10, 10, 10));
                    panel.add(btn);
                }
                add(panel, gbc);
                gbc.gridy++;
            }


来源:https://stackoverflow.com/questions/21618866/adding-a-jlabel-in-relative-position-to-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!