import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
//import java.awt.GraphicsConfiguration;
//import java.awt.GraphicsDevice;
//import java.awt.GraphicsEnvironment;
//import java.awt.Rectangle;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class SimpleButton
{
public static void main (String[] args)
{
MyApplication app = new MyApplication ();
app.setVisible (true);
}
}
class MyApplication extends JFrame
{
public MyApplication ()
{
Toolkit tk = Toolkit.getDefaultToolkit ();
Dimension d = tk.getScreenSize();
int screenHeight = d.height;
int screenWidth = d.width;
setTitle ("Simple Button");
setSize (screenWidth/3, screenHeight/3);
setLocationRelativeTo (null);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
Container container = getContentPane ();
container.add (new ButtonPanel ());
}
private static final long serialVersionUID = 0;
}
class ButtonPanel extends JPanel
implements
ActionListener
{
public ButtonPanel ()
{
InputStream inputStream = ButtonPanel.class.getResourceAsStream ("Buttons.properties");
Properties props = new Properties ();
try
{
props.load (inputStream);
}
catch (IOException ex)
{
ex.printStackTrace ();
}
setBackground (Color.lightGray);
firstButton = new JButton (props.getProperty ("button.first"));
firstButton.setActionCommand ("command1");
firstButton.addActionListener (this);
secondButton = new JButton (props.getProperty ("button.second"));
secondButton.setActionCommand ("command2");
secondButton.addActionListener (this);
add (firstButton);
add (secondButton);
}
public void paintComponent (Graphics g)
{
super.paintComponent (g);
Graphics2D g2 = (Graphics2D) g;
if ("command1".equals (lastCommand))
{
setBackground (Color.blue);
}
if ("command2".equals (lastCommand))
{
setBackground (Color.orange);
}
}
public void actionPerformed (ActionEvent evt)
{
Object source = evt.getSource();
if (source == firstButton)
{
System.out.println ("first button");
}
else if (source == secondButton)
{
System.out.println ("second button");
}
else assert false : "unknown event source";
String command = evt.getActionCommand ();
lastCommand = command;
System.out.println (command);
repaint ();
}
private JButton firstButton = null;
private JButton secondButton = null;
private String lastCommand = null;
private static final long serialVersionUID = 0;
}
Partager