簡體   English   中英

Java認為單選按鈕總是被選中

[英]Java think Radio button is always selected

我有一個程序應該顯示價格 1.50 * 單選按鈕的數量,除非我的程序無法識別單選按鈕打開,因此不顯示 1.50。

import java.awt.event.*;
import javax.swing.*;
/**
 *
 * @author silve
 */
public class Page3 extends javax.swing.JFrame {

    /**
     * Creates new form Page3
     */
    public Page3() {
        initComponents();


      double Checkout1 = RadioBtn();

        double Lj = Checkout1 * 1.50;

        String LM = String.valueOf(Lj);

        ToppingsPriceL.setText((LM) + "0");  


    }
public double RadioBtn() {
    double Checkout = 0;



   if(GreenOlivesBtn.isSelected()) {
        Checkout++; 
    }

   return Checkout;



}

您的主要問題是您在 gui 創建時調用RadioBtn()時幾乎可以保證不會被選中。 為了使此代碼起作用,需要在某種偵聽器(可能是 ActionListener)中調用該方法,因為用戶需要有機會更改單選按鈕的狀態,然后 GUI 對此做出響應。

順便說一句,您將需要學習和使用Java 命名約定 變量名應全部以小寫字母開頭,而類名應以大寫字母開頭。 此外,您應該避免使用諸如bs類的瑣碎變量名稱,除非它們被用於諸如 for 循環索引之類的瑣碎目的。 而是使用具有某種意義的名稱,以便您的代碼成為自我注釋。

您必須創建一個 JRadioButton 並將其放入 GroupButton。 前任。

JRadioButton yesButton   = new JRadioButton("Yes"  , true);
JRadioButton noButton    = new JRadioButton("No"   , false);
JRadioButton maybeButton = new JRadioButton("Maybe", false);

ButtonGroup bgroup = new ButtonGroup();
bgroup.add(yesButton);
bgroup.add(noButton);
bgroup.add(maybeButton);

JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3, 1));
radioPanel.add(yesButton);
radioPanel.add(noButton);
radioPanel.add(maybeButton);

radioPanel.setBorder(BorderFactory.createTitledBorder(
           BorderFactory.createEtchedBorder(), "Married?"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM