簡體   English   中英

如何從Jbutton actionlistener創建JLabel實例?

[英]How to create a JLabel instance from Jbutton actionlistener?

我試圖創建一個JLabel ActionListener的事件,所以請不要發布任何新的JLabel(); actionlistener事件之外的實例。 Main是JFrame,Credits是Jbutton,Oracle是我要創建的實例Jlabel。

這是代碼:

 Credits.addActionListener(new ActionListener() {
    public  void actionPerformed (ActionEvent e)
    { 
      JLabel Oracle = new JLabel();
      Oracle.setBounds(100,300,300,300);
      Oracle.setText("HI");
     Main.add(Oracle);
     }
 });

意見建議:

  • 首先,不要設定任何界限。 使用setBounds(...)表示您使用的是空布局,通常是新手Swing程序的標志,並且這些程序非常嚴格,難以更新,增強和調試。 請改用布局管理器。
  • 接下來,接受JLabel的容器(這里是“ Main”)的布局管理器是關鍵。 有些組件不能很好地添加組件,例如GroupLayout,而其他組件則更好,例如BoxLayout。
  • 添加或刪除組件后,在容器上調用revalidate()repaint()
  • 作為輔助建議(一個不直接影響您的問題的建議),為了現在對我們有所幫助,並在將來對您有所幫助,請編輯代碼並更改變量名以符合Java命名約定 :類名均以大寫字母開頭字母和帶有小寫字母的方法/變量名稱。
  • 如果您仍然需要更多幫助,請考慮創建並發布一個最小的示例程序

例如,帶有解釋性注釋的代碼:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class AddALabel extends JPanel {
   private static final int PREF_W = 300;
   private static final int PREF_H = 300;

   // The JPanel that gets the JLabels. GridLayout(0, 1) will stack them
   // in a single column
   private JPanel receivingPanel = new JPanel(new GridLayout(0, 1));

   // wrap the above JPanel in the below one, and add it 
   // BorderLayout.PAGE_START so that the newly added JLabels 
   // bunch to the top
   private JPanel wrapPanel = new JPanel(new BorderLayout());

   // put the outer JPanel, the wrapPanel into a JScrollPane
   private JScrollPane scrollpane = new JScrollPane(wrapPanel);

   // Holds text that goes into the newly created JLabel
   private JTextField textField = new JTextField("Foo", 10);

   public AddALabel() {
      // wrap the receiving panel.
      wrapPanel.add(receivingPanel, BorderLayout.PAGE_START);
      scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

      JPanel northPanel = new JPanel();
      northPanel.add(textField);
      // add a JButton that does our work. Give it an Action/ActionListener
      northPanel.add(new JButton(new AddLabelAction("Add a Label")));

      setLayout(new BorderLayout());
      add(northPanel, BorderLayout.PAGE_START);
      add(scrollpane, BorderLayout.CENTER);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   // the code for our Action/ActionListener
   private class AddLabelAction extends AbstractAction {
      public AddLabelAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         // get text from JTextField
         String text = textField.getText();

         // create JLabel and insert above text
         JLabel label = new JLabel(text);

         // add JLabel to receiving JPanel
         receivingPanel.add(label);

         // revalidate and repaint receiving JPanel
         receivingPanel.revalidate();
         receivingPanel.repaint();
      }
   }

   // create our GUI in a thread-safe way
   private static void createAndShowGui() {
      AddALabel mainPanel = new AddALabel();

      JFrame frame = new JFrame("AddALabel");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

我認為您所缺少的只是對pack方法的調用,這是我如何能夠獲得所需結果的方法:

public class Main extends JFrame {

    final JButton credits;

    public Main()
    {
        super("JLabel from JButton actionlistener");
        setSize(100, 100);        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        credits = new JButton("Credits");

        credits.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                JLabel oracle = new JLabel();
                oracle.setText("Oracle licenses are out of price");
                Main.this.add(oracle);
                Main.this.pack();
            }
        });

        getContentPane().setLayout(new FlowLayout());
        add(credits);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM