我正在尝试将一个动作监听器放在一个名为btnNew的JButton
上,在我看来:
public class MyWindow6 extends JFrame
{
private JButton btnNew;
private static final long serialVersionUID = 6579944958990616196L;
public static void main(String[] args) throws UnsupportedLookAndFeelException
{
UIManager.setLookAndFeel(new NimbusLookAndFeel());
MyWindow6 myWindow = new MyWindow6();
myWindow.setVisible( true );
public MyWindow6()
{
super( "JMenu sample" );
btnNew = new JButton( new ImageIcon( "icons/save.png"));
this.setSize(1200,800);
this.setLocationRelativeTo( null );
this.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
JPanel contentPane = (JPanel) this.getContentPane();
JScrollPane leftScrollPane = new JScrollPane( new JTree());
leftScrollPane.setPreferredSize( new Dimension(200, 0));
contentPane.add( leftScrollPane, BorderLayout.WEST);
JTable t = new JTable(DaoClef.createModel());
JScrollPane scrollPane = new JScrollPane(t);
t.setFillsViewportHeight(true);
add(scrollPane, BorderLayout.CENTER);
// toolbar
JToolBar jtb = new JToolBar();
btnNew.setToolTipText("Ajouter clef (CTRL + N");
jtb.add(btnNew);
contentPane.add(jtb, BorderLayout.NORTH);
}
public JButton getBtnNew() {
return btnNew;
}
public void setBtnNew(JButton btnNew) {
this.btnNew = btnNew;
}
}
}
控制器:
public class Controller2 {
private DaoClef dao;
private MyWindow6 view;
public Controller2(DaoClef d, MyWindow6 v) {
dao = d;
view = v;
}
public void initController() {
view.getBtnNew().addActionListener(e -> delete());
}
private void delete() {
System.out.println("hello");
}
}
我没有任何错误,只是println
根本不起作用。
您知道为什么这不起作用吗? 似乎控制器和视图未连接。
如果您对将MVC与Swing一起使用有任何建议,我会有些困惑,因为我不知道将监听器放在哪里。
答案 0 :(得分:0)
像下面这样发布mcve,使问题和解决方案易于理解和重现:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MyWindow6 extends JFrame
{
private final JButton btnNew;
public static void main(String[] args){
new Controller2(new MyWindow6());
}
public MyWindow6() {
btnNew = new JButton( "Delete");
this.setSize(120,80);
this.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
add(btnNew, BorderLayout.PAGE_START);
setVisible(true);
}
public JButton getBtnNew() {
return btnNew;
}
}
class Controller2 {
private final MyWindow6 view;
public Controller2(MyWindow6 v) {
view = v;
view.getBtnNew().addActionListener(e -> delete());
}
private void delete() {
System.out.println("delete btn clicked");
}
}