您好我的申请有问题。持有JTextArea的面板与包含menuBar的面板重叠。我想自定义我的GUI应用程序,但无法修复重叠。下面是我的代码:我导入了所有必需的apis。
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ClientPanels extends JPanel{
private JMenu fileM, editM, styleM;
private JTextArea textArea;
private JMenuBar menuBar;
private JScrollPane scpane;
private JPanel panel1;
private JPanel panel2;
private JMenuItem aboutI, openI, saveI, cutI, copyI, pasteI, exitI;
private GridBagConstraints g;
public ClientPanels() {
initialize();
}
private void initialize(){
//initializing and setting up my data
setLayout(new GridBagLayout());
textArea2 = new JTextArea(40, 50);
JScrollPane scpane = new JScrollPane(textArea2);
panel1 = new JPanel(new BorderLayout());
panel2 = new JPanel(new BorderLayout());
//menuitems
openI = new JMenuItem("Open");
saveI = new JMenuItem("Save");
exitI = new JMenuItem("Exit");
copyI = new JMenuItem("Copy");
pasteI = new JMenuItem("Paste");
aboutI = new JMenuItem("About");
fileM = new JMenu("File");
editM = new JMenu("Edit");
styleM = new JMenu("Style");
fileM.add(openI);
fileM.add(saveI);
fileM.add(aboutI);
fileM.add(exitI);
editM.add(copyI);
editM.add(pasteI);
//adding the menu to the menuBars
menuBar = new JMenuBar();
menuBar.add(fileM);
menuBar.add(editM);
menuBar.add(styleM);
panel1.add(menuBar,BorderLayout.NORTH);
panel2.add(scpane, BorderLayout.CENTER);
//adding the sub-panels to the main panel
addComp(panel1,0,0,0.5,0.0,0,0,GridBagConstraints.NORTHEAST,GridBagConstraints.HORIZONTAL);
addComp(panel2,4,1,3,10,0,10, GridBagConstraints.WEST, GridBagConstraints.NONE);
}
//adding components to panel using GridBagLayout as the layout manager
private void addComp(JPanel panel, int Xpos, int Ypos, double wx,double wy,
int compWidth, int compHeight, int place, int stretch)
{
GridBagConstraints g = new GridBagConstraints();
g.gridx = Xpos;
g.gridy = Ypos;
g.weightx = wx;
g.weighty= wy;
g.gridwidth = compWidth;
g.gridheight = compHeight;
g.insets = new Insets(5,5,5,5);
g.anchor = place;
g.fill = stretch;
add(panel, g);
}
}
主要方法:
import javax.swing.SwingUtilities;
public class TestJavaClient {
private ClientPanels panels;
public TestJavaClient()
{
JFrame frame = new JFrame();
panels = new ClientPanels();
frame.setSize(800,590);
frame.setLocationRelativeTo(null);
frame.add(panels);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new TestJavaClient();
}
});
}
}
答案 0 :(得分:1)
变化:
panel1.add(menuBar,BorderLayout.NORTH);
类似的东西(你需要重构代码):
frame.setJMenuBar(menuBar);
但正如评论中所提到的,MCVE会得到更好的答案。