简体   繁体   English

如何在Swing(Java)中的现有jPanel上画一条线?

[英]How to draw a line on a existing jPanel in Swing (Java)?

I want to draw a simple line on my existing jPanel called mypanel . 我想在现有的jPanel上画一条简单的线,称为mypanel I want to do it like this: 我想这样做:

    mypanel.drawLine(0,0, 20, 35);

The numbers are the X and Y Position of Point 1 and the others are X and Y Position of Point 2, between Point 1 and Point 2 there should be my line. 数字是点1的X和Y位置,其他数字是点2的X和Y位置,在点1和点2之间应该有我的行。 Is there a easy way without adding an additional jPanel on my jFrame? 有没有一种简单的方法,而无需在我的jFrame上添加额外的jPanel? Thank you in advance. 先感谢您。

Edit: 编辑:

My GUI Code: 我的GUI代码:

    import java.awt.Graphics;
import javax.swing.JPanel;

public class main_panel extends javax.swing.JFrame {

    public main_panel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 163, Short.MAX_VALUE)
        );

        jButton1.setText("Set Values");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 280, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawLine(0, 0, 20, 35);
            }

        };
    }                                        

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main_panel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel panel;
    // End of variables declaration                   

}

Something like this 像这样

myPanel = new JPanel() {
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawLine(0,0, 20, 35);
    };

But your suggestion with two panels is better. 但是您建议使用两个面板更好。

Here is the full GUI code (each click on "Set Values" will toggle the line). 这是完整的GUI代码(每次单击“设置值”将切换该行)。

import java.awt.Graphics;
import javax.swing.JPanel;

public class main_panel extends javax.swing.JFrame {

    private boolean drawLine;

    public main_panel() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panel = new javax.swing.JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (drawLine) {
                    g.drawLine(0, 0, 20, 35);
                }
            }
        };
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 163, Short.MAX_VALUE)
        );

        jButton1.setText("Set Values");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 280, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        drawLine = !drawLine;
        panel.repaint();
    }                                        

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(main_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main_panel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel panel;
    // End of variables declaration                   

}

Is there a easy way without adding an additional jPanel on my jFrame? 有没有一种简单的方法,而无需在我的jFrame上添加额外的jPanel?

This statement is hard to interpret by itself and out of context. 这种说法很难单独解释,也很难脱离上下文。 What you must do is override paintComponent as is noted above for the component that you want to display the line it, nothing more, and nothing less. 您必须要做的是,覆盖上面要指出的要显示行的组件的paintComponent ,仅此而已。 How you do this will depend on the structure of your program, something we know little about at present. 如何执行将取决于程序的结构,这是我们目前所知甚少的。

Please look at this link for more details. 请查看此链接以获取更多详细信息。

You also state: 您还声明:

I added exactly the code from @Sergiy Medvynskyy into my application, there are no errors the line just doesn't appear on the panel. 我将来自@Sergiy Medvynskyy的代码准确地添加到了我的应用程序中,没有错误,只是该行没有出现在面板上。 With the solution with two panels I want to add another jPanel on my existing jPanel with the line on it, maybe it's easier to implement. 对于具有两个面板的解决方案,我想在现有jPanel上添加另一个jPanel,并在上面加上一行,这也许更容易实现。

That's possible as long as your original JPanel is set up to receive a 2nd JPanel, in other words has a layout manager that will allow easy addition of the 2nd JPanel, and a location on it where the added JPanel won't cover anything else of importance. 只要您将原始JPanel设置为可以接收第二个JPanel,这就是可能的,换句话说,它具有一个布局管理器,可以轻松添加第二个JPanel,并且在该位置上添加的JPanel不会覆盖其他任何内容。重要性。 For instance if the first JPanel uses BorderLayout, then the second with the drawing code could be added BorderLayout.CENTER to display its drawing in the middle of the first. 例如,如果第一个JPanel使用BorderLayout,那么可以将第二个带有绘图代码的JPanel添加到BorderLayout.CENTER以在第一个中间显示其绘图。

But again, details are key. 但同样,细节是关键。 If you need more direct help, then show your GUI code, preferably an mcve . 如果您需要更多直接帮助,请显示您的GUI代码,最好是mcve


In your posted code, you create a 2nd JPanel but you add it to nothing, so of course it's not displayed. 在您发布的代码中,您创建了第二个JPanel,但是您没有将其添加到任何内容,因此当然不会显示它。 Just because you use the same panel variable has no effect, and in order for the 2nd JPanel to be seen, it must be added. 仅仅因为您使用相同的面板变量无效,并且为了显示第二个JPanel,必须添加它。 You need to learn layout managers and learn to use the human-usable managers such as BorderLayout for this to work. 您需要学习布局管理器,并学习使用诸如BorderLayout之类的可人类使用的管理器,才能使其正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM