actionlistener java,ActionListener中的Java Swing问题

这篇博客讨论了在Java GUI编程中遇到的问题,具体是关于JFrame上的按钮事件处理。当点击按钮时,预期更换显示面板的动作未能如愿触发。作者发现将事件处理代码放在`createGUI()`函数内可以正常工作,但在`actionPerformed()`方法中则失效。解决方案是在添加新面板后调用`pack()`方法,以确保JFrame更新显示。
摘要由CSDN通过智能技术生成

//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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值