[英]Change size of JButton and text of a label on focus Gain and lost event of JButton
我想增加和减小JButton
的焦点增益和丢失事件的大小。 同时,我想用聚焦JButton
的文本更改JLabel
。
如果不更改JLabel
文本,则可以更改按钮的大小,但是同时更改标签时, JButton
的大小不会更改。
这是代码:
public class Main extends JFrame implements FocusListener {
JButton b1, b2;
JLabel lbl;
private static final long serialVersionUID = 1L;
public Main() {
setSize(600, 600);//Size of JFrame
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);//Sets if its visible.
JPanel panel = new JPanel();
b1 = new JButton("Start");//The JButton name.
b1.setRequestFocusEnabled(false);
b1.addFocusListener(this);
panel.add(b1);
b2 = new JButton("End");//The JButton name.
b2.setRequestFocusEnabled(false);
b2.addFocusListener(this);
panel.add(b2);
add(panel, BorderLayout.CENTER);
lbl = new JLabel(" ");
add(lbl, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new Main();//Reads method main()
}
/*
* What the button does.
*/
@Override
public void focusLost(FocusEvent ae) {
if (ae.getSource() == b2) {
b2.setSize(55, 26);
} else if (ae.getSource() == b1) {
b1.setSize(55, 26);
}
}
@Override
public void focusGained(FocusEvent ae) {
if (ae.getSource() == b2) {
lbl.setText("End");
b2.setSize(55, 40);
} else if (ae.getSource() == b1) {
lbl.setText("Start");
b1.setSize(55, 40);
}
}
}
问题是您将绝对布局(或null布局)与隐式LayoutManager(默认情况下,JPanel随附FlowLayout)混合在一起。
当您在JLabel上调用setText时(该文本发生更改),它将自动调用revalidate,最终将触发LayoutManager对组件进行布局。
要么使用LayoutManager,或者选择设置一些约束和首选项/最小/最大大小(但不建议使用后者)(并且您永远不要调用setLocation / setSize / setBounds),或者使用null-layout并设置自己的位置和大小组件(在这种情况下,您必须自称setSize / setLocation / setBounds)。
认真考虑阅读LayoutManager教程 。 有专门的章节“ 不使用布局管理器(绝对定位) ”。
我认为这是您要实现的目标。
public class Main extends JFrame implements FocusListener {
JButton b1, b2;
JLabel lbl;
private static final long serialVersionUID = 1L;
public Main() {
setSize(600, 600);// Size of JFrame
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);// Sets if its visible.
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setSize(this.getSize());
b1 = new JButton("Start");// The JButton name.
b1.setRequestFocusEnabled(false);
b1.addFocusListener(this);
b1.setLocation(10, 12);
panel.add(b1);
b2 = new JButton("End");// The JButton name.
b2.setRequestFocusEnabled(false);
b2.addFocusListener(this);
b2.setLocation(70, 12);
panel.add(b2);
add(panel, BorderLayout.CENTER);
lbl = new JLabel(" ");
add(lbl, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new Main();// Reads method main()
}
/*
* What the button does.
*/
@Override
public void focusLost(FocusEvent ae) {
if (ae.getSource() == b2) {
b2.setSize(55, 26);
} else if (ae.getSource() == b1) {
b1.setSize(55, 26);
}
}
@Override
public void focusGained(FocusEvent ae) {
if (ae.getSource() == b2) {
lbl.setText("End");
b2.setSize(55, 40);
} else if (ae.getSource() == b1) {
lbl.setText("Start");
b1.setSize(55, 40);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.