我正在学习Java课程,我们正在学习Swing(我知道,我知道,JavaFX是最新的......)。无论如何,我有GridBagLayout工作,但由于某种原因我的JMenuBar不会显示背景颜色。我做了一些挖掘,但没有找到任何东西。这是我的代码:
package com.company;
import java.awt.*;
import javax.swing.*;
public class BasicGraphics {
public static void main(String[] args) {
JFrame myframe = new JFrame("Pleasant's GUI");
myframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JMenuBar myMenu = new JMenuBar();
myMenu.setBackground(Color.ORANGE);
myMenu.setOpaque(true);
myMenu.setPreferredSize(new Dimension(400,25));
myframe.setJMenuBar(myMenu);
Container contents = myframe.getContentPane();
contents.setBackground(Color.blue);
contents.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 5;
JLabel lblName = new JLabel("Name");
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.33;
contents.add(lblName, c);
JTextField tfName = new JTextField("Enter Name", 20);// columns and text
c.gridx = 1;
c.gridy = 0;
c.weightx = 1;
contents.add(tfName, c);
JLabel lblPwd = new JLabel("Password");
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.33;
contents.add(lblPwd, c);
JPasswordField pwdPassWord = new JPasswordField(10);
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
contents.add(pwdPassWord, c);
JLabel lblGender = new JLabel("Gender");
c.gridx = 0;
c.gridy = 2;
c.weightx = 0.33;
contents.add(lblGender, c);
ButtonGroup bgGender = new ButtonGroup();
JRadioButton rbMale = new JRadioButton("Male");
JRadioButton rbFemale = new JRadioButton("Female");
bgGender.add(rbMale);
bgGender.add(rbFemale);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0.5;
contents.add(rbMale, c);
c.gridy = 3;
contents.add(rbFemale, c);
//add to panel and show flow layout by changing order
//& resize window. Change BorderLayout to CENTER
myframe.pack();
myframe.setVisible(true);
}
}
谢谢!
答案 0 :(得分:0)
这是我的代码,它在窗口7中使用jdk 1.8,它也为JMenuBar
以及JMenu
着色。
import java.awt.*;
import javax.swing.*;
public class BasicGraphics
{
JFrame frame;
JMenuBar menuBar;
JMenu fileMenu;
JMenu editMenu;
public BasicGraphics()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuBar = new JMenuBar();
menuBar.setOpaque(true);
menuBar.setBackground(Color.BLUE);
fileMenu = new JMenu("File");
fileMenu.setBackground(Color.RED);
editMenu = new JMenu("Edit");
editMenu.setBackground(Color.YELLOW);
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
new BasicGraphics();
}
}
setOpaque(true);
绝对是有效的,它为JMenuBar
着色,我不明白为什么你的计算机无法正常工作。你的代码也是橙色JMenuBar
的颜色。这里是图像