【问题标题】:Why JLabel don't appear anymore after I press the buttons?为什么按下按钮后 JLabel 不再出现?
【发布时间】:2017-02-15 17:13:10
【问题描述】:

我试图让按钮在 JTextField 旁边显示一个 Jlabel,但是当我按下时,JLabels 就不再出现了。

如果它引起问题,我对一些框和标签使用相同的坐标,我希望它们根据我按下的按钮出现在同一个位置。

单张图的问题:

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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;

public class partegrafica extends JFrame{
    private static final long serialVersionUID = 1L;
    JPanel palumno,pprofe,ptutor,ptodo;
    JButton balumno,brofe,butor,avance,retroceso,guardar;
    JTextField boxname,boxdni,boxfecha,boxnrp,boxcial,boxcentrodestino,boxespecialidad,boxsalario,boxciclo;
    JLabel lavacia,lavaciaver, laname,ladni,lafecha,lanrp,lacial,laciclo,lacentrodestino,laespecialidad,lasalario,latitulo;

    public partegrafica(String[] args) {
    super("Catalogador de Humanos");

    GridBagConstraints cor = new GridBagConstraints();
    cor.anchor = GridBagConstraints.NORTHWEST;
    cor.weightx=1;
    cor.weighty=1;

setLayout(new GridBagLayout());

ptodo= new JPanel(new GridBagLayout());
setPreferredSize(new Dimension(1200, 800));
latitulo =new JLabel("Escoge perfil a introducir");
cor.gridx=0;
cor.gridy=0;
cor.gridheight=1;
cor.gridwidth=3;
ptodo.add(latitulo, cor);
balumno = new JButton("Insertar alumno");
cor.gridx=0;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(balumno, cor);
brofe = new JButton("Insertar Profesor");
cor.gridx=1;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(brofe, cor);
butor= new JButton("Insertar Tutor");
cor.gridx=2;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(butor, cor);
lavacia=new JLabel("                  ");
cor.gridx=3;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lavacia, cor);
retroceso=new JButton("<");
cor.gridx=4;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(retroceso, cor);
avance=new JButton(">");
cor.gridx=5;
cor.gridy=1;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(avance, cor);
laname=new JLabel("Nombre");
cor.gridx=0;
cor.gridy=3;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(laname, cor);
boxname = new JTextField(10);
cor.gridx=1;
cor.gridy=3;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxname, cor);
ladni= new JLabel("DNI");
cor.gridx=0;
cor.gridy=4;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(ladni, cor);
boxdni = new JTextField(10);
cor.gridx=1;
cor.gridy=4;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxdni, cor);
lafecha= new JLabel("Fecha Nacimiento");
cor.gridx=0;
cor.gridy=5;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lafecha, cor);
boxfecha= new JTextField(10);
cor.gridx=1;
cor.gridy=5;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxfecha, cor);
lanrp= new JLabel("NRP");
lanrp.setVisible(false);
cor.gridx=0;
cor.gridy=6;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lanrp, cor);
boxnrp= new JTextField(10);
boxnrp.setVisible(false);
cor.gridx=1;
cor.gridy=6;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxnrp, cor);
lacial= new JLabel("CIAL");
lacial.setVisible(false);
cor.gridx=0;
cor.gridy=6;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lacial, cor);
boxcial= new JTextField(10);
boxcial.setVisible(false);
cor.gridx=1;
cor.gridy=6;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxcial, cor);
laespecialidad= new JLabel("Especialidad (nº)");
//laespecialidad.setVisible(false);
cor.gridx=0;
cor.gridy=7;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(laespecialidad, cor);
boxespecialidad= new JTextField(10);
//boxespecialidad.setVisible(false);
cor.gridx=1;
cor.gridy=7;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxespecialidad, cor);
laciclo= new JLabel("Ciclo");
//laciclo.setVisible(false);
cor.gridx=0;
cor.gridy=7;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(laciclo, cor);
boxciclo=new JTextField(10);
//boxciclo.setVisible(false);
cor.gridx=1;
cor.gridy=7;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxciclo, cor);
lacentrodestino= new JLabel("Centro Destino");
//lacentrodestino.setVisible(false);
cor.gridx=0;
cor.gridy=8;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lacentrodestino, cor);
boxcentrodestino= new JTextField(10);
//boxcentrodestino.setVisible(false);
cor.gridx=1;
cor.gridy=8;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxcentrodestino, cor);
lasalario= new JLabel("Salario:");
lasalario.setVisible(true);
cor.gridx=0;
cor.gridy=9;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(lasalario, cor);
boxsalario= new JTextField(10);
//boxsalario.setVisible(false);
cor.gridx=1;
cor.gridy=9;
cor.gridheight=1;
cor.gridwidth=1;
ptodo.add(boxsalario, cor);
guardar= new JButton("Guardar");
cor.gridx=2;
cor.gridy=3;
cor.gridheight=3;
cor.gridwidth=1;
ptodo.add(guardar, cor);

balumno.addActionListener(new AAlumno());
brofe.addActionListener(new AProfe());
butor.addActionListener(new ATutor());
avance.addActionListener(new Avanzar());
retroceso.addActionListener(new Retroceso());
guardar.addActionListener(new Guardar());

add(ptodo, cor);

ptodo.setVisible(true);
pack();
}

    public class AAlumno implements ActionListener{
        public void actionPerformed(ActionEvent e){

        lacial.setVisible(true);
        boxcial.setVisible(true);
        laciclo.setVisible(true);
        boxciclo.setVisible(true);

        lanrp.setVisible(false);
        boxnrp.setVisible(false);
        laespecialidad.setVisible(false);
        boxespecialidad.setVisible(false);
        lacentrodestino.setVisible(false);
        boxcentrodestino.setVisible(false);
        lasalario.setVisible(false);
        boxsalario.setVisible(false);

        lanrp.setText("");
        boxnrp.setText("");
        laespecialidad.setText("");
        boxespecialidad.setText("");
        lacentrodestino.setText("");
        boxcentrodestino.setText("");
        lasalario.setText("");
        boxsalario.setText("");
        lacial.setText("");
        boxcial.setText("");
        laciclo.setText("");
        boxciclo.setText("");
        validate();

        }
    }
    public class AProfe implements ActionListener{
        public void actionPerformed(ActionEvent e){

        lacial.setVisible(false);
        boxcial.setVisible(false);
        laciclo.setVisible(false);
        boxciclo.setVisible(false);

        lanrp.setVisible(true);
        boxnrp.setVisible(true);
        laespecialidad.setVisible(true);
        boxespecialidad.setVisible(true);
        lacentrodestino.setVisible(true);
        boxcentrodestino.setVisible(true);
        lasalario.setVisible(true);
        boxsalario.setVisible(true);
        lacial.setText("");
        boxcial.setText("");
        laciclo.setText("");
        boxciclo.setText("");
        lanrp.setText("");
        boxnrp.setText("");
        laespecialidad.setText("");
        boxespecialidad.setText("");
        lacentrodestino.setText("");
        boxcentrodestino.setText("");
        lasalario.setText("");
        boxsalario.setText("");
        validate();
        }
    }
    public class ATutor implements ActionListener{
        public void actionPerformed(ActionEvent e){

        }
    }
    public class Avanzar implements ActionListener{
        public void actionPerformed(ActionEvent e){

        }
    }
    public class Retroceso implements ActionListener{
        public void actionPerformed(ActionEvent e){

        }
    }
    public class Guardar implements ActionListener{
        public void actionPerformed(ActionEvent e){

        }
    }
        }

【问题讨论】:

  • 请考虑展示您想要实现的目标和实际看到的图像。不用担心无法发布它们。如果您尝试发布它们,我们可以为您修复它,以便它们显示出来。

标签: java swing jlabel gridbaglayout


【解决方案1】:

我的主要建议是使用 JPanel 交换 JPanel“视图”,但如果您绝对需要使用上述代码,则不要交换 JLabels,而是交换它们显示的 文本使用setText(...) 方法。并且不要让 JLabel 可见或不可见,如果要使其不可见,则不要通过 setText("") 向它们提供任何文本。

CardLayout 教程可以在这里找到:CardLayout tutorial

以 CardLayout 为例:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class SwapViews extends JPanel {
    public static final String ALUMNO = "Insertar Alumno";
    public static final String PROFESSOR = "Insertar Profesor";
    public static final String[] ALUMNO_TEXTS = { "Nombre", "DNI", "Fecha Nacimiento", "CIAL",
            "Ciclo" };
    public static final String[] PROFESOR_TEXTS = { "Nombre", "DNI", "Fecha Nacimiento", "NRP",
            "Especialidad (nº)", "Centro Destino", "Salario:", };
    private static final int EB_GAP = 2;
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardHolderPanel = new JPanel(cardLayout);
    private DataEntryPanel alumnoPanel = new DataEntryPanel(ALUMNO, ALUMNO_TEXTS);
    private DataEntryPanel profesorPanel = new DataEntryPanel(PROFESSOR, PROFESOR_TEXTS);

    public SwapViews() {
        JPanel alumnoWrapperPanel = new JPanel(new BorderLayout());
        alumnoWrapperPanel.add(alumnoPanel, BorderLayout.PAGE_START);

        JPanel profesorWrapperPanel = new JPanel(new BorderLayout());
        profesorWrapperPanel.add(profesorPanel, BorderLayout.PAGE_START);

        cardHolderPanel.add(alumnoWrapperPanel, ALUMNO);
        cardHolderPanel.add(profesorWrapperPanel, PROFESSOR);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new ShowCardAction(ALUMNO, KeyEvent.VK_A)));
        buttonPanel.add(new JButton(new ShowCardAction(PROFESSOR, KeyEvent.VK_P)));

        setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
        setLayout(new BorderLayout());
        add(cardHolderPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_END);
    }

    private class ShowCardAction extends AbstractAction {
        public ShowCardAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            cardLayout.show(cardHolderPanel, getValue(NAME).toString());
        }
    }

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

        JFrame frame = new JFrame("SwapViews");
        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(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class DataEntryPanel extends JPanel {
    private static final int COLUMNS = 10;
    private static final Insets WEST_INSETS = new Insets(4, 4, 4, 4);
    private static final Insets EAST_INSETS = new Insets(4, 10, 4, 4);
    private String[] labels;
    private Map<String, JTextField> fieldMap = new HashMap<>();

    public DataEntryPanel(String title, String[] labels) {
        super(new GridBagLayout());
        setBorder(BorderFactory.createTitledBorder(title));
        this.labels = labels;
        for (int i = 0; i < labels.length; i++) {
            String text = labels[i];
            JLabel label = new JLabel(text);
            JTextField textField = new JTextField(COLUMNS);
            fieldMap.put(text, textField);

            add(label, getGbc(0, i));
            add(textField, getGbc(1, i));
        }
    }

    public String[] getLabels() {
        return labels;
    }

    public static GridBagConstraints getGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.insets = x == 0 ? WEST_INSETS : EAST_INSETS;
        return gbc;
    }

    public String getLabelText(String key) {
        return fieldMap.get(key).getText();
    }

}

您的代码可能无法正常工作,因为您在同一个 GridBagLayout 位置添加了多个组件。再次保留一组可重复使用的 JLabel 会更好。

根据我的评论,您还将一些 JLabel 的文本设置为您不希望这样做的“可见”。仔细检查您的 ActionListeners 以了解我的意思。

【讨论】:

  • 这可能是一个解决方案,我将在接下来的几分钟内这样做。但是......我想知道为什么这段代码不能正常工作的原因。只是为了避免将来发生类似情况。
  • @M.M.:您可能无法将组件添加到相同的网格布局位置而不会有副作用的风险。但无论如何,有更清洁的解决方案。请参阅上面的修改。
  • @M.M.:您还设置了一些 JLabel 的文本,这些 JLabels 设置为您不希望这样做的 "" 可见。仔细检查您的 ActionListener 以了解我的意思。
  • 这看起来太棒了。正如您可能已经看到的那样,我完全是一个初学者,而且还没有使用过那种卡片布局,但实际上它看起来很酷。但是,我尝试做的是在右侧添加一个面板,用户可以在其中左右导航存储的配置文件。干得好!
【解决方案2】:

我找到了标签消失的原因。我将所有标签设置为按钮内没有文本。仅此而已。一个愚蠢的错误。

【讨论】:

  • 是的,我也发现了这一点,并在您发布此内容时添加评论。校对,校对,再校对。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 2013-04-02
  • 1970-01-01
相关资源
最近更新 更多