[英]change JLabel of a panel depending on Jbutton of another panel in the same Jframe
I have constructed a class for the JPanel with several JButtons.Inside this class I want to construct another JPanel with JLabels that will change depending on the actionPerformed on the JButtons of the first JPanel.Finally, I want to add these 2 panels on the same Jframe. 我用几个JButton为JPanel构建了一个类,在这个类中我想用JLabel构造另一个JPanel,它会根据第一个JPanel的JButton上的actionPerformed进行改变,最后,我想在同一面板上添加这两个面板JFrame中。 Can all these be done within the class of the first Panel?Otherwise, which is a better approach for this problem?
可以在第一个专家组的班级中完成所有这些工作吗?否则,这是解决此问题的更好方法?
Yes, you can. 是的你可以。 One way you could accomplish this is with anonymous inner classes (saves keystrokes):
实现此目的的一种方法是使用匿名内部类(节省击键次数):
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class Foo {
JLabel one;
JLabel two;
public static void main(String[] args) {
(new Foo()).go();
}
public void go() {
JFrame frame = new JFrame("Test");
// Panel with buttons
JPanel buttonPanel = new JPanel();
JButton changeOne = new JButton("Change One");
changeOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
one.setText("New text for one");
}
}
buttonPanel.add(changeOne);
JButton changeTwo = new JButton("Change Two");
changeTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
two.setText("New text for two");
}
}
buttonPanel.add(changeTwo);
frame.add(buttonPanel, BorderLayout.NORTH);
// Panel with labels
JPanel labelPanel = new JLabel();
one = new JLabel("One");
labelPanel.add(one);
two = new JLabel("Two");
labelPanel.add(two);
// Set up the frame
frame.add(labelPanel, BorderLayout.SOUTH);
frame.setBounds(50, 50, 500, 500);
frame.setDefaultCloseAction(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.