對於我的任務,我必須編寫一個程序,該程序可以打印一些文本,橢圓形或矩形,具體取決於頂部按下哪個按鈕然而,當我按下按鈕時什麼也沒有發生,我該如何解決這個問題?這是我的第一個GUI,我會很感激任何幫助!我最終需要的程序是:從一個矩形開始,使窗口在調整大小時在屏幕上停留在繪圖區域的中心,而我的橢圓和矩形必須有一半的寬度並且顯示區域的高度。我一次只做這一步,所以我會試圖找出一旦我真的可以在屏幕上獲得一個形狀,感謝:-)。按下按鈕時繪製字符串,矩形或橢圓形的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);
}
}
什麼題? – Reimeus
@Reimeus編輯問題,以便實際提出問題,謝謝指出! – gdhc21