Где часто используется текстовая функция (например, в div и т. д.), тогда для текстовой области это val
get:
$ ('# myTextBox' ) .val ();
set:
$ ('# myTextBox'). val ('новое значение');
Существует ряд методов, которые вы могли бы использовать для достижения этого ...
Сделать переменную класса, доступную для numGenerator
для прямого доступа ...
public class Main{
public static void main(String[] args){
new Main();
}
// This variable will be visible to the inner class numGenerator
private JLabel output;
public Main() {
JFrame mainFrame = new JFrame("Experiment");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
Panel panel = new Panel();
mainFrame.getContentPane().add(panel);
output = new JLabel("This is where the result from the num variable in the numGenerator class would go");
panel.add(output);
JButton numGenerator = new JButton("Generate Number");
panel.add(numGenerator);
numGenerator.addActionListener(new numGenerator());
}
public class numGenerator implements ActionListener{
public void actionPerformed(ActionEvent e){
Random dice = new Random();
int num = dice.nextInt(3);
output.setText(Integer.toString(num));
}
}
}
Это сильно сочетает ваше действие с вашей меткой, делая код менее многоразовым ...
Передайте ссылку метки, которая будет изменена на numGenerator
...
public class Main{
public static void main(String[] args){
new Main();
}
public Main() {
JFrame mainFrame = new JFrame("Experiment");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
Panel panel = new Panel();
mainFrame.getContentPane().add(panel);
JLabel output = new JLabel("This is where the result from the num variable in the numGenerator class would go");
panel.add(output);
JButton numGenerator = new JButton("Generate Number");
panel.add(numGenerator);
numGenerator.addActionListener(new numGenerator(output));
}
public class numGenerator implements ActionListener{
private JLabel label;
public numGenerator(JLabel label) {
this.label = label;
}
public void actionPerformed(ActionEvent e){
Random dice = new Random();
int num = dice.nextInt(3);
if (label != null) {
label.setText(Integer.toString(num));
}
}
}
}
Это делает numGenerator
более многоразовым, поскольку он не зависит от одного экземпляра JLabel
Использовать шаблон стиля Observer , который мог бы рассказать некоторой заинтересованной стороне, что генерируется новый номер ...
public class Main{
public static void main(String[] args){
new Main();
}
public Main() {
JFrame mainFrame = new JFrame("Experiment");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
Panel panel = new Panel();
mainFrame.getContentPane().add(panel);
final JLabel output = new JLabel("This is where the result from the num variable in the numGenerator class would go");
panel.add(output);
JButton numGenerator = new JButton("Generate Number");
panel.add(numGenerator);
numGenerator.addActionListener(new numGenerator(new NumberGeneratorListener() {
public void numberGenerated(int number) {
output.setText(Integer.toString(number));
}
}));
}
public interface NumberGeneratorListener {
public void numberGenerated(int number);
}
public class numGenerator implements ActionListener{
private NumberGeneratorListener listener;
public numGenerator(NumberGeneratorListener listener) {
this.listener = listener;
}
public void actionPerformed(ActionEvent e){
Random dice = new Random();
int num = dice.nextInt(3);
if (listener != null) {
listener.numberGenerated(num);
}
}
}
}
Это не только отделяет numGenerator
от остальной части кода, так как он не зависит от какой-либо другой части кода, он делает его чрезвычайно многоразовым, поскольку его не волнует, где число идет или как он используется, это зависит от наблюдателя / слушателя, чтобы решить ...
Боковые заметки ...
Возможно, вы также захотите прочитать ...
Прежде всего, если u хочет, чтобы доступ к JLabel должен быть в объявлении CLVEL LEVEL или прошел по параметру в actionListener, причина, по которой ссылка на метку ur присутствует только в основном контексте.
public class Main{
public static void main(String[] args){
JFrame mainFrame = new JFrame("Experiment");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
Panel panel = new Panel();
mainFrame.getContentPane().add(panel);
JLabel output = new JLabel("This is where the result from the num variable in the numGenerator class would go");
panel.add(output);
JButton numGenerator = new JButton("Generate Number");
panel.add(numGenerator);
numGenerator.addActionListener(new NumGenerator(output));
}
private class NumGenerator implements ActionListener{
private final JLabel label;
public NumGenerator(final JLabel label){
this.label=label;
}
@Override
public void actionPerformed(ActionEvent arg0) {
int num;
Random dice = new Random();
num = dice.nextInt(3);
label.setText(num);
}
}
}
ИЛИ u может сделать что-то вроде этого
public class Main{
//if u want to hold all at class level properties but u really only interested in JLabel
private JFrame mainFrame;
private JPanel panel;
private JLabel label;
private JButton numGenerator;
//add Constructor
public Main(){
mainFrame = new JFrame("Experiment");
mainFrame.setSize(500,500);
mainFrame.setVisible(true);
panel = new JPanel();
mainFrame.getContentPane().add(panel);
output = new JLabel();
panel.add(output);
numGenerator = new JButton("Generate Number");
panel.add(numGenerator);
numGenerator.addActionListener(new NumGenerator(output));
}
public static void main(String[] args){
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().mainFrame.setVisible(true);
}
});
}
private class NumGenerator implements ActionListener{
@Override
public void actionPerformed(ActionEvent arg0) {
int num;
Random dice = new Random();
num = dice.nextInt(3);
label.setText(num); // now u have access
}
}
}
actionPerformed
(ActionPerfomed
). Теперь я запускаю его через компилятор и обновляю примеры и тестировал их – MadProgrammer 3 June 2013 в 03:15