[英]why can't we access parent class instance variables inside the class outside the method in child class in java?
[英]Can't access variables outside of their class
我的按鈕變量都沒有在他們的班級之外被識別。 當我嘗試在 changeSize 類中調用 butSmall 變量時,什么也沒有發生,而且它似乎無法識別。 我該如何解決這個問題,以便我可以訪問原始類之外的按鈕變量?
import javax.swing.*;
import java.awt.*
import java.awt.event.*;
public class SquareSimp
{
public static void main( String[] args )
{
FilledFrame frame = new FilledFrame();
frame.setVisible( true );
}
}
class FilledFrame extends JFrame
{
int size = 400;
public FilledFrame()
{
JButton butSmall = new JButton("Small");
JButton butMedium = new JButton("Medium");
JButton butLarge = new JButton("Large");
JButton butMessage = new JButton("Say Hi!");
JButton butQuit = new JButton("QUIT");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
butPanel.add(butQuit);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setSize( size+80, size+100 );
butMessage.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "Hi");
}
});
}
}
class SquarePanel extends JPanel {
FilledFrame theApp;
SquarePanel(FilledFrame app) {
theApp = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(40, 20, theApp.size, theApp.size);
}
}
class changeSize extends FilledFrame{
changeSize(){
butLarge.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
}
});
}
}
如果你想在整個代碼中引用你的按鈕而不在方法等中使用參數,那么你應該將聲明移到任何方法之外,但仍然在類中,就像安迪說的那樣。 您還需要根據您是否希望訪問類或包之外的按鈕,添加諸如protected
或public
類的訪問修飾符。 然后,只需初始化方法內的按鈕。
它看起來像這樣:
class FilledFrame extends JFrame {
protected JButton butSmall;
//Do this for all the buttons
int size = 400;
public FilledFrame() {
butSmall = new JButton("Small");
// Do this for all the buttons then continue with rest of code...
}
}
正如安迪指出的那樣,它應該有效。
基本上,僅僅因為您在FilledFrame
類的構造函數中聲明變量(例如butSmall
),它們就成為構造函數作用域的局部變量。
如果你想使用其他類中的變量,你應該改變你聲明它們的地方。
class FilledFrame extends JFrame
{
JButton butSmall;
JButton butMedium;
JButton butLarge;
JButton butMessage;
JButton butQuit;
SquarePanel panel;
JPanel butPanel;
int size = 400;
public FilledFrame()
{
butSmall = new JButton("Small");
butMedium = new JButton("Medium");
butLarge = new JButton("Large");
butMessage = new JButton("Say Hi!");
JbutQuit = new JButton("QUIT");
panel = new SquarePanel(this);
butPanel = new JPanel();
butPanel.add(butSmall);
butPanel.add(butMedium);
butPanel.add(butLarge);
butPanel.add(butMessage);
butPanel.add(butQuit);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
setSize( size+80, size+100 );
butMessage.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "Hi");
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.