Google Tag Manager

Showing posts with label GridBagLayout. Show all posts
Showing posts with label GridBagLayout. Show all posts

2019/04/25

aterai

Use the GridBagLayout to layout the JButton like a keyboard

Code

private static final String[][] KEYS = {
  {"`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "BS"},
  {"Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "\\", ""},
  {"Ctrl", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "Enter", ""},
  {"Shift", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "", "↑"},
  {"Fn", "Alt", "                             ", "Alt", "←", "↓", "→"}
};

private static Component makeKeyboardPanel() {
  JPanel keyboard = new JPanel(new GridBagLayout());

  GridBagConstraints c = new GridBagConstraints();
  c.fill = GridBagConstraints.BOTH;
  c.gridy = 50;
  for (int i = 0; i < KEYS[0].length * 2; i++) {
    c.gridx = i;
    keyboard.add(Box.createHorizontalStrut(KeyButton.SIZE));
  }

  for (int row = 0; row < KEYS.length; row++) {
    c.gridx = 0;
    c.gridy = row;
    for (int col = 0; col < KEYS[row].length; col++) {
      String key = KEYS[row][col];
      int len = key.length();
      c.gridwidth = len > 10 ? 14
                  : len > 4  ? 4
                  : len > 1  ? 3
                  : len == 1 ? 2 : 1;
      if (key.isEmpty()) {
        keyboard.add(Box.createHorizontalStrut(KeyButton.SIZE), c);
      } else {
        keyboard.add(new KeyButton(key, len <= 2), c);
      }
      c.gridx += c.gridwidth;
    }
  }
  EventQueue.invokeLater(() -> SwingUtilities.updateComponentTreeUI(keyboard));
  return keyboard;
}

References

2014/10/29

aterai

JMenuItem accelerator text alignment

Code

RightAcc

public static void paintAccText(
  Graphics g, MenuItemLayoutHelper lh, MenuItemLayoutHelper.LayoutResult lr,
  Color disabledForeground, Color acceleratorForeground,
  Color acceleratorSelectionForeground) {
  if (!lh.getAccText().equals("")) {
    ButtonModel model = lh.getMenuItem().getModel();
    g.setFont(lh.getAccFontMetrics().getFont());
    if (!model.isEnabled()) {
      // *** paint the accText disabled
      if (disabledForeground != null) {
        g.setColor(disabledForeground);
        SwingUtilities2.drawString(
          lh.getMenuItem(), g, lh.getAccText(),
          lr.getAccRect().x,
          lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
      } else {
        g.setColor(lh.getMenuItem().getBackground().brighter());
        SwingUtilities2.drawString(
          lh.getMenuItem(), g, lh.getAccText(),
          lr.getAccRect().x,
          lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
        g.setColor(lh.getMenuItem().getBackground().darker());
        SwingUtilities2.drawString(
          lh.getMenuItem(), g, lh.getAccText(),
          lr.getAccRect().x - 1,
          lr.getAccRect().y + lh.getFontMetrics().getAscent() - 1);
      }
    } else {
      // *** paint the accText normally
      if (model.isArmed() ||
          (lh.getMenuItem() instanceof JMenu && model.isSelected())) {
        g.setColor(acceleratorSelectionForeground);
      } else {
        g.setColor(acceleratorForeground);
      }
      SwingUtilities2.drawString(
        lh.getMenuItem(), g, lh.getAccText(),
        //lr.getAccRect().x, //++++++++++++++++++++
        lh.getViewRect().x + lh.getViewRect().width
        - lh.getMenuItem().getIconTextGap() - lr.getAccRect().width,
        //++++++++++++++++++++
        lr.getAccRect().y + lh.getAccFontMetrics().getAscent());
    }
  }
}

EastAcc

public static void paintAccText(
private static JMenuItem makeMenuItem2(JMenuItem mi) {
  final JLabel label = new JLabel(MenuItemUIHelper.getAccText(mi, "+"));
  label.setOpaque(true);
  JMenuItem item = new JMenuItem(mi.getText()) {
    @Override public void updateUI() {
      super.updateUI();
      if (getUI() instanceof WindowsMenuItemUI) {
        setUI(new WindowsMenuItemUI() {
          @Override protected void installDefaults() {
            super.installDefaults();
            acceleratorForeground = UIManager.getColor("MenuItem.background");
            acceleratorSelectionForeground = acceleratorForeground;
          }
        });
      }
    }
  };

  GridBagConstraints c = new GridBagConstraints();
  item.setLayout(new GridBagLayout());
  c.gridheight = 1;
  c.gridwidth  = 1;
  c.gridy = 0;
  c.gridx = 0;
  c.insets = new Insets(0, 0, 0, 4);

  c.weightx = 1d;
  c.fill = GridBagConstraints.HORIZONTAL;
  item.add(Box.createHorizontalGlue(), c);
  c.gridx = 1;
  c.fill = GridBagConstraints.NONE;
  c.weightx = 0d;
  c.anchor = GridBagConstraints.EAST;
  item.add(label, c);

  item.setMnemonic(mi.getMnemonic());
  item.setAccelerator(mi.getAccelerator());
  return item;
}

References

2014/09/29

aterai

Change a layout of a JPopupMenu to use their iconic menu items

Code

JPopupMenu popup = new JPopupMenu();
GridBagConstraints c = new GridBagConstraints();
popup.setLayout(new GridBagLayout());
c.gridheight = 1;

c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;

c.gridwidth = 1;
c.gridy = 0;
c.gridx = 0; popup.add(makeButton("\u21E6"), c);
c.gridx = 1; popup.add(makeButton("\u21E8"), c);
c.gridx = 2; popup.add(makeButton("\u21BB"), c);
c.gridx = 3; popup.add(makeButton("\u2729"), c);

c.gridwidth = 4;
c.gridx = 0;
c.insets = new Insets(2, 0, 2, 0);
c.gridy = 1; popup.add(new JSeparator(), c);
c.insets = new Insets(0, 0, 0, 0);
c.gridy = 2; popup.add(new JMenuItem("aaaaaaaaaa"), c);
c.gridy = 3; popup.add(new JPopupMenu.Separator(), c);
c.gridy = 4; popup.add(new JMenuItem("bbbb"), c);
c.gridy = 5; popup.add(new JMenuItem("ccccccccccccccccccccc"), c);
c.gridy = 6; popup.add(new JMenuItem("dddddddddd"), c);
final Icon icon = new SymbolIcon(symbol);
JMenuItem b = new JMenuItem() {
  private final Dimension d = new Dimension(icon.getIconWidth(), icon.getIconHeight());
  @Override public Dimension getPreferredSize() {
    return d;
  }
  @Override public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Dimension cd = getSize();
    Dimension pd = getPreferredSize();
    int offx = (int) (.5 + .5 * (cd.width  - pd.width));
    int offy = (int) (.5 + .5 * (cd.height - pd.height));
    icon.paintIcon(this, g, offx, offy);
  }
};
b.setOpaque(true);

References

2013/11/25

aterai

Cut copy paste buttuns in the JMenuItem

Code

private static JMenuItem makeEditMenuItem(final JPanel edit) {
  JMenuItem item = new JMenuItem("Edit") {
    @Override public Dimension getPreferredSize() {
      Dimension d = super.getPreferredSize();
      d.width += edit.getPreferredSize().width;
      d.height = Math.max(edit.getPreferredSize().height, d.height);
      return d;
    }
    @Override protected void fireStateChanged() {
      setForeground(Color.BLACK);
      super.fireStateChanged();
    }
  };
  item.setEnabled(false);

  GridBagConstraints c = new GridBagConstraints();
  item.setLayout(new GridBagLayout());
  c.gridheight = 1;
  c.gridwidth  = 1;
  c.gridy = 0;
  c.gridx = 0;

  c.weightx = 1.0;
  c.fill = GridBagConstraints.HORIZONTAL;
  item.add(Box.createHorizontalGlue(), c);
  c.gridx = 1;
  c.fill = GridBagConstraints.NONE;
  c.weightx = 0.0;
  c.anchor = GridBagConstraints.EAST;
  item.add(edit, c);

  return item;
}
private static JPanel makeEditButtonBar(List list) {
  int size = list.size();
  JPanel p = new JPanel(new GridLayout(1, size, 0, 0)) {
    @Override public Dimension getMaximumSize() {
      return super.getPreferredSize();
    }
  };
  for(AbstractButton b: list) {
    b.setIcon(new ToggleButtonBarCellIcon());
    p.add(b);
  }
  p.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10));
  p.setOpaque(false);
  return p;
}
private static AbstractButton makeButton(String title, Action action) {
  JButton b = new JButton(action);
  b.addActionListener(new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
      JButton b = (JButton)e.getSource();
      Container c = SwingUtilities.getAncestorOfClass(JPopupMenu.class, b);
      if(c != null) {
        ((JPopupMenu)c).setVisible(false);
      }
    }
  });
  b.setText(title);
  b.setVerticalAlignment(SwingConstants.CENTER);
  b.setVerticalTextPosition(SwingConstants.CENTER);
  b.setHorizontalAlignment(SwingConstants.CENTER);
  b.setHorizontalTextPosition(SwingConstants.CENTER);
  b.setBorder(BorderFactory.createEmptyBorder());
  b.setContentAreaFilled(false);
  b.setFocusPainted(false);
  b.setOpaque(false);
  b.setBorder(BorderFactory.createEmptyBorder());
  return b;
}

References

2010/09/13

aterai

Placeholder for an empty JTable

Code

JEditorPane hint = new JEditorPane("text/html", ">html<>a href='dummy'<No data!>/a<>/html<");

table.setFillsViewportHeight(true);
table.setLayout(new GridBagLayout());
table.add(hint);

model.addTableModelListener(new TableModelListener() {
  @Override public void tableChanged(TableModelEvent e) {
    DefaultTableModel model = (DefaultTableModel)e.getSource();
    hint.setVisible(model.getRowCount()==0);
  }
});

References