import javax.swing.*; import java.awt.*; import java.awt.event.*; class LeftRightButton extends JPanel implements ActionListener { private int x = 20; private JButton lBtn, rBtn; public LeftRightButton() { setPreferredSize(new Dimension(200, 70)); lBtn = new JButton("Left"); rBtn = new JButton("Right"); lBtn.addActionListener(this); rBtn.addActionListener(this); setLayout(new FlowLayout()); add(lBtn); add(rBtn); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("HELLO WORLD!", x, 55); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == lBtn) x -= 10; else if (source == rBtn) x += 10; repaint(); } } void main() { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("ボタン"); frame.add(new LeftRightButton()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }); }