JTextArea Append - java

Im woking on some code to do some computations on different types of beer. I have a main class which uses a GUI and has a JTextArea to print output. Calling append within the main class works just fine, but as soon as I try to call append from an outside class to write to the text area..no cigar..i've worked at this for awhile and simply have no clue. Quite a bit of code, but I think the fix is simple
and I guess while im at it, does it make sense to extend NewFileOpener into LagerChooser? Or should it extend jpanel?
thanks for the help!!
public class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public CustomTextArea customTextArea = new CustomTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList<String> namesForGeneration;
private boolean namesRead = false;
void displayGUI() {
JFrame frame = new JFrame("Binary Brewing! " + "Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
// customTextArea = new CustomTextArea();
customTextArea
.append(" Program progress and/or errors will display below:");
customTextArea
.append("\n"
+ "----------------------------------------------------------------------------------------------------");
customTextArea.append("\n" + "\n"
+ "To Enable Beer recipe Generation please read in Name file!" + "\n");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new NewFinalOpener().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if(namesRead == false){
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if(namesRead == false){
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if(namesRead == false){
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
public Dimension getPreferredSize() {
return (new Dimension(200, 100));
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(
fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList<String>();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
customTextArea.append("\n"
+ "Successfully read all names!" + " "
+ file + "\n");
customTextArea.append("\n" + "Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
customTextArea
.append("\n"
+ "---------------------------------------------------------");
br.close();
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, e);
}
} else {
customTextArea.append("Open command cancelled by user."
+ "\n");
}
}
if(action.equalsIgnoreCase("lager")){
customTextArea.append("\n" + "\n "+ "Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame(){
LagerChooser l1 = new LagerChooser();
}
}
class CustomTextArea extends JTextArea {
private static final int GAP = 5;
public CustomTextArea() {
setEditable(false);
setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
}
public Dimension getPreferredSize() {
return (new Dimension(800, 800));
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public void setCustomText(String text){
customTextArea.append(text);
}
}
and the class that needs to append to the JTextarea
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class LagerChooser extends NewFinalOpener{
public LagerChooser() {
}
public void tellCustom(String line){
setCustomText(line);
}
}

You can use:
public static final PrintStream OUT = System.out;
public CustomPanel() throws Throwable
{
...
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
customTextArea.append(str);
}
}));
And write to System.out. it will print to console and to textarea.
PS. Why you create custom textarea class? You should use JTextArea:
customTextArea=new JTextArea();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPrefferedSize(...);
Your code uses lot of memory, size of exported JAR isn't small for "simple program".
Optimized code:
import java.io.*;
import java.util.*;
class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public JTextArea customTextArea = new JTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList < String > namesForGeneration;
private boolean namesRead = false;
private static final PrintStream SYSOUT = System.out;
public NewFinalOpener() {
JFrame frame = new JFrame("Binary Brewing! Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPreferredSize(new Dimension(800, 800));
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
SYSOUT.write(b,offset,length);
customTextArea.append(str);
}
}));
System.setErr(System.out);
System.out.println(" Program progress and/or errors will display below:");
System.out.println("----------------------------------------------------------------------------------------------------\n");
System.out.println("To Enable Beer recipe Generation please read in Name file!");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewFinalOpener();
}
});
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
setPreferredSize(new Dimension(200, 100));
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if (namesRead == false) {
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if (namesRead == false) {
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if (namesRead == false) {
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList < String > ();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
System.out.println("Successfully read all names!" + " " + file + "\n");
System.out.println("Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
System.out.println("\n---------------------------------------------------------");
br.close();
}
} catch (Throwable f) {
f.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
} else {
System.out.println("Open command cancelled by user.");
}
}
if (action.equalsIgnoreCase("lager")) {
System.out.println("Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame() {
LagerChooser l1 = new LagerChooser();
}
}
}
class LagerChooser extends NewFinalOpener {
public LagerChooser() {}
public void tellCustom(String line) {
setCustomText(line);
}
}

Related

How to make a GUI program which iterate numbers in a file?

I want to make an GUI program which write in a file x numbers from y.
E.g: if y=103 and x=100, the output is "103 104 105 106...202"(100 numbers).
I tried this code, but when I run it and submit some numbers, the file still remain empty.
Probably the problem is at the void filein().
package me;
import java.io.FileInputStream;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class program {
static PrintStream OUT = System.out;
public static void main(String args[]) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
startGUI();
}
});
}
private static void startGUI() {
JFrame window = new JFrame();
window.setTitle("Text Writer");
{
setupWindowContent(window);
}
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
private static void setupWindowContent(JFrame window) {
JPanel content = new JPanel();
final JLabel lblEnterSmthng = new JLabel("Enter the first number and the iterate limit:");
final JTextField txtField1 = new JTextField(30);
final JTextField txtField2 = new JTextField(30);
JButton btnOk = new JButton("Ok");
final JLabel labelLastText = new JLabel();
content.add(lblEnterSmthng);
content.add(txtField1);
content.add(txtField2);
content.add(btnOk);
content.add(labelLastText);
window.setContentPane(content);
ActionListener submitAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String txt = txtField1.getText();
String txt2 = txtField2.getText();
int i = Integer.parseInt(txt);
int serii = Integer.parseInt(txt2);
if(!txt.isEmpty()){
labelLastText.setText(txt);
}
}
void filein(int i, int serii) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
out = new FileOutputStream("C:/Users/mihai/OneDrive/Desktop/Text.txt");
System.out.print(i + serii);
for(i=i;i<i+serii-1;i++) {
out.write(i);
}
}finally {
if (out != null) {
out.close();
}
}
}
};
btnOk.addActionListener(submitAction);
txtField1.addActionListener(submitAction);
txtField2.addActionListener(submitAction);
}
}
I do not know what details to give you.

Java : How to Save a File and overwrite it and display combobox strings?

I am working on a school project using BlueJay and I have created two classes in package Logic which are the Game class, and the VectorGames class.
In my package GUI, I created a class called AddGame and ViewGame class.
The issue that I have encountered is that, when I click the Save Button on Addgame, it saves the file only once. When I try to save it doesn't do or say anything it just stays there returning nothing. Another issue encountered is that on ViewGame, the gameType column is remaining empty ( this is from combo type box )
AddGame code :
package GUI;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import Logic.*;
public class AddGame extends JFrame implements ActionListener{
private JPanel north, south, east, west, center;
private JLabel titleLabel, westLabel, eastLabel;
private JTextField gameNameFld, gameKeyFld;
private JComboBox gameTypeCombo;
private JButton saveButton, clearButton;
private VectorGames vg;
public AddGame(){
super("Adding a Game");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
//north panel
north = new JPanel();
this.add(north,BorderLayout.NORTH);
titleLabel = new JLabel("Add a game below");
titleLabel.setFont(new Font("Verdana",Font.BOLD,20));
titleLabel.setForeground(Color.black);
north.add(titleLabel);
//west and east panels
west = new JPanel();
east = new JPanel();
this.add(west, BorderLayout.WEST);
this.add(east, BorderLayout.EAST);
westLabel = new JLabel(" ");
eastLabel = new JLabel(" ");
west.add(westLabel);
east.add(eastLabel);
//center panel
center = new JPanel();
this.add(center, BorderLayout.CENTER);
center.setLayout(new GridLayout(4,2,0,20));
gameNameFld = new JTextField();
gameKeyFld = new JTextField();
gameTypeCombo = new JComboBox();
gameTypeCombo.setModel(new DefaultComboBoxModel(new String[]
{"<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay"}));
center.add(createLabel("Game Name"));
center.add(gameNameFld);
center.add(createLabel("Game Key"));
center.add(gameKeyFld);
center.add(createLabel("Game Type"));
center.add(gameTypeCombo);
//south panel
south = new JPanel();
south.setLayout(new FlowLayout());
this.add(south, BorderLayout.SOUTH);
clearButton = new JButton("Clear");
south.add(clearButton);
clearButton.addActionListener(this);
saveButton = new JButton("Save");
south.add(saveButton);
saveButton.addActionListener(this);
this.setSize(300,400);
this.setLocation(50,50);
this.setVisible(true);
}
private JLabel createLabel(String title){
return new JLabel(title);
}
private void clearFields(){
gameNameFld.setText("");
gameKeyFld.setText("");
gameTypeCombo.setSelectedIndex(0);
}
private boolean validateForm(){
boolean flag = false;
if(gameNameFld.getText().equals("")||gameKeyFld.getText().equals("")||
gameTypeCombo.getSelectedIndex()==0){
flag = true;
}
return flag;
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == clearButton){
clearFields();
}
if(event.getSource() == saveButton){
if(validateForm() == true){
JOptionPane.showMessageDialog(null,"You have empty fields",
"Empty Fields", JOptionPane.ERROR_MESSAGE);
} else if(vg.checkGamebyGameKey(gameKeyFld.getText()) == true){
JOptionPane.showMessageDialog(null,"Game Key already exists!",
"Game Key Check", JOptionPane.ERROR_MESSAGE);
} else {
Game tempGame = new Game(gameNameFld.getText(),gameKeyFld.getText(),
(String)gameTypeCombo.getSelectedItem());
vg.addGame(tempGame);
vg.saveToFile();
JOptionPane.showMessageDialog(null, "Game added successfully!", "Adding a Game",
JOptionPane.INFORMATION_MESSAGE);
clearFields();
}
}
}
}
ViewGame code:
package GUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Logic.*;
public class ViewGame extends JFrame {
private JTable table;
private VectorGames vg;
public ViewGame(){
super("Viewing Games by Name");
this.setLayout(new BorderLayout());
vg = new VectorGames();
vg.readFromFile();
vg.sortGamesByName();
int numOfGames = vg.getVectorSize();
int count = 0;
Game tempGame = new Game();
String[] tableHeader = {"Game Name", "Game Type", "Game Key"};
Object [][] tableContent = new Object[numOfGames][3];
for(int i = 0; i < numOfGames; i++){
tempGame = vg.getGamesByIndex(count);
tableContent[i][0] = tempGame.getGameName();
tableContent[i][2] = tempGame.getGameType();
tableContent[i][1] = tempGame.getGameKey();
}
table = new JTable (tableContent, tableHeader);
JScrollPane scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
this.add(table.getTableHeader(), BorderLayout.NORTH);
this.add(table, BorderLayout.CENTER);
this.setSize(500,600);
this.setLocation(100,50);
this.setVisible(true);
}
}
Game code:
package Logic;
import java.io.*;
public class Game implements Serializable{ // Using serializable to allow easy save and read access
//Initializing variables related to Game
private String gameName, gameKey, gameType;
//Creating a constructor with the parameters for class Games
public Game(String gameName, String gamekey, String gameType){
setGameName(gameName);
setGameKey(gameKey);
setGameType(gameType);
}
//Setting up a parameterless constructor for class Games
public Game(){
}
public String getGameName(){//Get Method for gameName
return gameName;
}
public String getGameKey(){//Get Method for gameKey
return gameKey;
}
public String getGameType(){//Get Method for gameType
return gameType;
}
public void setGameName(String gameName){//Set Method for gameName
this.gameName = gameName;
}
public void setGameKey(String gameKey){//Set Method for gameKey
this.gameKey = gameKey;
}
public void setGameType(String gameType){//Set Method for gameType
this.gameType = gameType;
}
public String toString(){
return "Game Name : " + gameName + "\nGame Key : "
+ gameKey + "\nGame Type ; " + gameType;
}
}
VectorGames code:
package Logic;
import java.util.*;
import java.io.*;
import java.lang.*;
public class VectorGames extends IOException{
/* Add a Game, Remove a Game, getVectorGame Size, print allGamesAvailable,
* saveToFile , searchGame and return boolean literal, searchGame and return
* client object, sort games, readFromFile.
*
*/
private Vector<Game> games;
public VectorGames(){
games = new Vector<Game>();
}
//Adding a Game
public void addGame(Game game){
games.add(game);
}
public void deleteGame(Game game){
games.remove(game);
}
public int getVectorSize(){
return games.size();
}
public void clearVector(){
games.clear();
}
public void printGames(){
for(Game tempGame : games){
System.out.println(tempGame.toString());
System.out.println("");
}
}
public Game getGamesByIndex(int i){
Game tempGame = new Game();
if (i < getVectorSize()){
tempGame = games.get(i);
}
return tempGame;
}
public void sortGamesByName(){
Game currentGame = new Game();
Game nextGame = new Game();
Game tempGame = new Game();
for(int i = 0; i < getVectorSize(); i++){
for(int j = 0; j < getVectorSize()-i-1; j++){
currentGame = games.elementAt(j);
nextGame = games.elementAt(j+1);
if(currentGame.getGameName().compareTo(nextGame.getGameName())>0){
tempGame = currentGame;
games.setElementAt(nextGame, j);
games.setElementAt(tempGame, j+1);
}
}
}
}
public boolean checkGamebyGameKey(String gameKey){
boolean flag = false;
for(Game tempGames : games){
if(tempGames .getGameKey().equals(gameKey)){
flag = true;
}
}
return flag;
}
public Game accessGameByGameName(String gameName){
Game foundGameName = new Game();
for(Game tempGames: games){
if(tempGames.getGameName().equals(gameName)){
foundGameName = tempGames;
}
}
return foundGameName;
}
public void saveToFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.flush();
oos.close();
}catch (IOException ioe){
System.err.println("Cannot write to file!");
}
}
public void readFromFile(){
try{
File f = new File("C:/Users/Denis/Desktop/GameStore/Databases","gameList.obj");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
games = (Vector<Game>) ois.readObject();
ois.close();
} catch (FileNotFoundException fnfe){
System.err.println("Cannot find file!");
}catch (IOException ioe){
System.err.println("Cannot read from file!");
}catch(ClassNotFoundException cnfe){
System.err.println("Client class cannot be found!");
}
}
}
Main class: GameCenter
public class GameCenter extends JFrame {
public static void main(String... args) {
SwingUtilities.invokeLater(() -> new GameCenter().setVisible(true));
}
public GameCenter() {
super("Game Center");
init();
}
private void init() {
setLayout(new BorderLayout(5, 5));
Model model = new Model();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Add", new AddTabPanel(model));
tabbedPane.add("View", new ViewTabPanel(model));
add(tabbedPane, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 500);
setMinimumSize(new Dimension(400, 500));
setResizable(false);
}
}
Game entity:
final class Game {
private static final Pattern RECORD = Pattern.compile("(?<key>.+)\\|(?<name>.+)\\|(?<type>.+)");
private final String name;
private final String key;
private final String type;
public static Game createFromRecord(String str) {
Matcher matcher = RECORD.matcher(str);
return matcher.matches() ? new Game(matcher.group("name"), matcher.group("key"), matcher.group("type")) : null;
}
public Game(String name, String key, String type) {
this.name = name;
this.key = key;
this.type = type;
}
public String getName() {
return name;
}
public String getKey() {
return key;
}
public String getType() {
return type;
}
public String serialize() {
return String.format("%s|%s|%s", key, name, type);
}
}
Table model:
final class Model extends AbstractTableModel {
private static final long serialVersionUID = 1858846855164475327L;
private final Map<String, Game> keyGame = new TreeMap<>();
private final List<Game> data = new ArrayList<>();
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public void add(String name, String key, String type) {
keyGame.put(key, new Game(name, key, type));
fireTableDataChanged();
}
public void remove(int rowIndex) {
keyGame.remove(data.get(rowIndex).getKey());
fireTableDataChanged();
}
public void save() throws IOException {
if (file == null)
return;
try (FileWriter out = new FileWriter(file, false)) {
for (Game game : keyGame.values())
out.write(game.serialize() + '\n');
}
}
public void read() throws IOException {
if (file == null)
return;
keyGame.clear();
for (String record : Files.readAllLines(file.toPath())) {
Game game = Game.createFromRecord(record);
if (game != null)
keyGame.put(game.getKey(), game);
}
fireTableDataChanged();
}
private enum Column {
NAME("Game Name", Game::getName),
KEY("Game Key", Game::getKey),
TYPE("Game Type", Game::getType);
private final String title;
private final Function<Game, Object> get;
Column(String title, Function<Game, Object> get) {
this.title = title;
this.get = get;
}
public Object getValue(Game game) {
return get.apply(game);
}
}
// ========== AbstractTableModel ==========
#Override
public void fireTableDataChanged() {
data.clear();
data.addAll(keyGame.values());
super.fireTableDataChanged();
}
// ========== TableModel ==========
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return Column.values().length;
}
#Override
public String getColumnName(int columnIndex) {
return Column.values()[columnIndex].title;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return Column.values()[columnIndex].getValue(data.get(rowIndex));
}
}
AddGame tab panel:
final class AddTabPanel extends JPanel implements ActionListener, DocumentListener {
private final Model model;
private final JTextField nameField = new JTextField();
private final JTextField keyField = new JTextField();
private final JLabel nameLabel = new JLabel("Game Name");
private final JLabel keyLabel = new JLabel("Game Key");
private final JLabel typeLabel = new JLabel("Game Type");
private final JComboBox<String> typeCombo = createGameTypeCombo();
private final JButton openButton = new JButton("Open");
private final JButton saveButton = new JButton("Save");
private final JButton clearButton = new JButton("Clear");
public AddTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = createConstraints();
add(createTitlePanel(), gbc);
add(createMainPanel(), gbc);
add(createButtonPanel(), gbc);
gbc.weighty = 1;
add(Box.createVerticalGlue(), gbc);
onNameFieldChanged();
onKeyFieldChanged();
onTypeComboChanged();
}
private static JPanel createTitlePanel() {
JLabel label = new JLabel("Add a game below");
label.setFont(new Font("Verdana", Font.BOLD, 20));
JPanel panel = new JPanel();
panel.add(label);
return panel;
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));
panel.add(nameLabel);
panel.add(nameField);
panel.add(keyLabel);
panel.add(keyField);
panel.add(typeLabel);
panel.add(typeCombo);
return panel;
}
private static GridBagConstraints createConstraints() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
return gbc;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
panel.add(clearButton);
panel.add(saveButton);
panel.add(openButton);
return panel;
}
private static JComboBox<String> createGameTypeCombo() {
JComboBox<String> combo = new JComboBox<>();
combo.setModel(new DefaultComboBoxModel<>(new String[] { "<--Select-->", "Arcade", "Puzzle", "Adventure", "Shooter", "Roleplay" }));
return combo;
}
private void addListeners() {
clearButton.addActionListener(this);
saveButton.addActionListener(this);
openButton.addActionListener(this);
nameField.getDocument().addDocumentListener(this);
keyField.getDocument().addDocumentListener(this);
typeCombo.addActionListener(this);
}
private void validateFields() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
int type = typeCombo.getSelectedIndex();
saveButton.setEnabled(!name.isEmpty() && !key.isEmpty() && type != 0);
}
private void onNameFieldChanged() {
nameLabel.setForeground(nameField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onKeyFieldChanged() {
keyLabel.setForeground(keyField.getText().trim().isEmpty() ? Color.RED : Color.BLACK);
validateFields();
}
private void onTypeComboChanged() {
typeLabel.setForeground(typeCombo.getSelectedIndex() == 0 ? Color.RED : Color.BLACK);
validateFields();
}
private void onCleanButton() {
nameField.setText(null);
keyField.setText(null);
typeCombo.setSelectedIndex(0);
validateFields();
}
private void onSaveButton() {
String name = nameField.getText().trim();
String key = keyField.getText().trim();
String type = (String)typeCombo.getSelectedItem();
model.add(name, key, type);
if (model.getFile() == null) {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showSaveDialog(this);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
}
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
private void onOpenButton() {
JFileChooser fileChooser = new JFileChooser();
int res = fileChooser.showOpenDialog(null);
model.setFile(res == JFileChooser.APPROVE_OPTION ? fileChooser.getSelectedFile() : null);
try {
model.read();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot read file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == typeCombo)
onTypeComboChanged();
else if (e.getSource() == clearButton)
onCleanButton();
else if (e.getSource() == saveButton)
onSaveButton();
else if (e.getSource() == openButton)
onOpenButton();
}
// ========== DocumentListener ==========
#Override
public void insertUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument() == nameField.getDocument())
onNameFieldChanged();
else if (e.getDocument() == keyField.getDocument())
onKeyFieldChanged();
}
#Override
public void changedUpdate(DocumentEvent e) {
}
}
ViewGame tab panel:
final class ViewTabPanel extends JPanel implements ActionListener, PopupMenuListener {
private final Model model;
private final JTable table = new JTable();
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem deleteItem = new JMenuItem("Delete");
public ViewTabPanel(Model model) {
this.model = model;
init();
addListeners();
}
private void init() {
setLayout(new GridLayout(1, 1));
add(new JScrollPane(table));
popupMenu.add(deleteItem);
table.setComponentPopupMenu(popupMenu);
table.setAutoCreateRowSorter(true);
table.setModel(model);
table.updateUI();
}
private void addListeners() {
popupMenu.addPopupMenuListener(this);
deleteItem.addActionListener(this);
}
// ========== ActionListener ==========
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == deleteItem) {
model.remove(table.getSelectedRow());
try {
model.save();
} catch(Exception e) {
JOptionPane.showMessageDialog(this, "Cannot save file", e.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
// ========== PopupMenuListener ==========
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
if (event.getSource() == popupMenu) {
SwingUtilities.invokeLater(() -> {
int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table));
if (rowAtPoint > -1)
table.setRowSelectionInterval(rowAtPoint, rowAtPoint);
});
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent event) {
}
}

JComboBox ActionEvent performs with multiple comboboxes?

I am performing actions for 2 combo boxes which involves in changing the background color of JLabel. Here is my code,
public class JavaApplication8 {
private JFrame mainFrame;
private JLabel signal1;
private JLabel signal2;
private JPanel s1Panel;
private JPanel s2Panel;
public JavaApplication8()
{
try {
prepareGUI();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaApplication8.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws
ClassNotFoundException
{
JavaApplication8 swingControl = new JavaApplication8();
swingControl.showCombobox1();
}
public void prepareGUI() throws ClassNotFoundException
{
mainFrame = new JFrame("Signal");
mainFrame.setSize(300,200);
mainFrame.setLayout(new GridLayout(3, 0));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
signal1 = new JLabel("Signal 1",JLabel.LEFT);
signal1.setSize(100,100);
signal1.setOpaque(true);
signal2 = new JLabel("Signal 2",JLabel.LEFT);
signal2.setSize(100,100);
signal2.setOpaque(true);
final DefaultComboBoxModel light = new DefaultComboBoxModel();
light.addElement("Red");
light.addElement("Green");
final JComboBox s1Combo = new JComboBox(light);
s1Combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s1Combo.getSelectedIndex() == 0)
{
signal1.setBackground(Color.RED);
}
else
{
signal1.setBackground(Color.GREEN);
}
}
});
final JComboBox s2Combo1 = new JComboBox(light);
s2Combo1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s2Combo1.getSelectedIndex() == 0)
{
signal2.setBackground(Color.RED);
}
else
{
signal2.setBackground(Color.GREEN);
}
}
});
s1Panel = new JPanel();
s1Panel.setLayout(new FlowLayout());
JScrollPane ListScrollPane = new JScrollPane(s1Combo);
s1Panel.add(signal1);
s1Panel.add(ListScrollPane);
s2Panel = new JPanel();
s2Panel.setLayout(new FlowLayout());
JScrollPane List1ScrollPane = new JScrollPane(s2Combo1);
s2Panel.add(signal2);
s2Panel.add(List1ScrollPane);
mainFrame.add(s1Panel);
mainFrame.add(s2Panel);
String[] columnNames = {"Signal 1","Signal 2"};
Object[][] data = {{"1","1"}};
final JTable table = new JTable(data,columnNames);
JScrollPane tablepane = new JScrollPane(table);
table.setFillsViewportHeight(true);
mainFrame.add(tablepane);
mainFrame.setVisible(true);
}
}
When Executed, If I change the item from combo box 1, the 2nd combo box also performs the change. Where did I go wrong?
Yours is a simple solution: don't have the JComboBoxes share the same model. If they share the same model, then changes to the selected item of one JComboBox causes a change in the shared model which changes the view of both JComboBoxes.
I wold use a method to create your combo-jlabel duo so as not to duplicate code. For instance:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class App8 extends JPanel {
private static final int COMBO_COUNT = 2;
private static final String SIGNAL = "Signal";
private List<JComboBox<ComboColor>> comboList = new ArrayList<>();
public App8() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < COMBO_COUNT; i++) {
DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(ComboColor.values());
JComboBox<ComboColor> combo = new JComboBox<>(cModel);
add(createComboLabelPanel((i + 1), combo));
comboList.add(combo);
}
}
private JPanel createComboLabelPanel(int index, final JComboBox<ComboColor> combo) {
JPanel panel = new JPanel();
final JLabel label = new JLabel(SIGNAL + " " + index);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ComboColor cColor = (ComboColor) combo.getSelectedItem();
label.setBackground(cColor.getColor());
}
});
panel.add(label);
panel.add(combo);
return panel;
}
private static void createAndShowGui() {
App8 mainPanel = new App8();
JFrame frame = new JFrame("App8");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum ComboColor {
RED("Red", Color.RED),
GREEN("Green", Color.GREEN);
private String text;
private Color color;
public String getText() {
return text;
}
public Color getColor() {
return color;
}
private ComboColor(String text, Color color) {
this.text = text;
this.color = color;
}
#Override
public String toString() {
return text;
}
}

Sharing JPanel between client objects

I'm pretty new in Java, but I need to do something for school. I'm trying to do a Server-Client Puns game. I have Client and Server classes with chat and I have a class to drawing images on JPanel by mouse, but I have no idea how to share that picture with other Clients. Could you give me some ideas? Thanks!
Client code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.registry.*;
import java.util.*;
public class PunsClient extends JFrame {
//GUI
private JButton polacz, rozlacz;
private JPanel topPanel;
private JPanel centerPanel;
private Painter painter;
private JTextField host, wiadomosc;
private JTextArea komunikaty;
private JList<String> zalogowani;
private DefaultListModel<String> listaZalogowanych;
//Klient
private String nazwaSerwera = "localhost";
private Klient watekKlienta;
private PunsClient instancjaKlienta;
private Puns serwer;
private ClientImpl klient;
public PunsClient() {
super("Klient");
instancjaKlienta = this;
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
topPanel = new JPanel(new FlowLayout());
centerPanel = new JPanel(new FlowLayout());
painter = new Painter();
komunikaty = new JTextArea(20,12);
komunikaty.setLineWrap(true);
komunikaty.setEditable(false);
wiadomosc = new JTextField();
host = new JTextField(nazwaSerwera, 12);
polacz = new JButton("Połącz");
rozlacz = new JButton("Rozłącz");
rozlacz.setEnabled(false);
listaZalogowanych = new DefaultListModel<String>();
zalogowani = new JList<String>(listaZalogowanych);
zalogowani.setFixedCellWidth(120);
ObslugaZdarzen obsluga = new ObslugaZdarzen();
polacz.addActionListener(obsluga);
rozlacz.addActionListener(obsluga);
wiadomosc.addKeyListener(obsluga);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
rozlacz.doClick();
setVisible(false);
System.exit(0);
}
});
topPanel.add(new JLabel("Serwer RMI: "));
topPanel.add(host);
topPanel.add(polacz);
topPanel.add(rozlacz);
centerPanel.add(painter);
centerPanel.add(new JScrollPane(komunikaty), BorderLayout.EAST);
add(topPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
//add(painter, BorderLayout.CENTER);
//add(new JScrollPane(komunikaty), BorderLayout.EAST);
//add(new JScrollPane(zalogowani), BorderLayout.EAST);
add(wiadomosc, BorderLayout.SOUTH);
setVisible(true);
}
private class ObslugaZdarzen extends KeyAdapter implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Połącz")) {
wyswietlKomunikat("Łączę z: " + nazwaSerwera + "...");
polacz.setEnabled(false);
rozlacz.setEnabled(true);
host.setEnabled(false);
watekKlienta = new Klient();
watekKlienta.start();
}
if (e.getActionCommand().equals("Rozłącz")) {
listaZalogowanych.clear();
try {
serwer.opusc(klient);
} catch (Exception ex) {
System.out.println("Błąd: " + ex);
}
rozlacz.setEnabled(false);
polacz.setEnabled(true);
host.setEnabled(true);
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == 10) {
try {
serwer.wiadomosc(klient, wiadomosc.getText());
wiadomosc.setText("");
} catch (Exception ex) {
System.out.println("Błąd: " + ex);
}
}
}
}
private class Klient extends Thread {
public void run() {
try {
Registry rejestr = LocateRegistry.getRegistry(host.getText());
serwer = (Puns) rejestr.lookup("RMICzat");
wyswietlKomunikat("Połączyłem się z serwerem.");
String nick = JOptionPane.showInputDialog(null, "Podaj nick: ");
klient = new ClientImpl(instancjaKlienta, nick);
serwer.dolacz(klient);
} catch (Exception e) {
System.out.println("Błąd połączenia: " + e);
}
}
}
public void wyswietlKomunikat(String tekst) {
komunikaty.append(tekst + "\n");
komunikaty.setCaretPosition(komunikaty.getDocument().getLength());
}
public void odswiezListe(Vector<Client> lista) {
listaZalogowanych.clear();
for (Client n : lista) {
try {
listaZalogowanych.addElement(n.pobierzNicka());
System.out.println(n.pobierzNicka());
} catch (Exception e) {
System.out.println("Błąd: " + e);
}
}
}
public static void main(String[] args) {
new PunsClient();
}
}
Painter code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Painter extends JPanel {
private static final long serialVersionUID = 1L;
int xvalue = -10, yvalue = -10;
public Painter() {
setPreferredSize(new Dimension(400, 400));
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged( MouseEvent event ) {
xvalue = event.getX();
yvalue = event.getY();
repaint();
}
});
}
public void paint ( Graphics g ) {
g.fillOval( xvalue, yvalue, 10, 10 );
}
}
My suggestion would be to use a BufferedImage from which you there is a method getGraphics() I believe. Use this method as your graphics for drawing and you can then send the BufferedImage across.

how to add full image in JDialog this dialog is created by JOptionPane

my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame

Categories