actionlistener java,ActionListener中的Java Swing问题

actionlistener java,ActionListener中的Java Swing问题//GUI.javapublicclassGUIextendsJFrameimplementsActionListener{privatestaticfinallongserialVersionUID=870343916997182570L;privateJPanelbtmPanel;publicGUI(Stringarg0)throwsHeadlessExc…

大家好,欢迎来到IT知识分享网。

actionlistener java,ActionListener中的Java Swing问题

//GUI.java

public class GUI extends JFrame implements ActionListener {

private static final long serialVersionUID = 870343916997182570L;

private JPanel btmPanel;

public GUI(String arg0) throws HeadlessException {

super(arg0);

createGUI();

}

private void createGUI() {

setSize(WIDTH, HEIGHT);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

//ResultPanel rslt = new ResultPanel();

//this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);

btmPanel = new JPanel();

btmPanel.setBackground(Color.LIGHT_GRAY);

btmPanel.setLayout(new FlowLayout());

JButton blueSearch = new JButton(“Search”);

blueSearch.setBackground(Color.WHITE);

blueSearch.addActionListener(this);

btmPanel.add(blueSearch);

JButton blackChart = new JButton(“Chart”);

blackChart.setBackground(Color.WHITE);

blackChart.addActionListener(this);

btmPanel.add(blackChart);

this.getContentPane().add(btmPanel, BorderLayout.SOUTH);

}

@Override

public void actionPerformed(ActionEvent e) {

String buttonString = e.getActionCommand();

if (buttonString.equals(“Search”)) {

ResultPanel rslt = new ResultPanel();

this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);

}

}

}

//ResultPanel.java

public class ResultPanel extends JPanel implements ActionListener {

private static final long serialVersionUID = -7851502165390304971L;

private JPanel textPanel;

private JTextArea textDisplay;

public ResultPanel() {

textPanel = new JPanel();

textDisplay = new JTextArea(“Text Area:”);

}

public JPanel createPanel() {

textDisplay.setEditable(true);

textPanel.setBackground(Color.LIGHT_GRAY);

textPanel.setLayout(new BorderLayout());

textPanel.add(textDisplay,BorderLayout.CENTER);

return textPanel;

}

@Override

public void actionPerformed(ActionEvent e) {

}

}

I have two buttons on the main frame, and I hope to change the panel when I press the button.

The question is that the code in “actionPerformed” doesn’t work,

but it works well if I put them in the creatGUI()….(see the marked section).

Is that anything wrong ?

解决方案

Just call pack(); after you add the panel. This will get the JFrame to show the update.

if (buttonString.equals(“Search”)) {

ResultPanel rslt = new ResultPanel();

this.getContentPane().add(rslt.createPanel(), BorderLayout.CENTER);

pack();

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/11315.html

(0)
上一篇 2024-03-24 09:26
下一篇 2024-03-24 10:00

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信