我对Java Swing还是很陌生,但是遇到了一些问题。
在我的情况下,我希望有一个布局与Microsoft Word一样的应用程序,其中的JToolBar充满了按钮,而主JPanel则根据在工具栏中按下的按钮进行了更改。
public class Main {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MathMaker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
//MainToolBar mainTB = new MainToolBar();
MainPanel mainPanel = new MainPanel();
frame.getContentPane().add(mainPanel.getGUI(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
公共(public)类MainPanel实现ActionListener {
JPanel mPanel;
JToolBar mToolBar;
JButton addQuestion;
公共(public)MainPanel(){
mPanel = new JPanel(new BorderLayout());
mToolBar =新的JToolBar();
addQuestion = new JButton(“test”);
addQuestion.addActionListener(this); mPanel.setLayout(new BorderLayout()); mPanel.setBackground(new Color(248, 213, 131)); mPanel.setPreferredSize(new Dimension(200, 180)); mToolBar.add(addQuestion); mPanel.add(mToolBar, BorderLayout.PAGE_START);}public JComponent getGUI(){ return mPanel;}@Overridepublic void actionPerformed(ActionEvent e) { JButton temp = new JButton("temp"); mPanel.add(temp);}
最佳答案
你应该重新验证你的面板
@Override
public void actionPerformed(ActionEvent e) {
JButton temp = new JButton("temp");
mPanel.add(temp);
mPanel.revalidate();
mPanel.repaint();
}