简体   繁体   English

如何通过单击按钮重新绘制jpanel并在2个面板之间切换

[英]how to repaint a jpanel with button click and also switch between 2 panels

I am trying to repaint a panel with a button click, but its not happening. 我正在尝试通过单击按钮重新绘制面板,但是没有发生。 i tried using many methods like setEnabled(true), setVisible(true), repaint(), but none of these are working. 我尝试使用许多方法,例如setEnabled(true),setVisible(true),repaint(),但这些方法均无效。 And also i want to switch between two panels, like, if i click the "Total Vote" button, one panel should display, when i click on "Departmentwise Vote", another panel should display in the same place. 而且我也想在两个面板之间切换,例如,如果我单击“总投票”按钮,则应显示一个面板,当我单击“部门投票”时,另一个面板应显示在同一位置。

please help. 请帮忙。 Thanks in advance. 提前致谢。

here im providing the code : 这里我提供的代码:

public class RSummary extends JFrame implements ActionListener
{
    JFrame rframe = new JFrame();
    JPanel panel1, panel2, panel3, panel4, panel5;
    JTable table;
    JScrollPane scroll;
    JSplitPane splitPane;
    JButton butx;

   public RSummary()
   {

    rframe.setSize(550,300);
    rframe.setLocationRelativeTo(null);

    setSize(550,300);
        rframe.setTitle("Summary Report");

        /* Total Vote  & Department wise vote buttons */
           panel1= new JPanel();
          JButton but1 = new JButton("TOTAL VOTE");
          JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
          but1.addActionListener(this);
          panel1.add(but1);
          panel1.add(but2);

          /* Report contents according to button */
          panel2 = new JPanel();
         String[] columnNames = {"Name", "Department","Phno","LUID","Select"};
        DefaultTableModel model1 = new DefaultTableModel();
        model1.setColumnIdentifiers(columnNames);
        table = new JTable();
        table.setModel(model1); 
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        scroll = new JScrollPane(table);
        panel2.add(scroll);
        panel2.setVisible(false);


        /* close button */
        panel3 = new JPanel();
        JButton but4= new JButton("CLOSE");
        but4.addActionListener(this);
        panel3.add(but4);


        /* Page heading */
        panel4 = new JPanel();
        JLabel lab =new JLabel("VOTE SUMMARY REPORT");
        panel4.add(lab);


        /* dummy panel */
        panel5 = new JPanel();
        JButton butx = new JButton("Hello butx");
        panel5.add(butx);


    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
    rframe.add(splitPane);
    rframe.add(panel3,BorderLayout.SOUTH);
    rframe.add(panel4,BorderLayout.NORTH);

    rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    rframe.setVisible(true);

}  

    public void actionPerformed(ActionEvent ae)
    { 
String action=ae.getActionCommand();

if(action == "CLOSE")
{
    rframe.setVisible(false);
}
if(action == "TOTAL VOTE")
{
    panel2.setVisible(true);  //this code is not working, i want the solution here. 
}

    }
   public static void main(String args[]) throws ClassNotFoundException, SQLException
   {
        new RSummary();

   } 
    }

The first problem is you're comparing the object references of your String values and not there contents... 第一个问题是您要比较String值的对象引用,而不是内容...

if(action == "TOTAL VOTE")

Because of the way String s are managed by Java, it is very unlikely that these will ever be equal. 由于String由Java管理的方式,它们极不可能相等。

String comparison in Java is done using String#equals Java中的String比较是使用String#equals

if ("TOTAL VOTE".equals(action)) 

Your second problem may be related to the fact the setVisible may not be invalidating the container hierarchy, which would tell the layout framework that the containers need to be updated. 您的第二个问题可能与setVisible可能不会使容器层次结构无效有关,这将告诉布局框架容器需要更新。

You have two solutions, the first would be to call revalidate on the parent container, the second, and better, would be to use a CardLayout , which is designed to just what you are trying to do... 您有两种解决方案,第一种是在父容器上调用revalidate ,第二种是更好的方法是使用CardLayout ,其目的只是为了您要尝试做的事情...

Take a look at How to use Card Layout for more details 看看如何使用Card Layout了解更多详细信息

Update after running the Code 运行代码后更新

You have a series of compounding issues... 您有一系列复杂的问题...

  • You never set the action command of any of the buttons, so when the actionPerformed event is raised, the action is actually null 您永远不会设置任何按钮的操作命令,因此当引发actionPerformed事件时,该action实际上为null
  • RSummary extends from JFrame , yet you create a second JFrame called rframe . RSummaryJFrame扩展而来的,但是您创建了另一个名为rframe JFrame This is very confusing and could potentially lead to more problems if you're not dealing with the correct frame. 这非常令人困惑,如果您处理的框架不正确,可能会导致更多问题。

Start by setting the actionCommand property of your buttons... 首先设置按钮的actionCommand属性...

JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");

Then remove extends JFrame from RSummary , as it is doing nothing but adding to the confusion and adds no benefit 然后从RSummary删除extends JFrame ,因为它除了增加混乱之外什么都不做,也没有任何好处。

Setting a frame invisible will not "close" it. 将框架设置为不可见不会“关闭”它。 Instead use JFrame#dispose 而是使用JFrame#dispose

Finally, making a component visible while it's part of split pane won't resize the split divider. 最后,使组件在拆分窗格中可见时,不会调整拆分分隔符的大小。 Once you've made the corrections, you will need to manually move the divider. 进行更正后,您将需要手动移动分隔线。

You may consider placing a empty panel into the split pane and using a CardLayout , add the other components to it, switching them in and out using the CardLayout 您可以考虑将一个空面板放入拆分窗格中,并使用CardLayout ,向其中添加其他组件,然后使用CardLayout切换进出它们。

Updated with modified code 更新了修改后的代码

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class RSummary extends JFrame implements ActionListener {

    JFrame rframe = new JFrame();
    JPanel panel1, panel2, panel3, panel4, panel5;
    JTable table;
    JScrollPane scroll;
    JSplitPane splitPane;
    JButton butx;

    public RSummary() {

        rframe.setSize(550, 300);
        rframe.setLocationRelativeTo(null);

        setSize(550, 300);
        rframe.setTitle("Summary Report");

        /* Total Vote  & Department wise vote buttons */
        panel1 = new JPanel();
        JButton but1 = new JButton("TOTAL VOTE");
        but1.setActionCommand("TOTAL VOTE");
        JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
        but1.addActionListener(this);
        panel1.add(but1);
        panel1.add(but2);

        /* Report contents according to button */
        panel2 = new JPanel();
        String[] columnNames = {"Name", "Department", "Phno", "LUID", "Select"};
        DefaultTableModel model1 = new DefaultTableModel();
        model1.setColumnIdentifiers(columnNames);
        table = new JTable();
        table.setModel(model1);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        scroll = new JScrollPane(table);
        panel2.add(scroll);
        panel2.setVisible(false);


        /* close button */
        panel3 = new JPanel();
        JButton but4 = new JButton("CLOSE");
        but4.addActionListener(this);
        panel3.add(but4);


        /* Page heading */
        panel4 = new JPanel();
        JLabel lab = new JLabel("VOTE SUMMARY REPORT");
        panel4.add(lab);


        /* dummy panel */
        panel5 = new JPanel();
        JButton butx = new JButton("Hello butx");
        panel5.add(butx);

        splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
        rframe.add(splitPane);
        rframe.add(panel3, BorderLayout.SOUTH);
        rframe.add(panel4, BorderLayout.NORTH);

        rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rframe.setVisible(true);

    }

    public void actionPerformed(ActionEvent ae) {
        String action = ae.getActionCommand();

        if ("CLOSE".equals(action)) {
            rframe.dispose();
        }
        if ("TOTAL VOTE".equals(action)) {
            panel2.setVisible(true);  //this code is not working, i want the solution here. 
            panel2.getParent().revalidate();
        }

    }

    public static void main(String args[]) throws ClassNotFoundException, SQLException {
        new RSummary();

    }

}

To switch panels you can do: 要切换面板,您可以执行以下操作:

rframe.remove (panelToRemove);
rframe.add(panelToShow);

Is this the answer to your question or why do you want to repaint? 这是您问题的答案,还是您为什么要重新粉刷?

Geosearchef Geosearchef

UPDATE: To summarize: MadProgrammer is right, you have to replace if(action == "TOTAL VOTE") by if(action.equals("TOTAL VOTE")) (same for CLOSE) 更新:总结:MadProgrammer是正确的,您必须将if(action == "TOTAL VOTE")替换为if(action.equals("TOTAL VOTE")) (与CLOSE相同)

and you have to add an actionCommand: 并且您必须添加一个actionCommand:

JButton but1 = new JButton("TOTAL VOTE");
but1.addActionListener(this);
but1.setActionCommand("TOTAL VOTE");

To change panels: 更换面板:

if (action.equals("TOTAL VOTE")) {
    try{rframe.remove(panel1;)}catch(Exception e){}//clear window, maybe there is a method
    try{rframe.remove(panel2;)}catch(Exception e){}
    try{rframe.remove(panel3;)}catch(Exception e){}
    rframe.add(panel2);//the panel you want to show
}

Of course, you have to get references to the panels to actionPerformed(ActionEvent ae) . 当然,您必须获得对actionPerformed(ActionEvent ae)面板的引用。

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

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