2017-12-23 1 views
-1

여러 사용자의 여러 세부 정보를 보유 할 사용자 시스템을 만들고 있습니다. 그래서 나는 다른 버튼을 만들 수있는 버튼을 만들고 싶습니다. 두 번째 버튼을 누르면 사용자가 채울 수있는 양식이 열립니다. 사용자가 채울 양식을 이미 만들었지 만 더 많은 단추를 만들 수는 없습니다. 이 코드를 코딩했는데 Jpanel에 버튼이 표시되지 않습니다.JPanel에서 다른 버튼을 만들 JButton을 만드는 방법은 무엇입니까?

나는 다음과 같은 코드를 만들었습니다

private void mainButtonActionPerformed(java.awt.event.ActionEvent evt) {  
     JButton b=new JButton("Click Here"); 
     b.setBounds(50,100,95,30); 
     jPanel3.add(b); 
     b.setVisible(true); 
} 

jPanel3 내에서 새로운 버튼을 생성하지 않는 것 같습니다. 내가 코드를 잘못 입력했거나이 작업을 수행 할 수있는 올바른 대체 방법이 있습니까?

행에 3 개의 버튼이 있고 새 버튼 행이 필요합니다.

+1

1) * * 무엇가있다 그렇게하는 목적? 최종 사용자에게 제공하려는 필요를 충족시키기에 더 적합한 다른 접근법이있을 가능성이 큽니다. 2) 이것은 IDE와는 아무런 관련이 없으며 태그를 추가하지 마십시오. –

+1

위의 @ AndrewThompson의 의견에 110 % 동의합니다. 또한 답변을 보려면 업데이트를 참조하십시오. 질문이 불완전하기 때문에 나는 그것을 "커뮤니티 위키"로 대답했지만, 그의 의견과 커뮤니티 위키 답변의 정보에 따라 질문을 개선하십시오. –

답변

1

코드와 질문에 너무 많은 정보가 없어 완벽하게 응답 할 수 없습니다. 에 대해 내가 말할 수있는 모두는 항상이 그들을 다시 그리는 모든 구성 요소를 레이아웃을 다시하고 컨테이너의 (여기 jPanel3) 레이아웃 매니저를 알려줍니다로에서 구성 요소를 추가하거나 제거한 후 용기에 jPanel3.revalidate()jPanel3.repaint() 전화

  1. 입니다 .
  2. 컨테이너의 레이아웃 관리자는 이것이 잘 작동하는 데 핵심입니다. 현재 그 내용을 잘 모릅니다. 일부 레이아웃 관리자는이 작업을 쉽게 수행 할 수 있습니다 (예 : FlowLayout, GridLayout). (예 : GroupLayout).
  3. 새로 생성 된 JComponent (여기 JButton)가 기본적으로 표시되어 있으므로 b.setVisible(true);이 필요하지 않습니다.
  4. setBounds(...)을 호출 중이므로 null 레이아웃을 사용하고 있다고 가정하는 것처럼 보입니다. 이것은 입니다. 잘못된 아이디어 ™입니다. null 레이아웃과 setBounds()은 복잡한 GUI를 만드는 가장 쉽고 좋은 방법처럼 Swing 초보자처럼 보일 수 있지만 더 많은 스윙 GUI를 사용하면 더 어려울 수 있습니다. 그들은 GUI의 크기를 조정할 때 구성 요소의 크기를 조정하지 않으며, 향상 시키거나 유지 보수 할 왕가이며, 스크롤 패널에 배치 될 때 완전히 실패합니다. 원래 플랫폼과 다른 모든 플랫폼이나 화면 해상도에서 볼 때 끔찍한 것처럼 보입니다. .
  5. 그런 질문을 할 때는 시험하고 실행할 수있는 작지만 완전한 프로그램 인 질문을 작성하여 게시하고 문제를 설명하는 minimal example program (링크를 클릭하십시오)을 시도하십시오. 당신의 코드가 작동하는 방법을 보여줍니다 예를 들어

, MCVE : "어떻게 JPanel의 내 다른 버튼을 생성하는하는 JButton를 만들기 위해"

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

@SuppressWarnings("serial") 
public class AddButton extends JPanel { 
    private JPanel jPanel3 = new JPanel(); // panel to hold buttons 

    public AddButton() { 
     // create JButton that will add new buttons to jPanel3 
     JButton addMoreButtonsBtn = new JButton("Add More Buttons"); 
     // give it an ActionListener 
     addMoreButtonsBtn.addActionListener(e -> { 
      final JButton newButton = new JButton("Click Here"); 
      // when you click it, it removes itself (just for grins) 
      newButton.addActionListener(e2 -> { 
       jPanel3.remove(newButton); 
       // again revalidate and repaint 
       jPanel3.revalidate(); 
       jPanel3.repaint();    
      }); 
      // add to jPanel3, the "container" 
      jPanel3.add(newButton); 
      // revalidate and repaint the container 
      jPanel3.revalidate(); 
      jPanel3.repaint();    
     }); 

     // create a JPanel and put the add more buttons button to it 
     JPanel bottomPanel = new JPanel(); 
     bottomPanel.add(addMoreButtonsBtn); 

     // give jPanel3 a layout that can handle new buttons 
     // a gridlayout with 1 column and any number of rows 
     jPanel3.setLayout(new GridLayout(0, 1)); 

     // add it to the top of another JPanel that uses BorderLayout 
     JPanel borderLayoutPanel = new JPanel(new BorderLayout()); 
     borderLayoutPanel.add(jPanel3, BorderLayout.PAGE_START); 
     // and add that to a JScrollPane, so we can add many buttons and scroll 
     JScrollPane scrollPane = new JScrollPane(borderLayoutPanel); 
     // make the vert scrollbar always visible 
     scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 

     // force GUI to be larger 
     setPreferredSize(new Dimension(400, 200)); 
     // give the main JPanel a BorderLayout 
     setLayout(new BorderLayout()); 
     // and add scrollpane to center 
     add(scrollPane, BorderLayout.CENTER); 
     // add bottom panel to the bottom 
     add(bottomPanel, BorderLayout.PAGE_END); 
    } 

    private static void createAndShowGui() { 
     AddButton mainPanel = new AddButton(); 

     JFrame frame = new JFrame("AddButton"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 
+0

덕분에 내가 위의 질문을 더 명확하게하기 위해 위의 변경을 할 것입니다. 죄송합니다. 자바 스윙을하는 아마추어입니다. – Harshmellow

+0

@ kingo123 : [mcve]가 없으므로 귀하의 질문이 향상되지 않았으며 사용 된 레이아웃 관리자도 알지 못합니다. .[도움말]의 How-to-Ask 섹션을보고 스윙 튜토리얼을 읽고 라이브러리 작동 방법을 확인하십시오. –

관련 문제