【发布时间】:2016-04-09 14:39:14
【问题描述】:
我是 Java 编程新手,有“初学者问题”。 我已经尝试查找是否有人已经遇到了同样的问题,但是我找不到任何属于我的低级别的帖子。
我的问题: 我在其中一个中有 2 个 JPanel,(我们称之为 Panel1)我实现了一个 JTextField(field1)和一个 JButton(button1)。在 Panel2 上,我想画一些东西,这取决于第一个 JTextField 中使用的内容。
我的问题是我希望 Panel2“看到”那个 button1(在 Panel1 中),但我没能做到。
谁能给我一个提示,一个 Youtube 视频或类似的东西,我可以看到一个很好的例子来处理这样的问题?
你好文图拉
P.S 我有一个想法将值传递给 Panel2,它应该在其中绘制我想要的那些东西,这是我的代码到目前为止(我希望我正确发布它):这里是 Panel1:
public class Panel1 extends JPanel
{
public JButton button = new JButton("OK");
public JTextField field1 = new JTextField(5);
public String name;int b;
public Panel1()
{
setBackground(Color.WHITE);
add(field1);
add(button);
ButtonListener listener = new ButtonListener(field1);
button.addActionListener(listener);
}
public Dimension getPreferredSize()
{
return new Dimension(400,400);
}
}
这里是 ButtonListener:
class ButtonListener implements ActionListener
{
Graphics g;
//Graphics2D g2 = (Graphics2D) g;
public Panel2 pan2 = new Panel2();
public String name;
public JTextField field1 = new JTextField();
int b;
public ButtonListener(JTextField field1)
{this.field1 = field1;}
public void actionPerformed(ActionEvent e)
{
String op = e.getActionCommand();
if(op.equals("OK"))
{
name = field1.getText();
try
{
b = Integer.parseInt(name);
JOptionPane.showMessageDialog(null,"Ihre Zahl = "+b);
pan2.setvalue(b,g);
}
catch(NumberFormatException ex) {JOptionPane.showMessageDialog(null,"Please enter real numbers!");}
}
}
}
最后是 Panel2,我想根据 Panel1 中给出的输入来绘制东西(例如:我输入 10,他给我画了一个宽度为 10 的矩形或类似的东西)
public class Panel2 extends JPanel
{
Graphics g;
Graphics2D g2 = (Graphics2D) g;
public int b;
public Panel2()
{
setBackground(Color.YELLOW);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g2.setColor(Color.RED);
g2.fillRect(200, 200, 50, 50);
Paint2(g);
}
public void Paint2(Graphics g)
{
this.g = g;
Graphics2D g2 = (Graphics2D) g;
//super.paintComponent(g);
System.out.println("TEST2");
g2.setColor(Color.BLUE);
//System.out.println("TEST3");
g2.fillRect(10 , 10, 40, 40);
}
public void setvalue(int b, Graphics g)
{
this.b = b;
this.g = g;
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.CYAN);
g2.fillRect(0, 0, 40, 40);
System.out.println("B ist gleich = "+b);
//Paint2(g2);
}
public Dimension getPreferredSize()
{
return new Dimension(400,400);
}
如果阅读起来有点麻烦,我很抱歉。 我在这段代码中遇到的基本问题是当我想调用方法时 Panel2 中的 NullpointerException
setvalue(int b, 图形 g) g2.setColor(Color.Cyan)
问候帕特里克
【问题讨论】:
标签: class jpanel jbutton actionlistener