本文介绍了在同一帧中有多个面板时,如何在特定的JPanel中绘制-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已更新-这与我昨天发布的以下链接有关.

Updated - this is related with the following link I posted yesterday.

https://stackoverflow.com/questions/15916360/swing -gui-应用程序在Java中具有多个框架

如果在这里做错了事,我深表歉意,我尝试在上一篇文章中写,但在评论框之外找不到其他方法.

I apologize if I am doing something wrong here, I tried to write in my previous post and I couldn't find a way to do it beyond the comments box.

我对代码进行了一些更改,现在我正在使用3个JPanels.我为每个面板创建了一个类,但主要面板除外,其他面板将保留在CardLayout中.主面板是在我的主类和应用程序中同时创建的.现在,当我按下一个按钮时,我试图在两个面板之一中画一个幸福的脸,但是它不起作用.

I did some changes on my code, now I am working with 3 JPanels. I created a class for each panel except the main one that will hold in a CardLayout the other two. The main panel is created in my main class and application at the same time.Now I am trying to paint a happy face in one of the two panels when I press a button but it doesn't work.

import statements;


public class JDataAnalyzerGui extends JFrame {

private static final String INTRO = "welcome";
private static final String OPERATIONS = "operations";
private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private WelcomePanel welcomePanel = new WelcomePanel();
private OperationPanel operationPanel = new OperationPanel();
private ReadFiles aFileReader;

public JDataAnalyzerGui() {

// adding panels to the main panel

    mainPanel.add(welcomePanel.getMainComponent(), INTRO);
    mainPanel.add(operationPanel.getMainComponent(), OPERATIONS);

    welcomePanel.addAcceptActionListener(new ActionListener() {    //moves to next view where the buttons are and were the drawing should happen

        @Override
        public void actionPerformed(ActionEvent e) {
            int input = Integer.parseInt(welcomePanel.userInput.getText());
            boolean isValid = isOptionValid(input);
            if(isValid) {
                cardlayout.show(mainPanel, OPERATIONS);
                performActions(aFileReader);
            }
        }
    });

    operationPanel.addReturnActionListener(new ActionListener() {  //returns to welcome window
        @Override
        public void actionPerformed(ActionEvent e) {
            Graphics pen = getGraphics();
            Object source = e.getSource();
            if(source == operationPanel.aButton8) {
                operationPanel.results.setText(null);
                welcomePanel.userInput.setText(null);
                cardlayout.show(mainPanel, INTRO);
            }

//当按下button1时,我想从operationPanel在panel2上绘制一个String.

// when button1 is pressed I want to draw a String on panel2 from operationPanel.

            else if(source == operationPanel.aButton1) {

                operationPanel.results.setText("The maximun opening value was " + Calculations.hiOpenValue);
                operationPanel.panel2.setBackground(Color.GREEN);
                pen.setFont(new Font("Broadway", Font.ITALIC, 12));
                pen.setColor(Color.MAGENTA);
                pen.drawString("this is a test", 20, 40);

            }
            // code for the rest of buttons
        }
    });
}


private boolean isOptionValid(int option) {

    switch(option) {

    case 1:
        aFileReader = new ReadFiles("newMSFT.csv");
        return true;

    case 4:
        Object[] options = { "YES", "CANCEL" };
        int reply = JOptionPane.showOptionDialog(null, "Are you sure you want to go?", "Confirm Exit", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
        if(reply == JOptionPane.YES_OPTION)
        System.exit(0);
        return false;

    default:
        JOptionPane.showMessageDialog(null, "That is an invalid option. Please try again");
        return false;
    }
}


public void performActions(ReadFiles obj) {
    // code for numeric calculations
}


private JComponent getMainComponent() {
    return mainPanel;
}

private static void createAndShowUI() {

    JFrame frame = new JFrame("Data Analyzer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new JDataAnalyzerGui().getMainComponent());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}


public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            createAndShowUI();
        }
    });
}
}

------------------------------ Jpanel行动 导入语句;

------------------------------ Operation Jpanel import statements;

class OperationPanel {

JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel(new FlowLayout());
JPanel panel2 = new JPanel(new FlowLayout());
JPanel panel3 = new JPanel(new FlowLayout());
JLabel results = new JLabel ("");

JButton aButton1 = new JButton("Max Open");;   // 8 buttons in total, this is the one for painting

JButton aButton8 = new JButton("Return to Main");

public OperationPanel() {

    mainPanel.setLayout(new GridLayout(3, 1));
    mainPanel.add(panel1);
    mainPanel.add(panel3);
    panel2.setBackground(Color.WHITE);
    mainPanel.add(panel2);
    panel1.add(aButton1);
    // adding all buttons to panel1
    panel2.add(results);

}

public JComponent getMainComponent() {
    return mainPanel;
}

public void addReturnActionListener(ActionListener listener) {   // el que retorna a welcome view
    aButton8.addActionListener(listener);
    aButton1.addActionListener(listener);
    //addActionListener for all buttons
}

}

--------------------欢迎面板 类WelcomePanel {

-------------------- Welcome panel class WelcomePanel {

private JPanel mainPanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel(new GridLayout(5,1));
JPanel panel3 = new JPanel(new FlowLayout());
    JLabel greetings = new JLabel("Welcome to Data Analizer");
Font bigFont = new Font("Comic Sans", Font.BOLD, 30);
JLabel label1 = new JLabel("Please select one of these options:");
JLabel label2 = new JLabel("1. newMSFT.csv");
JLabel label3 = new JLabel("2. XXX.csv");
JLabel label4 = new JLabel("3. YYY.csv");
JLabel label5 = new JLabel("4. QUIT");
Font bigFont2 = new Font("Arial", Font.BOLD, 20);
JTextField userInput = new JTextField(10);
JButton aButton = new JButton("Accept");

public WelcomePanel() {

    mainPanel.setLayout(new GridLayout(3, 1));
    greetings.setFont(bigFont);
    label1.setFont(bigFont2);
    label2.setFont(bigFont2);
    label3.setFont(bigFont2);
    label4.setFont(bigFont2);
    label5.setFont(bigFont2);

    mainPanel.add(panel1);
    mainPanel.add(panel2);
    mainPanel.add(panel3);
    panel1.add(greetings);
    panel2.add(label1);
    panel2.add(label2);
    panel2.add(label3);
    panel2.add(label4);
    panel2.add(label5);
    panel3.add(userInput);
    panel3.add(aButton);

    }

public void addAcceptActionListener(ActionListener listener) {  // este es el que llama a segunda ventana o view
    aButton.addActionListener(listener);
    userInput.addActionListener(listener);
}

public JComponent getMainComponent() {
    return mainPanel;
}

}

我不知道如何绘制特定的面板.

I can't figure out how to draw in an specific panel.

谢谢

推荐答案

您可以...

使用玻璃窗格...

You could...

Use the glass pane...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class TestGlassPane04 {

    public static void main(String[] args) {
        new TestGlassPane04();
    }

    public TestGlassPane04() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(2, 2, 10, 10));
                frame.add(createBox(1));
                frame.add(createBox(2));
                frame.add(createBox(3));
                frame.add(createBox(4));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setGlassPane(new GlassPane());
                frame.getGlassPane().setVisible(true);
                frame.setVisible(true);
            }
        });
    }

    protected JLabel createBox(int box) {
        JLabel label = new JLabel("Box " + box);
        label.setBorder(new CompoundBorder(new LineBorder(Color.GRAY), new EmptyBorder(10, 10, 10, 10)));
        return label;
    }

    public class GlassPane extends JPanel {

        private BufferedImage background;

        public GlassPane() {
            setOpaque(false);
            try {
                background = ImageIO.read(getClass().getResource("/sillydash.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (background != null) {
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g2d.drawImage(background, x, y, this);
            }
            g2d.dispose();
        }
    }

}

看看如何使用根窗格有关更多详细信息...

Take a look at How to use Root Panes for more details...

使用JXLayer/ JLayer 来完成更多工作玻璃窗格的本地化版本...

Use a JXLayer/JLayer to accomplish a more localized version of a glass pane...

这篇关于在同一帧中有多个面板时,如何在特定的JPanel中绘制-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 16:26
查看更多