我有两节课。主类有一个JFrame,并且有一个按钮,在单击按钮后,它会从另一个类加载一个面板,并在框架的按钮中找到它。
我可以实现它,但我必须重新调整框架大小,然后显示其他面板,否则它将被隐藏。
这是我的代码:
public class PanelLoader {
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JPanel mainPanel = new JPanel(new BorderLayout());
JButton press = new JButton("press");
press.addActionListener(new ActionListener(){ //ActionListener, on click it opens a file choser,
@Override //selects a directory then gives it to srcDirField
public void actionPerformed(java.awt.event.ActionEvent event){
JPanel mine = ClassWhereStored.newJPanel();
mainPanel.add(mine, BorderLayout.SOUTH);
}
});
mainPanel.add(press, BorderLayout.NORTH);
frame.add(mainPanel);
frame.setVisible(true);
}
}
第二课程:
public class ClassWhereStored {
public static JPanel newJPanel(){
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
JLabel test= new JLabel("Some Text");
panel.add(test);
return panel;
}
}
那么只有在重新调整框架大小时,此框架才显示附加面板有什么问题?
答案 0 :(得分:2)
使用CardLayout
,添加空白/空JPanel
和您要显示的JPanel
。单击该按钮后,只需让CardLayout
切换面板即可。
有关详细信息,请参阅How to Use CardLayout
例如......
package javaapplication765;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BasePane extends JPanel {
public BasePane() {
setLayout(new BorderLayout());
CardLayout cl = new CardLayout();
JPanel mainView = new JPanel(cl);
mainView.add(new JPanel(), "empty");
mainView.add(new BananaPane(), "banana");
add(mainView);
JButton btn = new JButton("Fruit loop");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cl.show(mainView, "banana");
}
});
add(btn, BorderLayout.NORTH);
}
}
public class BananaPane extends JPanel {
public BananaPane() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(25, 25, 25, 25));
add(new JLabel("I'm a banana"));
}
}
}
答案 1 :(得分:2)