【问题标题】:Java Swing FormattingJava Swing 格式
【发布时间】:2017-05-06 04:27:19
【问题描述】:

所以我正在做一个小型 Java Punnett Square 项目(提出了一个问题,该问题提供了更多关于它到底做什么的细节)。在问完最后一个问题后,我决定开始重写程序,因为它非常混乱和混乱。这是我想要的格式:

https://snag.gy/IsfbNQ.jpg

这是我的输出截图:

https://snag.gy/bcxykV.jpg

文本字段不在标签的右侧,我的计算按钮没有显示我的表格。

代码如下:

//imports

public class GeneticsGUI
{
   public static void main(String[] args) 
   {
       JFrame window = new JFrame("Genetics");
       JPanel panel = new JPanel(new GridLayout(25,2));

       JLabel o = new JLabel("Options:");
       panel.add(o);
       String[] options = new String[] {"2x2 Punnett Square", "4x4 Punnett Square"};
       JComboBox<String> list = new JComboBox<>(options);
       panel.add(list);


       String selected = (String) list.getSelectedItem();


       JLabel p1 = new JLabel("Parent 1:");
       JTextField par1 = new JTextField();
       JLabel p2 = new JLabel("Parent 1:");
       JTextField par2 = new JTextField();

       panel.add(p1,BorderLayout.WEST);
       panel.add(par1,BorderLayout.CENTER);
       panel.add(p2,BorderLayout.WEST);
       panel.add(par2,BorderLayout.CENTER);

       JButton submit = new JButton("Calculate");
       submit.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                if(e.getSource()==submit)
                {
                      String p1 = par1.getText();
                      String p2 = par2.getText();
                      if(selected == "2x2 Punnett Square")
                      {

                          String[][] mono = Genetics.monohybridPunett(p1, p2);
                          for(int row = 0; row<2 ; row++)
                          {
                              for(int col = 0; col<2; col++)
                              {
                                  mono[row][col] = "         "+ mono[row][col];
                              }
                          }
                          JTable table = new JTable(mono.length,mono.length);

                          table.setShowGrid(true);

                          for(int i = 0; i<mono.length; i++)
                              for(int j = 0; j<mono.length; j++)
                                  table.setValueAt(mono[i][j], i, j);

                          DefaultTableCellRenderer t = new DefaultTableCellRenderer();
                          t.setHorizontalTextPosition(DefaultTableCellRenderer.CENTER);
                          t.setVerticalTextPosition(DefaultTableCellRenderer.CENTER);

                          table.setSize(300, 300);
                          table.isCellEditable(0,0);
                          table.setRowHeight(100);
                          panel.add(table,BorderLayout.EAST);;
                          panel.revalidate();
                      }
                      else if(selected == "4x4 Punnett Square")
                      {


                          String[][] di = Genetics.dihybridPunett(p1, p2);
                          JTable table = new JTable(di.length,di.length);
                          table.setShowGrid(true);

                          DefaultTableModel model = new DefaultTableModel(di,new Object[]{"AaBb","AaBb","",""});
                          table.isCellEditable(0, 0);
                          table.setModel(model);
                          table.setRowHeight(100);

                          table.getColumnModel().getColumn(0).setPreferredWidth(100);
                          table.getColumnModel().getColumn(1).setPreferredWidth(100);
                          table.getColumnModel().getColumn(2).setPreferredWidth(100);
                          table.getColumnModel().getColumn(3).setPreferredWidth(100);
                          panel.add(table,BorderLayout.CENTER);
                          panel.revalidate();
                      }
                }
            }
          });

       panel.add(submit);

       window.add(panel);
       window.setSize(800, 800);
       window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
       window.setVisible(true);
   }
}

再说一次,我并不是 GUI 或 Swing 方面的专家,所以想知道我需要做些什么来解决这个格式问题。

编辑:

这是我当前的 GridBagLayout 实现代码。

   JFrame window = new JFrame("Genetics");
   JPanel panel = new JPanel();

   panel.setLayout(new GridBagLayout());
   GridBagConstraints c = new GridBagConstraints();

   JLabel o = new JLabel("Options:");

   c.fill = GridBagConstraints.HORIZONTAL;
   c.gridx = 0;
   c.gridy = 0;
   c.weightx = 0;
   panel.add(o, c);

   String[] options = new String[] {"2x2 Punnett Square", "4x4 Punnett Square"};
   JComboBox<String> list = new JComboBox<>(options);
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 1;
   c.gridx = 1;
   c.gridy = 0;
   panel.add(list, c);
   String selected = (String) list.getSelectedItem();

   JLabel p1 = new JLabel("Parent 1:");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.weighty = 1;
   c.insets = new Insets(40,0,0,0);
   c.gridx = 0;
   c.gridy = 1;
   panel.add(p1, c);

   JTextField par1 = new JTextField();
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 1;
   c.gridy = 1;
   panel.add(par1, c);

   JLabel p2 = new JLabel("Parent 2:");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.insets = new Insets(0,0,0,0);
   c.weightx = 0.5;
   c.gridx = 0;
   c.gridy = 2;
   panel.add(p2, c);

   JTextField par2 = new JTextField();
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 1;
   c.gridy = 2;
   panel.add(par2, c);



   JButton submit = new JButton("Calculate");
   c.fill = GridBagConstraints.HORIZONTAL;
   c.weightx = 0.5;
   c.gridx = 0;
   c.gridy = 3;
   c.anchor = GridBagConstraints.LINE_START;
   panel.add(submit, c);

【问题讨论】:

  • 顺便说一句...selected == "2x2 Punnett Square"不是how to compare strings
  • 将 JPanel 的布局设置为 GridLayout,然后在向 JPanel 添加组件时使用 BorderLayout 常量是没有意义的,这表明您忽略了先查看教程。要点 1)查看教程,2)嵌套 JPanel,每个 JPanel 都使用自己的布局管理器,以实现您的目标。
  • 对顶部的 JPanel 使用 GridBagLayout,其中包含标签和 JTextFields,对整个 GUI 使用 BorderLayout,添加顶部的 JPanel BorderLayout.PAGE_START。在主 JPanel、BorderLayout.CENTER\ 中添加图表或 JTable,或其他任何内容(可能在 JScrollPane 中)
  • This link 展示了我如何处理 GridBagLayout GUI。

标签: java swing user-interface


【解决方案1】:

您正在使用 50 个单元格 (25x2) GridLayout 创建您的 JPanel,然后使用 BorderLayout 常量向该 JPanel 添加组件。

GridLayout 不像BorderLayout 那样使用常量,它只是添加组件,每个单元格按添加顺序添加一个。查看How to Use GridLayout,快速了解如何正确使用GridLayout

对于您想要的 UI 布局,您可能需要使用 GridBagLayout (How to Use GridBagLayout) 或 SpringLayout (How to Use SpringLayout) 之类的东西。两者都是强大/灵活的布局管理器,但它们也可以说是 Swing 中可用的最复杂的布局管理器。

除非您打算精通 Swing GUI 布局的细节,否则我强烈建议您使用 NetBeans 之类的东西来生成布局(请参阅:Designing a Swing GUI in NetBeans IDE

编辑

以下是使用GridBagLayout 的布局示例。我添加了额外的面板 optionsPanelparent1Panelparent2Panel 来帮助对组件进行分组和对齐。

我还添加了一个 resultsPanel 来容纳生成的 Punnett 广场。由于目前没有任何内容,因此我添加了一个红线边框以使面板可见。

这并没有完全复制你草图上的布局,但它很接近,我认为你应该能够从这里弄乱约束来改进布局,使其完全符合你的愿望.

遗传学GUI

import javax.swing.*;
import java.awt.*;

public class GeneticsGUI {
    public static void main(String[] args) {

        boolean debug = true;
        JFrame window = new JFrame("Genetics");
        JPanel panel = new JPanel();

        panel.setLayout(new GridBagLayout());

        JPanel optionsPanel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 0, 0);
        panel.add(optionsPanel, c);

        JLabel optionsLabel = new JLabel("Options:");

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        optionsPanel.add(optionsLabel, c);

        String[] options = new String[]{"2x2 Punnett Square", "4x4 Punnett Square"};
        JComboBox<String> optionsCombo = new JComboBox<>(options);

        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        optionsPanel.add(optionsCombo, c);

        String selected = (String) optionsCombo.getSelectedItem();

        JPanel parent1Panel = new JPanel(new GridBagLayout());
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 5, 0);
        panel.add(parent1Panel, c);

        JLabel p1 = new JLabel("Parent 1:");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        parent1Panel.add(p1, c);

        JTextField par1 = new JTextField();
        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        parent1Panel.add(par1, c);

        JPanel parent2Panel = new JPanel(new GridBagLayout());
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 0, 5, 0);
        panel.add(parent2Panel, c);

        JLabel p2 = new JLabel("Parent 2:");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(0, 5, 0, 5);
        parent2Panel.add(p2, c);

        JTextField par2 = new JTextField();
        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 0;
        c.weightx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        parent2Panel.add(par2, c);

        JButton submit = new JButton("Calculate");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 3;
        c.weightx = 1;
        //           c.weighty = .1;
        c.insets = new Insets(0, 5, 0, 0);
        c.anchor = GridBagConstraints.LINE_START;
        panel.add(submit, c);

        JPanel resultsPanel = new JPanel();
        resultsPanel.setBorder(BorderFactory.createLineBorder(Color.red));
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 4;
        c.weightx = 1;
        c.weighty = 1;
        c.insets = new Insets(5, 5, 5, 5);
        c.anchor = GridBagConstraints.LINE_START;
        c.fill = GridBagConstraints.BOTH;
        panel.add(resultsPanel, c);

        window.add(panel);
        window.setSize(800, 800);
        window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        window.setVisible(true);
    }
}

【讨论】:

  • 谢谢,不知道 NetBeans IDE 有内置的。我现在正在尝试使用 GridBagLayout,我正在慢慢掌握它。我可能会在某个时候使用 NetBeans IDE 来帮助我,因为我确信我会在某个时候遇到障碍。感谢您的提示!
  • @user3238399:虽然这个答案可能建议您学习和使用 NetBeans 拖放来创建复杂的 GUI,虽然这会起作用,但您不会理解 NetBeans 和 Swing 的底层布局正在使用,因此当您需要超越 NetBeans 的能力时,例如如果您想在程序运行过程中更改布局或添加组件,最终会碰壁。因此,您最好学习和使用布局管理器。
  • @user3238399:您可以在此处找到布局管理器教程:Layout Manager Tutorial,您可以在此处找到 Swing 教程和其他 Swing 资源的链接:Swing Info
  • @HovercraftFullOfEels 我 100% 同意拖放布局编辑器的局限性。但是,我也倾向于认为 GridBagLayout 足够复杂,不建议一次性学习。基于这个问题,我推测 OP 不一定要掌握挥杆布局管理器的使用。因此,我建议改用拖放编辑器。 :)
  • @HovercraftFullOfEels 是的,在尝试了 NetBeans 之后,我认为它对我来说完全没有意义。代码变得非常难以阅读并且非常反直觉(显然是由程序完成的)。我正在使用 GridBagLayout 并且到目前为止取得了一些成功。我正在努力使第一个列网格空间更小,并且想知道如何将文本字段对齐到标签旁边。这是它现在的样子:snag.gy/lZwiSH.jpg
猜你喜欢
  • 2017-12-05
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 2015-01-03
相关资源
最近更新 更多