jjzjj

java - Java GUI 可以控制 Python 后端吗?

coder 2023-08-24 原文

好的,到目前为止,我只有一个图形用户界面(Java)和一个程序(Python)。我想要 gui 中的按钮按下时将输出发送到 python 程序并运行它。然后我希望 gui 程序在右侧的文本框中显示 python 打印命令。

所以,我的问题是,这是否可能,我将如何让它发挥作用?

界面

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class dogedice extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField textField;
    private JComboBox combo;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    dogedice frame = new dogedice();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public dogedice() {
        setTitle("DogeDice Bot");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.WEST);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0};
        gbl_panel.rowHeights = new int[]{0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 1.0};
        gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        //Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
        JLabel userTag = new JLabel("Username:");
        GridBagConstraints gbc_userTag = new GridBagConstraints();
        gbc_userTag.insets = new Insets(0, 0, 0, 5);
        gbc_userTag.anchor = GridBagConstraints.EAST;
        gbc_userTag.gridx = 0;//Here are your x + y coords
        gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
        panel.add(userTag, gbc_userTag);

        //Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
        textField = new JTextField();
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 0;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel startTag = new JLabel("Starting Bid:");
        GridBagConstraints gbc_startTag = new GridBagConstraints();
        gbc_startTag.insets = new Insets(0, 0, 0, 5);
        gbc_startTag.anchor = GridBagConstraints.EAST;
        gbc_startTag.gridx = 0;
        gbc_startTag.gridy = 2;
        panel.add(startTag, gbc_startTag);

        textField = new JTextField();
        GridBagConstraints gbc_textField3 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 2;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel multTag = new JLabel("Multiplier:");
        GridBagConstraints gbc_multTag = new GridBagConstraints();
        gbc_multTag.insets = new Insets(0, 0, 0, 5);
        gbc_multTag.anchor = GridBagConstraints.EAST;
        gbc_multTag.gridx = 0;
        gbc_multTag.gridy = 3;
        panel.add(multTag, gbc_multTag);

        textField = new JTextField();
        GridBagConstraints gbc_textField4 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 3;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel minTag = new JLabel("Min Remaining:");
        GridBagConstraints gbc_minTag = new GridBagConstraints();
        gbc_minTag.insets = new Insets(0, 0, 0, 5);
        gbc_minTag.anchor = GridBagConstraints.EAST;
        gbc_minTag.gridx = 0;
        gbc_minTag.gridy = 4;
        panel.add(minTag, gbc_minTag);

        textField = new JTextField();
        GridBagConstraints gbc_textField5 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 4;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        textField = new JTextField();
        GridBagConstraints gbc_textField2 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 1;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel passTag = new JLabel("Password:");
        GridBagConstraints gbc_passTag = new GridBagConstraints();
        gbc_passTag.insets = new Insets(0, 0, 0, 5);
        gbc_passTag.anchor = GridBagConstraints.EAST;
        gbc_passTag.gridx = 0;
        gbc_passTag.gridy = 1;
        panel.add(passTag, gbc_passTag);

        textField = new JTextField();
        GridBagConstraints gbc_textField6 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 5;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel oddsTag = new JLabel("Odds %:");
        GridBagConstraints gbc_oddsTag = new GridBagConstraints();
        gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
        gbc_oddsTag.anchor = GridBagConstraints.EAST;
        gbc_oddsTag.gridx = 0;
        gbc_oddsTag.gridy = 5;
        panel.add(oddsTag, gbc_oddsTag);

        textField = new JTextField();
        GridBagConstraints gbc_textField7 = new GridBagConstraints();
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 6;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        //This is the Combo Box
        combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
        combo.addActionListener(this);
        GridBagConstraints gbc_list = new GridBagConstraints();
        gbc_list.fill = GridBagConstraints.HORIZONTAL;
        gbc_list.gridx = 1;
        gbc_list.gridy = 7;
        panel.add(combo, gbc_list);

        JLabel maxTag = new JLabel("MaxBet:");
        GridBagConstraints gbc_maxTag = new GridBagConstraints();
        gbc_maxTag.insets = new Insets(0, 0, 0, 5);
        gbc_maxTag.anchor = GridBagConstraints.EAST;
        gbc_maxTag.gridx = 0;
        gbc_maxTag.gridy = 6;
        panel.add(maxTag, gbc_maxTag);

        JPanel panel_1 = new JPanel();
        contentPane.add(panel_1, BorderLayout.SOUTH);
        panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));

        JButton btnConfirm = new JButton("Turn Up");
        panel_1.add(btnConfirm);


        JScrollPane scrollPane = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
        contentPane.add(scrollPane, BorderLayout.CENTER);
        JTextArea textArea = new JTextArea("Imput bot information here...");
        textArea.setColumns(20);
        scrollPane.setViewportView(textArea);

        pack();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == combo) {
            System.out.println(combo.getSelectedIndex()+1);
        }
    }

}

Python 程序:

import random
import time

username = gtk.entry.get_text("usernameimput")
password = gtk.entry.get_text("passwordimput")

odds = gtk.entry.get_text("oddsimput")
RollBelow = odds
RollAbove = 100 - odds - 0.0001

currency = gtk.entry.get_text("currencyimput")

LowerStopLimit = gtk.entry.get_text("minimumimput")

Low = "0"
High = "1"

startbet = gtk.entry.get_text("startingbetimput")
multiplyer = gtk.entry.get_text("multiplierimput")
maxbet = gtk.entry.get_text("maxbetimput")
bet = startbet

key = -1
print "Logging in..."
while key == -1:
    try:
        key = peerbetapi.__login(username, password)
    except:
        key = -1
    if key == -1:
        print "Error logging in. Retrying..."
print "Logged in..."

result = peerbetapi.__roll_dice(key, High, RollAbove,  currency, bet, random.randint(1,999999999))
startbalance = float(result["user_balance"])
Stopbot = False
while Stopbot == False:
    try:
        if float(result["game_won"]) == 0:
            # we lost so multiply the bet
            bet = "%0.8f" % (float(bet) * float(multiplyer))
            if float(bet) > float(maxbet):
                print "*** MAX BET REACHED RESETING ***"
                bet = startbet
            print "Bet: " + bet
            print "Profit: %0.8f" % (float(result["user_balance"]) - startbalance)
        else:
            # we won so reset the bet to the start bet
            bet = startbet
            print "Bet: " + bet
            print "Profit: %0.8f" % (float(result["user_balance"]) - startbalance)
        if float(result["dice_roll"]) >= 50:
            result = peerbetapi.__roll_dice(key, Low, RollBelow, currency, bet, random.randint(1,999999999))
        else:
            result = peerbetapi.__roll_dice(key, High, RollAbove, currency, bet, random.randint(1,999999999))
        print "Balance: %3.4f" % float(result["user_balance"]) + " Rolled: %06.4f" % float(result["dice_roll"]) + " Target: " + str(result["dice_target"]) + " Won: " + str(result["game_won"])
        if float(result["user_balance"]) <= float(LowerStopLimit):
            Stopbot = True
    except:
        print "Error: Last multiplyer %0.4f" % float(bet)
        time.sleep(30)
    #time.sleep(1)

最佳答案

您可以生成一个 python 进程:

Process p = Runtime.getRuntime().exec("python "+yourpythonprog+" "+yourargs);

然后使用 Process 对象读取 python 程序的输出。

关于java - Java GUI 可以控制 Python 后端吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24089806/

有关java - Java GUI 可以控制 Python 后端吗?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  5. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  6. ruby - 我可以使用 aws-sdk-ruby 在 AWS S3 上使用事务性文件删除/上传吗? - 2

    我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby-on-rails - 带 Spring 锁的 Rails 4 控制台 - 2

    我正在使用Ruby2.1.1和Rails4.1.0.rc1。当执行railsc时,它被锁定了。使用Ctrl-C停止,我得到以下错误日志:~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`gets':Interruptfrom~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`verify_server_version'from~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.

  9. ruby-on-rails - openshift 上的 rails 控制台 - 2

    我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新ruby​​gems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems

  10. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

随机推荐