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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34596194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:05:44  来源:igfitidea点击:

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

javaswinggraphicsjpaneldraw

提问by Pascal Ackermann

I want to draw a simple line on my existing jPanel called mypanel. I want to do it like this:

我想在我现有的 jPanel 上画一条简单的线,名为mypanel. 我想这样做:

    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. Is there a easy way without adding an additional jPanel on my jFrame? Thank you in advance.

数字是点1的X和Y位置,其他是点2的X和Y位置,点1和点2之间应该有我的线。有没有一种简单的方法而不在我的 jFrame 上添加额外的 jPanel?先感谢您。

Edit:

编辑:

My GUI Code:

我的图形用户界面代码:

    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                   

}

回答by Sergiy Medvynskyy

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                   

}

回答by Hovercraft Full Of Eels

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 paintComponentas is noted above for the component that you want to display the line it, nothing more, and nothing less. How you do this will depend on the structure of your program, something we know little about at present.

这句话本身很难解释,也很难断章取意。您必须做的是覆盖paintComponent上面提到的要显示它的行的组件,仅此而已,仅此而已。你如何做到这一点取决于你的程序结构,我们目前对此知之甚少。

Please look at this linkfor 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. 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.

我将来自@Sergiy Medvynskyy 的代码准确添加到我的应用程序中,没有错误,只是面板上没有出现该行。对于带有两个面板的解决方案,我想在我现有的 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. 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 设置为接收第二个 JPanel,即具有允许轻松添加第二个 JPanel 的布局管理器,以及在其上添加的 JPanel 不会覆盖任何其他内容的位置,这是可能的重要性。例如,如果第一个 JPanel 使用 BorderLayout,那么第二个带有绘图代码的可以添加 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. 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. You need to learn layout managers and learn to use the human-usable managers such as BorderLayout for this to work.

在您发布的代码中,您创建了第二个 JPanel,但您没有添加任何内容,因此当然不会显示它。仅仅因为您使用相同的面板变量没有效果,并且为了看到第二个 JPanel,必须添加它。您需要学习布局管理器并学习使用人类可用的管理器(例如 BorderLayout)才能使其工作。