1 回答

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
(在你繼續(xù)你的項(xiàng)目之前,先看看Swing 和 AWT 有什么區(qū)別。我建議你轉(zhuǎn)向 Swing。)
您看不到復(fù)選框,因?yàn)槟鷽]有將它們添加到框架中。使用Frame.add(Component c)
方法來(lái)實(shí)現(xiàn)這一點(diǎn)。
現(xiàn)在關(guān)于自定義繪畫,我不喜歡這里,因?yàn)樗皇且粋€(gè)文本。您可以添加標(biāo)簽或其他東西,而不是使用自定義繪畫。此外,當(dāng)您重寫paint
方法時(shí),始終從調(diào)用開始super.paint(Graphics g)
(相同的“規(guī)則”適用于 Swing -paintComponent
方法)。
最后,所有 AWT(和 Swing)應(yīng)用程序都必須在它們自己的線程上運(yùn)行。將EventQueue#invokeLater
方法用于 AWT 和SwingUtilities#invokeLater
Swing。(他們真的不同嗎?)
您的代碼以及我提到的所有實(shí)現(xiàn):
public class CBGroup extends Frame implements ItemListener {
? ? String msg = "";
? ? Checkbox windows, android, solaris, mac;
? ? CheckboxGroup cbg;
? ? public CBGroup() {
? ? ? ? super("");
? ? ? ? // Use a flow layout
? ? ? ? setLayout(new FlowLayout());
? ? ? ? // Create a checkbox group
? ? ? ? cbg = new CheckboxGroup();
? ? ? ? // Create the checkboxes and include them in the group
? ? ? ? windows = new Checkbox("windows", cbg, true);
? ? ? ? android = new Checkbox("android", cbg, false);
? ? ? ? solaris = new Checkbox("solaris", cbg, false);
? ? ? ? mac = new Checkbox("mac", cbg, false);
? ? ? ? add(windows);
? ? ? ? add(android);
? ? ? ? add(solaris);
? ? ? ? add(mac);
? ? ? ? // Add item listeners
? ? ? ? windows.addItemListener(this);
? ? ? ? android.addItemListener(this);
? ? ? ? solaris.addItemListener(this);
? ? ? ? mac.addItemListener(this);
? ? ? ? addWindowListener(new WindowAdapter() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void windowClosing(WindowEvent we) {
? ? ? ? ? ? ? ? System.exit(0);
? ? ? ? ? ? }
? ? ? ? });
? ? }
? ? @Override
? ? public void itemStateChanged(ItemEvent ie) {
? ? ? ? repaint();
? ? }
//? // Display current state of the check boxes
? ? @Override
? ? public void paint(Graphics g) {
? ? ? ? super.paint(g);
? ? ? ? msg = "Current selection: ";
? ? ? ? msg += cbg.getSelectedCheckbox().getLabel();
? ? ? ? g.drawString(msg, 20, 120);
? ? }
? ? public static void main(String[] args) {
? ? ? ? EventQueue.invokeLater(() -> {
? ? ? ? ? ? CBGroup appwin = new CBGroup();
? ? ? ? ? ? appwin.setSize(new Dimension(240, 180));
? ? ? ? ? ? appwin.setTitle("CBGroup");
? ? ? ? ? ? appwin.setVisible(true);
? ? ? ? });
? ? }
}
添加回答
舉報(bào)