私はJava Swingにかなり慣れていないので、いくつかの問題に直面しています。
- 余談ですが、かなり大きな Java Swing アプリケーションを作成する場合、コードを分割する最善の方法は何ですか? 私の場合、ボタンで満たされた JToolBar とツールバーで押されたボタンに基づいて変更が行われるメイン JPanel がある Microsoft Word と同じレイアウトを持つアプリケーションが必要です。
以下のコードに示すように、JFrame があり、MainPanel クラスを呼び出してパネルを作成し、ボタン付きのツールバーを追加します。ボタンが押されると、パネルにボタンが追加されます。ボタンをクリックすると問題が発生し、ウィンドウのサイズを変更するまで何も表示されません (私の場合は、画面を手動でドラッグして大きくします)。
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 class MainPanel は ActionListener を実装します{ JPanel mPanel; JToolBar mToolBar; JButton addQuestion; public MainPanel() { mPanel = new JPanel(new BorderLayout()); mToolBar = new JToolBar(); addQuestion = new JButton("テスト");
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); }
}