0

ボタンがクリックされたときに、JDialog(他のクラス)のJlabelsのテキストを変更したい。

私はJavaが初めてなので、このコードは少し長いです。我慢してください

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import java.awt.*;
import java.awt.event.*;
public class HotelRoomsGUI extends JPanel{
    private JTabbedPane mainJTP;
    private JPanel classicTab,deluxeTab,presidentialTab,classicSubPanel,deluxeSubPanel,presidentialSubPanel;
    private String classicRoomNo[] = {"101","102","103","104","105","106","107","108","109","101","111","112"};
    private String deluxeRoomNo[] = {"201","202","203","204","205","206","207","208","209","201","211","212"};
    private String presidentialRoomNo[] = {"301","302","303","304","305","306","307","308","309","301","311","312"};
    private JButton[] classicRoom, deluxeRoom, presidentialRoom;
    private JLabel[] inputLabels;
    ButtonHandler bh;
    public HotelRoomsGUI(){

        setLayout(null);
        setBackground(new Color(90,90,90));
        add(tabbedPane());

    }
    public JPanel classic()
    {
        classicTab = new JPanel();
        classicTab.setBackground(new Color(70,70,70));
        classicTab.setLayout(null);
        classicSubPanel();
        return classicTab;
    }
    public JPanel classicSubPanel()
    {
        classicSubPanel = new JPanel();
        classicSubPanel.setBounds(10,10,605,455);
        classicSubPanel.setLayout(new GridLayout(4,3,10,10));
        classicSubPanel.setBackground(new Color(70,70,70));
        classicTab.add(classicSubPanel);
        return classicTab;
    }
    public JPanel deluxe()
    {
        deluxeTab = new JPanel();
        deluxeTab.setBackground(new Color(70,70,70));
        deluxeTab.setLayout(null);
        deluxeSubPanel();
        return deluxeTab;
    }
    public JPanel deluxeSubPanel()
    {
        deluxeSubPanel = new JPanel();
        deluxeSubPanel.setBounds(10,10,605,455);
        deluxeSubPanel.setLayout(new GridLayout(4,3,10,10));
        deluxeSubPanel.setBackground(new Color(70,70,70));
        deluxeTab.add(deluxeSubPanel);
        return deluxeSubPanel;
    }
    public JPanel presidential()
    {
        presidentialTab = new JPanel();
        presidentialTab.setBackground(new Color(70,70,70));
        presidentialTab.setLayout(null);
        presidentialSubPanel();
        return presidentialTab;
    }
    public JPanel presidentialSubPanel()
    {
        presidentialSubPanel = new JPanel();
        presidentialSubPanel.setBounds(10,10,605,455);
        presidentialSubPanel.setLayout(new GridLayout(4,3,10,10));
        presidentialSubPanel.setBackground(new Color(70,70,70));
        presidentialTab.add(presidentialSubPanel);
        return presidentialSubPanel;
    }
    //Holder of buttons
    public JTabbedPane tabbedPane()
    {
        UIManager.put("TabbedPane.selected", Color.ORANGE); 
        mainJTP = new JTabbedPane();
        mainJTP.setBackground(Color.WHITE); 
        mainJTP.setBounds(3,1,630,500);
        mainJTP.addTab("Classic",classic());
        mainJTP.addTab("Deluxe",deluxe());
        mainJTP.addTab("Presidential",presidential());
        rooms();
        return mainJTP;
    }
    //Labels that will be display on the RoomProfile class
    public JLabel[] inputLabels()
    {
        inputLabels = new JLabel[10];
        for(int x = 0; x<inputLabels.length;x++)
        {
            inputLabels[x] = new JLabel();
            inputLabels[x].setForeground(Color.WHITE);
        }
        return inputLabels;
    }
    public void rooms()
    {
        bh = new ButtonHandler();
        presidentialRoom = new JButton[presidentialRoomNo.length];      
        deluxeRoom = new JButton[deluxeRoomNo.length];
        classicRoom = new JButton[classicRoomNo.length];
        for(int x = 0;x<classicRoomNo.length;x++){
            //classic rooms
            ImageIcon imageC = new ImageIcon("C:\\Users\\John\\workspace" +
                    "\\SystemTest\\src\\Images\\classicRooms.JPG"); // image
            classicRoom[x] = new JButton(classicRoomNo[x],imageC);
            classicRoom[x].setBackground(Color.WHITE);
            classicRoom[x].setBorder(new CompoundBorder(BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY),
                    BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY)));
            classicRoom[x].addActionListener(bh);
            classicSubPanel.add(classicRoom[x]);
            //deluxe rooms
            ImageIcon imageD = new ImageIcon("C:\\Users\\John\\workspace" +
                    "\\SystemTest\\src\\Images\\deluxeRooms.JPG"); // image
            deluxeRoom[x] = new JButton(deluxeRoomNo[x],imageD);
            deluxeRoom[x].setBackground(Color.WHITE);
            deluxeRoom[x].setBorder(new CompoundBorder(BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY),
                    BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY)));
            deluxeRoom[x].addActionListener(bh);
            deluxeSubPanel.add(deluxeRoom[x]);
            //presidential rooms
            ImageIcon imageP = new ImageIcon("C:\\Users\\John\\workspace" +
                    "\\SystemTest\\src\\Images\\presidentialRooms.JPG"); // image
            presidentialRoom[x] = new JButton(presidentialRoomNo[x],imageP);
            presidentialRoom[x].setBackground(Color.WHITE);
            presidentialRoom[x].setBorder(new CompoundBorder(BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY),
                    BorderFactory.createEtchedBorder(Color.WHITE,Color.GRAY)));
            presidentialRoom[x].addActionListener(bh);
            presidentialSubPanel.add(presidentialRoom[x]);

        }
    }
    public class ButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            //to get what button is accessed
            Room room = new Room(e.getActionCommand());
            //get all info using the room no. got from getActionCommand();
            GuestsInfo info = new GuestsInfo(room.getGuestID());
            String data[] = {info.getFirstName()+" "+info.getLastName(),info.getAge(),info.getGender(),
                    info.getContactNo(),"Today",info.getTime(),"Tomorrow",room.getRoomNo(),room.getRoomType()};
            RoomProfile prof = new RoomProfile();
            if(prof.isVisible())
            {
                System.out.print("test");
            }
            else
            {

                //setting text on label
                prof.setVisible(true);
                inputLabels();
                for(int i = 0; i<data.length; i++){
                    inputLabels[i].setText(" "+data[i]);
                    System.out.println(""+data[i]);
                }
            }
        }
    }

}

これは RoomProfile クラスのコードです

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RoomProfile extends JDialog{

    private JLabel[] labels;
    JLabel inputLabels[];
    private String topTextLabels[] = {"Fullname","Age","Gender","Address","Contact No","Arrival", "Time in", "Departure","Room No","Room Type"};
    private JButton okB;
    private JPanel subFrame,topPanel, bottomLeftPanel,bottomRightPanel;
    private JLabel designLabel;
    private ButtonHandler bh;
    private HotelRoomsGUI label = new HotelRoomsGUI();
    public RoomProfile() {
        setLayout(null);
        setModal(true);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
        setBackground(new Color(80,80,80));
        setContentPane(setSubFrame());
        setSize(600,500);
        setLocationRelativeTo(null);
    }
    public JPanel setSubFrame()
    {
        createLabels();
        buttons();
        designLabel();
        subFrame = new JPanel();
        subFrame.setBounds(0,0,600,500);
        subFrame.setBackground(new Color(90,90,90));
        subFrame.setLayout(null);
        subFrame.add(setTopPanel());
        subFrame.add(setBottomRightPanel());
        subFrame.add(setBottomLeftPanel());
        subFrame.add(okB);
        subFrame.add(designLabel);
        return subFrame;
    }
    public void designLabel()
    {
        ImageIcon img = new ImageIcon("C:\\Documents and Settings\\Janpol\\workspace\\HotelGUI\\src\\Images\\Account.JPG");
        designLabel = new JLabel(img);
        designLabel.setBounds(380,27,190,190);
        designLabel.setBorder(BorderFactory.createEtchedBorder(Color.GRAY,Color.BLACK));

    }
    // this is where i added some of the labels
    public JPanel setTopPanel()
    {
        topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(5,1));
        topPanel.setBounds(20,20,350,200);
        topPanel.setBackground(new Color(90,90,90));
        topPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.GRAY,Color.BLACK)
                ,"Personal Information",1,2,new Font("Arial",Font.BOLD,13),Color.ORANGE));
        JLabel[] top = label.inputLabels();
        for(int x = 0; x<5; x++)
        {
            topPanel.add(labels[x]);
            topPanel.add(top[x]);
        }

        return topPanel;
    }
    // also here
    public JPanel setBottomLeftPanel()
    {
        bottomLeftPanel = new JPanel();
        bottomLeftPanel.setLayout(new GridLayout(3,2));
        bottomLeftPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.GRAY,Color.BLACK)
                ,"Stay Information",1,2,new Font("Arial",Font.BOLD,13),Color.ORANGE));
        bottomLeftPanel.setBackground(new Color(90,90,90));
        bottomLeftPanel.setBounds(20,250,300,140);
        JLabel[] bot = label.inputLabels();
        for(int x = 5; x<8; x++)
        {
            bottomLeftPanel.add(labels[x]);
            bottomLeftPanel.add(bot[x]);
        }
        return bottomLeftPanel;
    }
    // lastly here
    public JPanel setBottomRightPanel()
    {
        bottomRightPanel = new JPanel();
        bottomRightPanel.setLayout(new GridLayout(2,2));
        bottomRightPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.GRAY,Color.BLACK)
                ,"Personal Information",1,2,new Font("Arial",Font.BOLD,13),Color.ORANGE));
        bottomRightPanel.setBackground(new Color(90,90,90));
        bottomRightPanel.setBounds(350,250,200,140);
        JLabel[] right = label.inputLabels();
        for(int x = 8; x<10; x++)
        {
            bottomRightPanel.add(labels[x]);
            bottomRightPanel.add(right[x]);
        }
        return bottomRightPanel;
    }

    public JLabel[] createLabels()
    {
        labels = new JLabel[topTextLabels.length];

        for(int x = 0; x<topTextLabels.length;x++)
        {
            labels[x] = new JLabel(topTextLabels[x]);
            labels[x].setForeground(Color.WHITE);
                    }
        return labels;
    }
    public void buttons()
    {
        bh = new ButtonHandler();
        okB = new JButton("Ok");
        okB.setBounds(400,400,100,50);
        okB.addActionListener(bh);
    }

    public class ButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
                dispose();
        }
    }

}

教室はこちら

import java.sql.*;

public class Room 
{

    private String roomType, availability, roomNo, Rate;
    private int  guestID;

    private Connection con;
    private PreparedStatement statement = null;

    public Room(){
        try {
             Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/3moronsdb","root","");

        } 
        catch (Exception e) {
             e.printStackTrace();
        }
    }
    public Room(int id)
    {
        this();
        try{
            statement = con.prepareStatement("SELECT * FROM room WHERE guestID=?");
            statement.setInt(1, id);
            ResultSet rs = statement.executeQuery();
            while(rs.next()){
                this.guestID = rs.getInt(1);
                this.roomType = rs.getString(2);
                this.roomNo = rs.getString(3);
                this.Rate = rs.getString(4);
                this.availability= rs.getString(5);
            }
        }catch(Exception e){
            System.out.print(e);
        }
    }
    //Constructor for setting rate
    public Room(String roomTypeL, String roomNoL , String RateL, String availabilityL)
    {
        this();
        try
        {   
            statement = con.prepareStatement("Insert into room(roomType, roomNo, rate,availability) values(?,?,?,?)");
                statement.setString(1, roomTypeL);
                statement.setString(2, roomNoL);
                statement.setString(3, RateL);
                statement.setString(4, availabilityL);
                statement.executeUpdate();
        }
        catch(Exception e)
        {
            e.printStackTrace();        
            return;
        }
    }
    public Room(String roomNo){
        this();
        try{
            statement = con.prepareStatement("SELECT * FROM room WHERE roomNo=?");
            statement.setString(1, roomNo);
            ResultSet rs = statement.executeQuery();
            while(rs.next()){
                this.guestID = rs.getInt(1);
                this.roomType = rs.getString(2);
                this.roomNo = rs.getString(3);
                this.Rate = rs.getString(4);
                this.availability= rs.getString(5);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return;
        }
    }
    //get guestID from the database
    public int getGuestID(){
        return this.guestID;
    }   
    //getting roomType
    public String getRoomType(){
        return this.roomType;
    }
    //getting roomNo
    public String getRoomNo(){
        return this.roomNo; 
    }
    //getting rate
    public String getRate(){
        return this.Rate; 
    }
    //getting availability  
    public String getAvailability(){
        return this.availability; 
    }
}

そして、これがGuestInformationのクラスです

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class GuestsInfo
{
    private String  firstName, lastName, gender, address, time, deposit, age, contactNo, stay;
    private int  guestID;
    private Connection con;
    private PreparedStatement statement;
    //default constructor
    public GuestsInfo()
    {
        try {
             Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/3moronsdb","root","");

        } 
        catch (Exception e) {
             e.printStackTrace();
        }
    }
    public GuestsInfo(int guestID)
    {
        this();
        try{
            statement = con.prepareStatement("SELECT * FROM guest WHERE guestID=?");
            statement.setInt(1, guestID);
            ResultSet rs = statement.executeQuery();
            while(rs.next()){
                this.guestID = rs.getInt(1);
                this.firstName = rs.getString(2);
                this.lastName = rs.getString(3);
                this.age = rs.getString(4);
                this.gender= rs.getString(5);
                this.address= rs.getString(6);
                this.contactNo = rs.getString(7);
                this.time= rs.getString(8);
                this.stay = rs.getString(9);
                this.deposit = rs.getString(10);
                System.out.print(firstName +""+ lastName +""+ age +""+ gender +""+ address +""+ contactNo +""+ 
                        time +""+ stay +""+ deposit);
            }   
        }catch(Exception e){}
    }
    public GuestsInfo(String firstName, String lastName, String age, String gender,
            String address, String contactNo, String time, String stay,  String deposit)
    {
        this();
        try
        {   
            statement = con.prepareStatement("Insert into guest(firstName,lastName,age,gender,address,contactNo,time,stay,deposit)values(?,?,?,?,?,?,?,?,?)");  

                statement.setString(1, firstName);
                statement.setString(2, lastName);
                statement.setString(3, age);
                statement.setString(4, gender);
                statement.setString(5, address);
                statement.setString(6, contactNo);
                statement.setString(7, time);
                statement.setString(8, stay);
                statement.setString(9, deposit);
                statement.executeUpdate();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return;
        }   
    }
    //get guestID from the database
    public int getGuestID(){
        return guestID;
    }   
    //get firstName from the database
    public String getFirstName(){
        return this.firstName;
    }

    //get lastName from the database
    public String getLastName(){    
        return lastName;
    }
    //get age from the database
    public String getAge(){

        return this.age;
    }

    //get gender from the database
    public String getGender(){
        return this.gender;
    }
    //get address from database
    public String getAddress(){
        return this.address;
    }
    //get contactNo from the database
    public String getContactNo(){
        return this.contactNo;
    }
    //get time from database
    public String getTime()
    {
        return this.time;
    }
    //get stay from database
    public String getStay()
    {
        return this.stay;
    }
    //get roomType from database
    public String getDeposit()
    {
        return this.deposit;
    }
}

ラベルにテキストが表示されない理由がわかりません。私を助けてください。事前に感謝し、私と一緒にいてくれてありがとう

私を助けてくれてありがとう。ありがとうございました

4

2 に答える 2

2

これが私の推測です:あなたのactionPerformed()ハンドラーで、あなたは を呼び出しますinputLabels();JLabelオブジェクトの新しい配列をインスタンス化し、それをinputLabelsフィールドに割り当てるようです。ただし、これらのオブジェクトはパネルに追加されません。setBottomLeftPanel()これは、初めてラベルを作成するときにのみ行われます。

そのため、コード内のコードが で定義されている(そして既にパネルに含まれている)ラベルでactionPerformed()呼び出されていることを確認してください。setText()setBottomLeftPanel()

編集(完全なコードが投稿された後):

間違っていることが複数あります。さて、問題を解決するには:

1)RoomProfileでフィールドJLabel[] bottomLeftPanelFields;を作成し、 で作成したラベルをそれに割り当てますsetBottomRightPanel()

2) そのフィールドに getter を作成します ( getBottomLeftPanelFields())

3)次のように変更actionPerformed()します。

...
JLabel[] bottomLeftFields = prof.getBottomLeftPanelFields();
for(int i = 0; i<data.length; i++){
                 bottomLeftFields[i].setText(" "+data[i]);
             }

                //setting text on label
                prof.setVisible(true);
...

つまり、呼び出す前にフィールドを設定しますsetVisible()(これは、ルーム ダイアログをモーダルに表示する場所です)。この時点から、ラベルが表示されるはずです。

さらにいくつかのビット:

a) おそらく、他のラベル (top など) についても同様のことを行います。

b) 両方のinputLabelsフィールドを削除します。inputLabels()1 つは、インスタンス化中に 3 回呼び出されるたびに書き換えられますRoomProfile。その他は特に必要ありません。inputLables()また、毎回異なる数のラベルが必要な場合でも、メソッドは常に 10 個のオブジェクトを作成することに注意してください。

c) おそらく、Swing と Java の設計パターンに関するチュートリアルを入手してください (Oracle の Web サイトにいくつかあります)。これは、物事を構造化する方法を理解するのに役立ちます。

于 2012-10-08T13:05:11.067 に答える
0

問題はこの行にあると思います:

   JLabel[] bot = label.inputLabels();

これは、パネルに追加する前に、これらすべてのラベルを再インスタンス化しています。試す:

   JLabel[] bot = inputLabels;

ここでの混乱は、あなたの抽出物から何が最初に実行されているかを判断するのが難しいことですが、これがあなたの予期しない動作が発生している場所であると考えています.

于 2012-10-08T13:28:54.830 に答える