我有两个类 mainpanel.java 和 subpanel.java。 subpanel.class 包含一个复选框和一些标签。当我单击 mainpanel.java 中的某些按钮时,我想更改这些组件的 setSelected() 和 setText() 。
我在 subpanel.java 中创建了一个方法,我从 mainpanel.java 调用它并传递 boolean 值。
public void schedulerchange(boolean check){
System.out.println("checked"+check);
scheduleenabler.setEnabled(check);
scheduleenabler.setSelected(check);
scheduleinfo.setText("Scheduler in On");
//subpanel21.updateUI();
}
当我从 mainpanel.java 调用此函数时,该函数被调用但值不会改变,除非我将 jcheckbox 和 jlabel 设为静态。但据我所知,除非非常必要,否则我们不应该使用静态组件。 有没有其他方法可以更改组件?
最佳答案
如果我理解了你的问题,那么我想你想写一个单独的 ActionListener
类并在那里执行操作,这将启用或禁用 UI 类中的 JCheckBox
.下面的代码显示了这一点。将您的复选框引用传递给该 PerformAction
类,并通过单击按钮启用或禁用它。
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainClass {
MainClass() {
JFrame jfrm = new JFrame("JTable Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(460, 180);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox check = null;
// Get the Panel from the subclass;
JPanel panel = new CheckBox().getCheckBoxPanel();
// From the compoenents present in the panel get the CheckBox compoenent.
for(int i = 0; i < panel.getComponentCount(); i++) {
if(panel.getComponent(i) instanceof JCheckBox) {
check = (JCheckBox) panel.getComponent(i);
}
}
JButton button = new JButton("Click");
// Pass the CheckBox Compoenent to the ActionListener.
button.addActionListener(new PerformAction(check));
jfrm.add(button);
jfrm.add(panel);
jfrm.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainClass();
}
});
}
}
class PerformAction implements ActionListener {
JCheckBox check = null;
public PerformAction(JCheckBox checkBox) {
check = checkBox;
}
@Override
public void actionPerformed(ActionEvent e) {
boolean checkStatus = check.isSelected();
if(checkStatus == true) {
check.setEnabled(false);
check.setSelected(false);
} else {
check.setEnabled(true);
check.setSelected(true);
}
}
}
class CheckBox {
public JPanel getCheckBoxPanel() {
JPanel checkPanel = new JPanel();
JCheckBox check = new JCheckBox();
checkPanel.add(new JLabel("CheckBox"));
checkPanel.add(check);
return checkPanel;
}
}
关于java - 访问其他类的 swing 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14411737/