JButton "disappears" 尽管它位于 JLabel 之外的另一层
JButton "disappears" although it is on another Layer than JLabel
我最近在做一个类似国际象棋的棋盘游戏,所以我做了一个11*11的场地。在每个字段上应该有一个 JButton(在默认层上),并且在一个更高的层上有一个可移动的 JLabel。但是标签仍然将按钮推开。这是简化的代码:
public class Demo {
public static void main(String[] args) {
ImageIcon image = new ImageIcon("C:src\myImage.png");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JLayeredPane[] tileLayeredPane = new JLayeredPane[121];
JButton button = new JButton();
JLabel label = new JLabel();
label.setIcon(image);
button.setText("I am not visible!");
for (int i = 0; i < tileLayeredPane.length; i++) { // creates 121 JLabels
tileLayeredPane[i] = new JLayeredPane();
tileLayeredPane[i].setLayout(new BoxLayout(tileLayeredPane[i], BoxLayout.Y_AXIS));
tileLayeredPane[i].setOpaque(true);
}
tileLayeredPane[0].add(button, JLayeredPane.DEFAULT_LAYER);
tileLayeredPane[0].add(label, JLayeredPane.PALETTE_LAYER);
mainPanel.setLayout(new GridLayout(11, 11));
for(int i = 0; i < 121; i++) {
mainPanel.add(tileLayeredPane[i]);
}
frame.add(mainPanel);
frame.setVisible(true);
}
}
On each field should be a JButton (on the default layer) and and on a higher layer that a movable JLabel
是的,因为您在 JLayeredPane
上使用了 BoxLayout
,它决定了组件的布局方式 - JLayeredPane
只会影响组件的顺序是涂漆的,而不是它们的布局方式
我 "guessing" 你试图将标签放在按钮的顶部,这回避了 "why aren't you using the buttons inbuilt image support"?
的问题
我最近在做一个类似国际象棋的棋盘游戏,所以我做了一个11*11的场地。在每个字段上应该有一个 JButton(在默认层上),并且在一个更高的层上有一个可移动的 JLabel。但是标签仍然将按钮推开。这是简化的代码:
public class Demo {
public static void main(String[] args) {
ImageIcon image = new ImageIcon("C:src\myImage.png");
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JLayeredPane[] tileLayeredPane = new JLayeredPane[121];
JButton button = new JButton();
JLabel label = new JLabel();
label.setIcon(image);
button.setText("I am not visible!");
for (int i = 0; i < tileLayeredPane.length; i++) { // creates 121 JLabels
tileLayeredPane[i] = new JLayeredPane();
tileLayeredPane[i].setLayout(new BoxLayout(tileLayeredPane[i], BoxLayout.Y_AXIS));
tileLayeredPane[i].setOpaque(true);
}
tileLayeredPane[0].add(button, JLayeredPane.DEFAULT_LAYER);
tileLayeredPane[0].add(label, JLayeredPane.PALETTE_LAYER);
mainPanel.setLayout(new GridLayout(11, 11));
for(int i = 0; i < 121; i++) {
mainPanel.add(tileLayeredPane[i]);
}
frame.add(mainPanel);
frame.setVisible(true);
}
}
On each field should be a JButton (on the default layer) and and on a higher layer that a movable JLabel
是的,因为您在 JLayeredPane
上使用了 BoxLayout
,它决定了组件的布局方式 - JLayeredPane
只会影响组件的顺序是涂漆的,而不是它们的布局方式
我 "guessing" 你试图将标签放在按钮的顶部,这回避了 "why aren't you using the buttons inbuilt image support"?
的问题