Доступ и запуск метода основного класса из другого класса
У меня проблема с поиском способа выполнить метод печати в моем основном классе из другого класса с помощью JButton
,
Это мое Mainclass
метод, который я хочу выполнить.
public void genInReceipt(Date in, String res)
throws Exception
{
log.debug("start printing...");
// TOP
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(new String(new byte[] {ESC, '@', 0x1b, 0x61, 0x01}));
serialPort.writeString(new String(new byte[] {ESC, '!', 0x08}));
serialPort.writeString(new String(new byte[] {ESC, 'E', 0x1b}));
serialPort.writeString(String.format("%s\n", "PLAZA INDONESIA"));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
// PARAGRAPH 1 Still Fix(Add Parimeter)
serialPort.writeString(new String(new byte[] {ESC, '!', 0x08, ESC, 'a', 0x00}) + String.format("%s\n"," 1343KZT/MOBIL"));// + new String(new byte[] {ESC, 'E', 0x1B, GS, '!', 0x10, 0x01}) + String.format(" MOBIL"));
serialPort.writeString(String.format("%s\n", " PP6-ADE SILFIANAH"));
serialPort.writeString(String.format(" In : %s\n", df.format(in)));
serialPort.writeString(String.format(" Out : %s\n", "21 Jul 2016 17:00:00"));
serialPort.writeString(String.format(" Duration: %s\n", "1 hours 29 minutes")); //Pakegate
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
serialPort.writeString(String.format(" Sewa Parkir: %s\n", "Rp 6.000"));
serialPort.writeString(new String(new byte[] {ESC, 'J', 0x4A}));
// BOTTOMLINE
serialPort.writeString(new String(new byte[] {ESC, 'a', 0x01}));
serialPort.writeString(new String("TERIMA KASIH\n".getBytes()));
serialPort.writeString(new String("ATAS KUNJUNGAN ANDA\n".getBytes()));
log.debug(" ... done");
serialPort.writeString(new String(new byte[] {GS, 'v', 0x1D}));
serialPort.writeString(new String(new byte[] {0x1b, 0x64, 0x05}));
serialPort.writeString(new String(new byte[] {0x1d, 0x56, 0x42, 0x00}));
}
И это мой код GUI
package unibit.embedded.parking;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class GUIPrinter {
public static void main(String[] args) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//What i have to add here to execute genInReciept method?
}
});
}
}
Я знаю, что с моим кодом что-то не так, может кто-нибудь мне помочь?
3 ответа
То, что вам нужно / нужно, довольно просто, вам нужен экземпляр класса и вызов метода...
Пример:
public void actionPerformed(ActionEvent arg0) {
//What i have to add here to execute genInReciept method?
Mainclass mc = ...//get a MainClass or create a new instance like doing new Mainclass();...
mc.genInReceipt(new Date() ,"???"); //I dont know what res is, since I can not find it in the method
}
Вам нужно создать экземпляр класса с genInReceipt
и затем назовите это так:
ClassWithGenInReceiptMethod o = new ClassWithGenInReceiptMethod();
o.genInReceipt();
Но сначала было бы здорово начать читать басни о Java и программировании.
Предполагая, что ваш GUIprinter
Основной класс находится в том же файле, что и ваш genInReceipt()
учебный класс. Вот как бы я это сделал.
public class GUIPrinter extends JFrame{
public static void main(String[] args) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button1 = new JButton();
final Date date = new Date();// declare Date variable
final String yourString = "Your String here";// declare String variable
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
genInReceipt(date,yourString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static void genInReceipt(Date in, String res){
// your code
}
}
Примечание: ваш genInReceipt()
класс требует от вас пройти Date
а также String
переменные. Объявите эти переменные и передайте их genInReceipt()
учебный класс.
Но если ваш getInReceipt()
класс находится в другом файле. Следуйте предыдущим ответам. Итак, подведем итоги, как сделать предыдущие ответы.
- Объявите экземпляр класса, где
genInReceipt()
расположен. Позвоните
genInReceipt()
,public class ClassThatWouldCallgenInReceipt extends JFrame { ClassWithgenInReceipt o = new ClassWithGenInReceipt();// Here is the class where genInReceipt() is located public static void main(String[] args) { final JFrame frame = new JFrame(); JPanel panel = new JPanel(); JButton button1 = new JButton(); final Date date = new Date();// declare Date variable final String yourString = "Your String here";// declare String variable frame.add(panel); panel.add(button1); frame.setVisible(true); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { o.genInReceipt(date, yourString);// Call genInReceipt() like this } }); } }
А вот ClassWithgenInReceipt
где genInReceipt()
класс расположен
public class ClassWithgenInReceipt{
public void genInReceipt(Date date, String yourString){
//your code
}
}
Примечание: я также довольно новичок в Java. Так что я мог сделать этот ответ с некоторыми ошибками. Однако, если есть ошибки, пожалуйста, сообщите мне в целях обучения:).