[英]How to view another jPanel containing many sub-jPanels from same JFrame in netbeans (Java Swing)
我想从按钮事件动作中显示另一个jPanel。 例如
private void jButtonMouseClicked(MouseEvent e)
{
getContentPane().removeAll();
update(getGraphics());
//code to show another jPanel containing different sub-panels
}
当我使用
CardLayout
,一次只能使用一个面板,难道没有一种方法可以在一个框架中添加多个面板,然后在事件切换到同一框架中的另一组多个面板之后,又如何呢?
确实,每次使用CardLayout
只能显示一个JPanel
,但这并不能阻止您在使用它时显示多个JPanel
。
你需要做的card
(在JPanel
显示多是在当前视图中显示) JPanel
秒。
例如:
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CardLayoutWithMultiplePanes {
private JFrame frame;
private JPanel pane;
private JPanel cardsPane;
private JPanel[] cards;
private CardLayout cl;
private JButton nextButton;
private JButton previousButton;
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutWithMultiplePanes()::createAndShowGui);
}
private void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
previousButton = new JButton("Previous");
nextButton = new JButton("Next");
cl = new CardLayout();
cardsPane = new JPanel(cl);
cards = new JPanel[2];
for (int i = 0; i < cards.length; i++) {
cards[i] = new JPanel();
cards[i].setLayout(new GridLayout(2, 1));
cards[i].add(new CustomPane((i + 1) % 2 == 0 ? Color.BLUE : Color.RED));
cards[i].add(new CustomPane((i + 1) % 2 == 0 ? Color.GREEN : Color.MAGENTA));
cardsPane.add(cards[i]);
}
Box box = Box.createHorizontalBox();
box.add(previousButton);
box.add(Box.createHorizontalGlue());
box.add(nextButton);
previousButton.addActionListener(listener);
nextButton.addActionListener(listener);
pane.add(cardsPane);
pane.add(box);
frame.add(pane);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private ActionListener listener = e -> {
if (e.getSource().equals(previousButton)) {
cl.previous(cardsPane);
} else if (e.getSource().equals(nextButton)) {
cl.next(cardsPane);
}
};
@SuppressWarnings("serial")
class CustomPane extends JPanel {
private Color color;
public CustomPane(Color color) {
this.color = color;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
}
}
上面的代码示出了单个JPanel
包含2个JPanel
S,其中每个JPanel
具有其自己的背景颜色(和可能含有自己的组件,如JLabel
或JButton
,等等)
我希望这可以使您对要尝试的操作有所了解。
JFrame
作为笔记本。 JPanel
作为表。 CardLayout
作为您的手指传递页面(前进和后退) 在每个工作表( JPanel
)中,您都可以拥有想要的任何东西(甚至可以粘贴到1张以上),这是相同的原理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.