Toa*_*ast 4 java swing jpanel jbutton jtoolbar
我是Java Swing的新手,我遇到了一些问题.
因此,如下面的代码所示,我有一个JFrame,我调用MainPanel类来创建一个面板并添加一个带按钮的ToolBar.按下按钮时,它会向面板添加一个按钮.在您调整窗口大小之前单击按钮时没有显示问题(在我的情况下,我只需手动拖动屏幕使其变大).
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();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
public class MainPanel implements ActionListener{
JPanel mPanel;
JToolBar mToolBar;
JButton addQuestion;
public MainPanel() {
mPanel = new JPanel(new BorderLayout());
mToolBar = new 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;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton temp = new JButton("temp");
mPanel.add(temp);
}
Run Code Online (Sandbox Code Playgroud)
}
您应该重新验证您的面板
@Override
public void actionPerformed(ActionEvent e) {
JButton temp = new JButton("temp");
mPanel.add(temp);
mPanel.revalidate();
mPanel.repaint();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3115 次 |
| 最近记录: |