我刚接触Java Swing. 在动态添加组件方面有一些疑问。
基本上,我有一个主JPanel
,其中包含两个子JPanel
(leftpanel和rightpanel),并水平对齐。在左侧JPanel
中,我有一些JButtons
,当我点击JButton
时,我需要在右侧JPanel
中显示一些JLabel
、JTextArea
等组件 。我尝试了一些代码,但它不起作用。当我点击按钮时,它会进入事件监听器函数,但是我无法看到JLabel
。
我在下面给出了我的代码。请查看并纠正我。谢谢提前。
package my;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* @author root
*/
public class myAplliwithPanel extends JFrame{
JPanel rightPanel;
public myAplliwithPanel() {
initGui();
}
public void initGui()
{
JPanel mainPanel=new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
JPanel leftPanel=new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
rightPanel=new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JButton dbBut=new JButton("DB");
JButton appliBut=new JButton("Appli");
appliBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JLabel label=new JLabel("dsggs");
rightPanel.add(label);
}
});
JButton backendBut=new JButton("Backend");
leftPanel.add(dbBut);
leftPanel.add(appliBut);
leftPanel.add(backendBut);
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
add(mainPanel);
setTitle("System Manger");
setSize(400, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myAplliwithPanel myObj = new myAplliwithPanel();
myObj.setVisible(true);
}
});
}
}