所以,我正在尝试这样做,以便当选择“名字”或“姓氏”并在palettePane中按下鼠标时,带有我的名字或姓氏的标签出现在mouseX或mouseY上。这是我得到的,我很难过。有什么想法吗?
这是设置:
public class benNameFunc extends JPanel implements ActionListener, MouseListener{
private final JRadioButton firstName;
private final JRadioButton lastName;
private final JButton deleteButton;
private JLabel firstNameLabel;
int x;
int y;
int firstOrLast = 1;
public benNameFunc(){
lastName = new JRadioButton("Last Name");
lastName.setPreferredSize(new Dimension(100, 50));
lastName.setForeground(Color.RED);
lastName.setActionCommand("last");
lastName.setSelected(false);
firstName = new JRadioButton("First Name");
firstName.setPreferredSize(new Dimension(100, 50));
firstName.setForeground(Color.RED);
firstName.setActionCommand("first");
firstName.setSelected(true);
JPanel palettePane = new JPanel(new BorderLayout());
palettePane.setPreferredSize(new Dimension (800, 500));
add(palettePane, BorderLayout.CENTER);
firstNameLabel = new JLabel("Ben");
firstNameLabel.setPreferredSize(new Dimension(100, 10));
firstNameLabel.setForeground(Color.WHITE);
firstNameLabel.setVisible(true);
palettePane.add(firstNameLabel);
buttonPane.setBackground(Color.BLACK);
firstName.addActionListener(this);
lastName.addActionListener(this);
deleteButton.addActionListener(this);
palettePane.addMouseListener(this);
}
然后是动作代码:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "first") {
firstOrLast = 1;
} else if (e.getActionCommand() == "last") {
firstOrLast = 2;
} else if (e.getSource() == deleteButton){
firstOrLast = 3;
}
}
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
switch (firstOrLast) {
case 1:
firstNameLabel.setLocation(x, y);
break;
case 2:
break;
case 3:
break;
default:
break;
}
...
答案 0 :(得分:1)
palettePane
目前处于布局管理器的控制之下,这意味着当重新验证容器时,任何更改位置的尝试都很可能会失败或被取代...将它的布局管理器设置为{{1} } null
无济于事。相反,您需要使用组件preferredSize
方法代替... setSize
firstNameLabel.setSize(firstNameLabel.getPreferredSize());
比较错误... 例如,你正在......
String
你应该做什么......
if (e.getActionCommand() == "first") {
firstOrLast = 1;
} else if (e.getActionCommand() == "last") {
firstOrLast = 2;
} else if (e.getSource() == deleteButton) {
firstOrLast = 3;
}
<强>买者强>
if (e.getActionCommand().equals("first")) {
firstOrLast = 1;
} else if (e.getActionCommand().equals("last")) {
firstOrLast = 2;
} else if (e.getSource() == deleteButton) {
firstOrLast = 3;
}
布局非常难以解决问题。请确保这实际上是您想要做的。
示例强>
null