2013-04-17 2 views
3

мне нужно выровнять все поля с соответствующими этикетками,Устройте Этикетка с соответствующим полем свинг

enter image description here

вот мой код:

 public class Progress extends JPanel implements ActionListener { 

public JLabel ClientIP; JTextField ip; 
JLabel ClientPassword; JTextField pass; 
JLabel Videoname; JTextField vname; 
JLabel perccomplete; JTextField percent; 
JLabel PacketsSent; JTextField pacsent; 
JLabel Connectiontype; JTextField conntype; 
JLabel noofvideossent; JTextField videosend; 
JButton disconnect; JButton refresh; 
JButton ok; 

public Progress() { 
ClientIP = new JLabel("Client's IP:"); 
ClientPassword = new JLabel("Clients Password:"); 
Videoname = new JLabel("Video being Transfered:"); 
perccomplete = new JLabel("% of transfer Complete:"); 
PacketsSent = new JLabel("No of Packets sent:"); 
Connectiontype = new JLabel("Connection Type:"); 
noofvideossent = new JLabel("No of Videos Sent:"); 
String Ipad,Ipass,Iselvid; 
if(ClientIPAddr==null || ClientIPAddr.equals("")){ 
    Ipad="Not Connected"; 
}else Ipad=ClientIPAddr.toString(); 
if(vFilePassword ==null || vFilePassword.equals("")){ 
    Ipass="No Password"; 
}else Ipass=vFilePassword; 
if(selected_video==null || selected_video.equals("")){ 
    Iselvid="Not Selected"; 
}else Iselvid=selected_video; 

ip = new JTextField(Ipad); 
ip.setColumns(20); 
pass = new JTextField(Ipass); 
pass.setColumns(20); 
vname = new JTextField(Iselvid); 
vname.setColumns(20); 
percent = new JTextField("10%"); 
percent.setColumns(20); 
pacsent =new JTextField(String.valueOf(RTSPSeqNb)); 
pacsent.setColumns(20); 
String c; 
if(clientConnected==true) 
    c="TCP"; 
else c="not Connected"; 
conntype = new JTextField(c); 
conntype.setColumns(20); 
videosend = new JTextField(String.valueOf(videocount)); 
videosend.setColumns(20); 

    //Tell accessibility tools about label/textfield pairs. 
ClientIP.setLabelFor(ip); 
ClientPassword.setLabelFor(pass); 
Videoname.setLabelFor(vname); 
perccomplete.setLabelFor(percent); 
PacketsSent.setLabelFor(pacsent); 
Connectiontype.setLabelFor(conntype); 
noofvideossent.setLabelFor(videosend); 

//Lay out the labels in a panel. 
    JPanel labelPane = new JPanel(new GridLayout(0,1)); 
    labelPane.add(ClientIP); 
    labelPane.add(ClientPassword); 
    labelPane.add(Videoname); 
    labelPane.add(perccomplete); 
    labelPane.add(PacketsSent); 
    labelPane.add(Connectiontype); 
    labelPane.add(noofvideossent); 

    //Layout the text fields in a panel. 
    JPanel fieldPane = new JPanel(new GridLayout(0,1)); 
    fieldPane.add(ip); 
    fieldPane.add(pass); 
    fieldPane.add(vname); 
    fieldPane.add(percent); 
    fieldPane.add(pacsent); 
    fieldPane.add(conntype); 
    fieldPane.add(videosend); 
    //Put the panels in this panel, labels on left, 
    //text fields on right. 
    //setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); 


    JPanel buttonPane = new JPanel(new GridLayout(0,1)); 
    disconnect = new JButton("Disconnect Client"); 
    disconnect.setActionCommand("Disconnect"); 
    disconnect.addActionListener(this); 
    refresh = new JButton("Refresh Details"); 
    refresh.setActionCommand("refresh"); 
    refresh.addActionListener(this); 
    ok = new JButton("OK"); 
    ok.setActionCommand("ok"); 
    ok.addActionListener(this); 
    buttonPane.add(refresh); 
    buttonPane.add(disconnect); 
    buttonPane.add(ok); 
    add(labelPane, BorderLayout.CENTER); 
    add(fieldPane, BorderLayout.LINE_END); 
    add(buttonPane, BorderLayout.AFTER_LAST_LINE); 
} 


    private void createAndShowGUI() { 
    //Create and set up the window. 
    frame = new JFrame("Connected Client's Details"); 
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


    //Add contents to the window. 
    frame.add(new Progress()); 
    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
} 

Я пытался идти его путем ссылки но он не работал, никаких предложений?

+0

Может кто-нибудь предложить любые другие рамки, в которых это может быть проще? – Learner

+0

Используйте [менеджеры макетов] (http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html) или дизайнер GUI. (И NetBeans и IntelliJ превосходны.) – millimoose

ответ

1

Посмотрите на примере, приведенный на GroupLayout (картинку по ссылке):

enter image description here

Вашего код должен внимательно походить код по ссылке.

+1

@ syb0rg Вы имеете в виду 'GroupLayout'? – tarrsalah

+0

@tarrsalah Да, это был мозговой пердит. – syb0rg

+1

Handcoding 'GroupLayout' - довольно сумасшедшее предложение. Это лучше использовать с дизайнером GUI NetBeans. Я сомневаюсь, что было бы целесообразно скомпоновать «GroupLayout», который не может быть проще с помощью «GridBagLayout». – millimoose

1

Как правило, Никогда продлевает JPanel/JFrame, если вы не действительно расширяя их функциональные возможности, всегда favour composition over inheritance.

Для менеджера компоновки качели, я очень рекомендую miglayout, простой и easy, чтобы начать с, вы должны загрузить jar и добавить его в CLASSPATH.

Полный код для прототипирования этого GUI

enter image description here

будет так же просто, как:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import net.miginfocom.swing.MigLayout; 

/** 
* Hello world! 
* 
*/ 
public class App { 

    private JPanel panel; 

    private JLabel cilentIPLabel= new JLabel(); 
    private JLabel clientPWLabel= new JLabel(); 
    private JTextField clientIPTextField= new JTextField(); 
    private JTextField clientPWTextField= new JTextField(); 
    private JButton printButton = new JButton(); 

    public App() { 
     initComponents(); 
    } 


    private void initComponents() { 
     cilentIPLabel.setText("Client IP :"); 
     clientPWLabel.setText("Client Password :"); 
     printButton.setText("print"); 
     printButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) {   
       System.out.println("The ID of the clinet is " + clientIPTextField.getText()); 
      } 
     }); 
    } 

    public JPanel getPanel() { 

     if (panel == null) { 
      panel= new JPanel(new MigLayout("gap 10","[100]10[100, left, fill, grow]","[][]20[]")); 
      panel.add(cilentIPLabel); 
      panel.add(clientIPTextField, "wrap"); 
      panel.add(clientPWLabel); 
      panel.add(clientPWTextField, "wrap"); 
      panel.add(printButton, "skip, tag apply"); 
     } 
     return panel;  
    } 


    public static void main(String[] args) { 
     JFrame frame= new JFrame("SO demo"); 
     frame.setSize(400, 150); 
     frame.setContentPane(new App().getPanel()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 

    } 
} 
1

Несколько вариантов:

  • GroupLayout, Иллюстрированный от here и here.

  • BoxLayout, показаны here.

  • JTable, обсуждено here.

0

Большое спасибо за помощь. Я изменил код следующим образом, и он работал ..

GroupLayout layout = new GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setAutoCreateGaps(true); 
     layout.setAutoCreateContainerGaps(true); 

     // Turn on automatically creating gaps between components that touch 
     // the edge of the container and the container. 
     layout.setAutoCreateContainerGaps(true); 

     GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); 
     hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING). 
       addComponent(ClientIP).addComponent(ClientPassword).addComponent(Videoname).addComponent(perccomplete).addComponent(PacketsSent).addComponent(Connectiontype).addComponent(noofvideossent)); 

     hGroup.addGroup(layout.createParallelGroup(Alignment.LEADING). 
       addComponent(ip).addComponent(pass).addComponent(vname).addComponent(percent). 
       addComponent(pacsent).addComponent(conntype).addComponent(videosend).addComponent(disconnect).addComponent(refresh).addComponent(ok)); 
     layout.setHorizontalGroup(hGroup); 


     GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); 

     vGroup.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(ClientIP).addComponent(ip)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(ClientPassword).addComponent(pass)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(Videoname).addComponent(vname)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(perccomplete).addComponent(percent)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(PacketsSent).addComponent(pacsent)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(Connectiontype).addComponent(conntype)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(noofvideossent).addComponent(videosend)); 

     vGroup.addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(disconnect)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(refresh)).addGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(ok)); 
     layout.setVerticalGroup(vGroup); 
0

Единственный надежный способ получить метки и соответствующие им поля выстраиваются правильно, чтобы поместить их в той же панели и использовать один экземпляр макета менеджер, чтобы выровнять их.

GridLayout

Самый простой подход будет использовать два столбца макет сетки:

JPanel fieldPane = new JPanel(new GridLayout(0, 2)); 
fieldPane.add(ClientIP); 
fieldPane.add(ip); 
fieldPane.add(ClientPassword); 
fieldPane.add(pass); 
fieldPane.add(Videoname); 
fieldPane.add(vname); 
fieldPane.add(perccomplete); 
fieldPane.add(percent); 
fieldPane.add(PacketsSent); 
fieldPane.add(pacsent); 
fieldPane.add(Connectiontype); 
fieldPane.add(conntype); 
fieldPane.add(noofvideossent); 
fieldPane.add(videosend); 

Это имеет один недостаток, что все клетки будут иметь одинаковый размер.В частности, все ячейки ярлыков будут иметь ту же ширину, что и ячейки поля. Это, вероятно, не имеет значения в этом конкретном случае, однако в более общем случае вы хотели бы использовать другой макет, который позволяет первому столбцу оставаться узким и дает всю оставшуюся ширину ко второму столбцу.

GridBagLayout

Вот как бы я сделать это с GridBagLayout:

JPanel fieldPane = new JPanel(new GridBagLayout()); 
Insets insets = new Insets(2, 2, 2, 2); 
GridBagConstraints label = new GridBagConstraints(
    0, 0, 1, 1, 0.0, 0.0, 
    GridBagConstraints.BASELINE_LEADING, GridBagConstraints.NONE, 
    insets, 2, 2); 
GridBagConstraints value = new GridBagConstraints(
    1, 0, 1, 1, 0.0, 0.0, 
    GridBagConstraints.BASELINE_LEADING, GridBagConstraints.HORIZONTAL, 
    insets, 2, 2); 
fieldPane.add(ClientIP, label); 
fieldPane.add(ip, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(ClientPassword, label); 
fieldPane.add(pass, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(Videoname, label); 
fieldPane.add(vname, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(perccomplete, label); 
fieldPane.add(percent, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(PacketsSent, label); 
fieldPane.add(pacsent, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(Connectiontype, label); 
fieldPane.add(conntype, value); 
label.gridy++; 
value.gridy++; 
fieldPane.add(noofvideossent, label); 
fieldPane.add(videosend, value); 

Поскольку я использую GridBagLayout много, я подклассы GridBagConstraints, чтобы сделать свою жизнь немного легче. Мой подкласс имеет, помимо прочего, следующий метод:

public SuperGBC at(int x, int y) { 
    gridx = x; 
    gridy = y; 
    return this; 
} 

Он имеет аналогичные методы anchor(), fill() и insets() для себя инициализацию без указания всех значений. Это делает код более компактным:

JPanel fieldPane = new JPanel(new GridBagLayout()); 
Insets insets = new Insets(2, 2, 2, 2); 
SuperGBC label = new SuperGBC() 
    .anchor(SuperGBC.BASELINE_LEADING) 
    .insets(insets); 
SuperGBC value = new SuperGBC() 
    .anchor(SuperGBC.BASELINE_LEADING) 
    .insets(insets) 
    .fill(GridBagConstraints.HORIZONTAL, 0.0, 0.0); 
fieldPane.add(ClientIP, label.at(0, 0)); 
fieldPane.add(ip, value.at(1, 0)); 
fieldPane.add(ClientPassword, label.at(0, 1)); 
fieldPane.add(pass, value.at(1, 1)); 
fieldPane.add(Videoname, label.at(0, 2)); 
fieldPane.add(vname, value.at(1, 2)); 
fieldPane.add(perccomplete, label.at(0, 3)); 
fieldPane.add(percent, value.at(1, 3)); 
fieldPane.add(PacketsSent, label.at(0, 4)); 
fieldPane.add(pacsent, value.at(1, 4)); 
fieldPane.add(Connectiontype, label.at(0, 5)); 
fieldPane.add(conntype, value.at(1, 5)); 
fieldPane.add(noofvideossent, label.at(0, 6)); 
fieldPane.add(videosend, value.at(1, 6)); 
Смежные вопросы