Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would write a custom <code>PianoLayoutManager</code> and position the black keys with a higher z-order than the white buttons. Create your own "constraint" class that allows you to add components like this:</p> <pre><code>add(new WhiteKey(), new PianoLayoutConstraint(WHITE, 1); add(new WhiteKey(), new PianoLayoutConstraint(WHITE, 2); ... add(new WhiteKey(), new PianoLayoutConstraint(WHITE, n); add(new BlackKey(), new PianoLayoutConstraint(BLACK, 1); add(new BlackKey(), new PianoLayoutConstraint(BLACK, 2); ... add(new BlackKey(), new PianoLayoutConstraint(BLACK, m); </code></pre> <p>From <a href="http://download.oracle.com/javase/tutorial/uiswing/components/jcomponent.html" rel="nofollow noreferrer">Using Swing Components tutorial trail</a></p> <blockquote> <p><strong>Note:</strong> The z-order determines the order that components are painted. The component with the highest z-order paints first and the component with the lowest z-order paints last. Where components overlap, the component with the lower z-order paints over the component with the higher z-order.</p> </blockquote> <p>Here is an ugly hack that uses null-layout to get you started.</p> <pre><code>import java.awt.Color; import javax.swing.*; class PianoComponent extends JPanel { PianoComponent() { setLayout(null); for (int i = 0; i &lt; 20; i++) { JButton key = new JButton(); key.setBackground(Color.WHITE); key.setLocation(i * 20, 0); key.setSize(20, 120); add(key); setComponentZOrder(key, i); } for (int i = 0; i &lt; 20; i++) { int j = i % 7; if (j == 2 || j == 6) continue; JButton key = new JButton(); key.setBackground(Color.BLACK); key.setLocation(i * 20 + 12, 0); key.setSize(16, 80); add(key); setComponentZOrder(key, 0); } } } public class Test { public static void main(String[] args) { JFrame jf = new JFrame("Piano!"); jf.setSize(400, 200); jf.add(new PianoComponent()); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } } </code></pre> <p><img src="https://i.stack.imgur.com/bo6Fp.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload