但是,对于我的任务,我必须编写一个程序来打印一些文本、椭圆或矩形,具体取决于在屏幕顶部按下的按钮;当我按下按钮时没有任何反应,我将如何解决这个问题?这是我的第一个 GUI,我将不胜感激!我最终需要该程序:从一个矩形开始,当窗口调整大小时,使屏幕上出现的任何形状都停留在绘图区域的中心,并且我的椭圆形和矩形必须有一半的宽度和显示区域的高度。我一次迈出这一步,所以一旦我能在屏幕上真正得到一个形状,我会试着弄清楚这些,谢谢:-)。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class firstGUI extends JFrame
implements ActionListener
{
private boolean showText = false;
private boolean showRect = false;
private boolean showOval = false;
private JButton text;
private JButton oval;
private JButton rectangle;
private JPanel buttonPanel;
public firstGUI()
{
super("First GUI");
setSize(512, 512);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
text = new JButton("Text");
text.addActionListener(this);
buttonPanel.add(text);
oval = new JButton("Oval");
oval.addActionListener(this);
buttonPanel.add(oval);
rectangle = new JButton("Rectangle");
rectangle.addActionListener(this);
buttonPanel.add(rectangle);
//JComponent drawArea = new JComponent();
drawStuff d = new drawStuff();
Container contentPane = this.getContentPane();
contentPane.add(buttonPanel, BorderLayout.NORTH);
contentPane.add(d);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source == text)
{
showText = true;
}
else if (source == oval)
{
showOval = true;
}
else if (source == rectangle)
{
showRect = true;
}
}
public void draw(Graphics g)
{
if(showText)
{
g.drawString("Hello", 0, 0);
}
else if (showOval)
{
g.drawOval(0, 0, 100, 100);
}
else if (showRect)
{
g.drawRect(0, 0, 100, 100);
}
}
public static void main(String [] args)
{
firstGUI myTest = new firstGUI();
myTest.setVisible(true);
}
}
class drawStuff extends JPanel
{
public void paint(Graphics g)
{
super.paint(g);
}
}