我打算创建一个简单的gui,它会在窗口的顶部三分之一处绘制一个椭圆形,在中间三分之一处显示一个名称,并在底部三分之一处绘制一个矩形(稍后将完成)< / p>
到目前为止,我能够创建和显示的唯一部分是四个按钮,最终意味着切换对象和标签的可见性。
我遇到的问题是我无法看到标签或椭圆形,而且我不确定我错过了什么,以防止它们变得不可见
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Gui extends JFrame
implements ActionListener
{
private JButton bottomLeftButton;
private JButton bottomMiddleLeftButton;
private JButton bottomRightButton;
private JButton bottomMiddleRightButton;
private OtherPanel mypanel;
private JLabel name;
private JPanel panelOne;
private boolean visible;
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == bottomLeftButton)
{
visible = name.isVisible();
name.setVisible(visible);
}
else if(e.getSource() == bottomMiddleLeftButton)
{
}
else if (e.getSource() == bottomMiddleRightButton)
{
}
else if (e.getSource() == bottomRightButton)
{
}
repaint();
}
public Gui()
{
setTitle("First GUI");
setSize(800,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
JPanel BottomPanel = new JPanel(new GridLayout(1,4));
contentPane.add(BottomPanel, BorderLayout.SOUTH);
bottomLeftButton = new JButton("Name");
bottomLeftButton.addActionListener(this);
BottomPanel.add(bottomLeftButton);
bottomMiddleLeftButton = new JButton("Oval");
bottomMiddleLeftButton.addActionListener(this);
BottomPanel.add(bottomMiddleLeftButton);
bottomMiddleRightButton = new JButton("Square");
bottomMiddleRightButton.addActionListener(this);
BottomPanel.add(bottomMiddleRightButton);
bottomRightButton = new JButton("Special");
bottomRightButton.addActionListener(this);
BottomPanel.add(bottomRightButton);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3,1));
panelOne = new OtherPanel();
name = new JLabel("Name");
name.setHorizontalAlignment(SwingConstants.CENTER);
JLabel label3 = new JLabel("Label3");
centerPanel.add(panelOne);
centerPanel.add(name);
centerPanel.add(label3);
}
public static void main(String[] args)
{
Gui gui = new Gui();
gui.setVisible(true);
}
}
&#13;
(意为绘制椭圆形)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OtherPanel extends JPanel
{
public void paintComponent(Graphics g)
{
int x = 10;
int y = 10;
int width = getWidth(); //ten pixels of spaces
int height = getHeight();
g.fillOval(x, y, width, height);
}
}
&#13;
答案 0 :(得分:0)
缺少一行代码来将对象添加到contentPane
contentPane.add(centerPanel);在gui()方法结束时