我是Java Swing的新手。我對Swing中的動態組件有些疑問。java swing動態添加組件
基本上我甲肝一個主要JPanel
包括兩個子JPanel
(leftpanel和rightpanel)的神韻:horizontally.In離開JPanel
我甲肝一些JButtons
,我會點擊JButton
我NEDD表現出一定的JLabel
,JTextArea
等右JPanel
。我嘗試了一個代碼,但它不工作。當我點擊按鈕時,它將進入事件監聽器功能,但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);
}
});
}
}
我edided您的文章,請回復,如果不更新UI ... – mKorbel